Post not yet marked as solved
Click to stop watching this thread.
You have stopped watching this post. Click to start watching again.
Post marked as unsolved with 5 replies, 0 views
Replied In
How to release memory leaked by CoreML Model
It seems that if I compile DeeplabV3FP16 model as objc class, the memory leak disappears, while as swift class, the memory leaks.
My comparison codes as below
Objc version
@implementation ViewController
(void)dealloc
{
		[DeepLabV3Generator destroy];
}
(void)viewDidLoad {
		[super viewDidLoad];
		// Do any additional setup after loading the view.
		
		
		NSString *name = [NSString stringWithFormat:@"DeeplabV3-%tu", nameIndex];
		nameIndex ++;
		CIImage *image = [[CIImage alloc]initWithImage:[UIImage imageNamed:name]];
		CVPixelBufferRef pb;
		CVPixelBufferCreate(kCFAllocatorDefault, image.extent.size.width, image.extent.size.height, kCVPixelFormatType_32BGRA, NULL, &pb);
		[CIContext.context render:image toCVPixelBuffer:pb];
		
		[DeepLabV3Generator.si loadDeeplabV3From:pb];
		
		CVPixelBufferRelease(pb);
}
#import "DeepLabV3Generator.h"
@implementation DeepLabV3Generator
static DeepLabV3Generator* sharedInstance = nil;
(DeepLabV3Generator*)si{
		if(sharedInstance != nil){
				return sharedInstance;
		}
		static dispatch_once_t onceToken;
		dispatch_once(&onceToken, ^{
				sharedInstance = [[DeepLabV3Generator alloc]init];
		});
		
		return sharedInstance;
}
(void)destroy{
		sharedInstance = nil;
}
(instancetype)init
{
		self = [super init];
		if (self) {
				NSError *error = nil;
				MLModelConfiguration *config = [MLModelConfiguration new];
				self.v3 = [[DeepLabV3FP16 alloc]initWithConfiguration:config error:&error];
		}
		return self;
}
(MLMultiArray *)loadDeeplabV3From:(CVPixelBufferRef)pixeBuffer{
		NSError *error = nil;
		DeepLabV3FP16Output *output = [_v3 predictionFromImage:pixeBuffer error:&error];
		if (error) {
				NSLog(@"error %@",error.localizedDescription);
		}
		return output.semanticPredictions;
}
Swift verisoin
@objc class DeepLabV3Generator: NSObject {
		private static var sharedInstance : DeepLabV3Generator?
		@objc class func si() -> DeepLabV3Generator { // change class to final to prevent override
				guard let uwShared = sharedInstance else {
						sharedInstance = DeepLabV3Generator()
						return sharedInstance!
				}
				return uwShared
		}
		@objc class func destroy() {
				sharedInstance = nil
		}
		let v3 : DeepLabV3FP16
		
		private override init() {
				let config = MLModelConfiguration()
				config.computeUnits = .all
				v3 = try! DeepLabV3FP16(configuration: config)
		}
		@objc func loadDeeplabV3(from pixelBuffer:CVPixelBuffer) -> MLMultiArray? {
				let output = try! v3 .prediction(image: pixelBuffer)
				return output.semanticPredictions
		}
}