Macos Catalina
xcode 11.3
Недавно я столкнулся со странной проблемой утечки памяти при использовании MLModel. Я поместил следующий псевдокод.
// prediction class
class Prediction {
public:
Prediction(const std::string &mlmodelc_file);
~Prediction();
void RunPrediction();
private:
MLPredictionOptions *options_;
MLModelConfiguration *config_;
MLModel *mlmodel_;
}
Prediction::Prediction() {
// set configuration
options_ = [[MLPredictionOptions alloc] init];
config_ = [[MLModelConfiguration alloc] init];
options_.usesCPUOnly = false;
config_.computeUnits = MLComputeUnitsAll;
// load mlmodelc file
NSError *error = nil;
NSString *model_path_nsstring = [NSString stringWithUTF8String:mlmodelc_file.c_str()];
NSURL *compiled_model_url = [NSURL fileURLWithPath:model_path_nsstring isDirectory:YES];
mlmodel_ = [MLModel modelWithContentsOfURL:compiled_model_url configuration:config_ error:&error];
}
Prediction::~Prediction() {
}
void Prediction::RunPrediction() {
NSError *error = nil;
@autoreleasepool {
[mlmodel_ predictionFromFeatures:model_input options:options_ error:&error];
}
}
// There is no memory leakage, if I just create the prediction once, and run the prediction for a loop.
int main(int argc, char **argv) {
std::shared_ptr<Prediction> pred = std::make_shared<Prediction>(mlmodelc_file);
for (int i = 0; i < 1000; ++i) {
pred->RunPrediction();
}
return 0;
}
// But if I put the creation in the loop, memory leakage occurs.
int main(int argc, char **argv) {
for (int i = 0; i < 1000; ++i) {
std::shared_ptr<Prediction> pred = std::make_shared<Prediction>(mlmodelc_file);
pred->RunPrediction();
}
return 0;
}
MLPredictionOptions, MLModelConfiguration и MLModel - это объекты AR C. Они должны автоматически выпускаться через каждые l oop. Но похоже, что они не выпускаются автоматически. Я включил AR C в xcode. Но объем памяти все равно увеличивается с 200 МБ до 2 ГБ и более.