我們知道,一般機(jī)器學(xué)習(xí)都會(huì)考慮使用GPU進(jìn)行加速。從iOS 12開(kāi)始,Core ML不僅支持了GPU加速,還支持了Apple Neural Engine加速。Apple Neural Engine大家可以看蘋(píng)果的官方介紹。
要使用GPU和Apple Neural Engine,我們需要在初始化模型類(lèi)對(duì)象的時(shí)候,傳入配置。我們?cè)诔跏蓟P停∕LModel類(lèi)頭文件)的時(shí)候,可以看到如下兩個(gè)方法(注意第二個(gè)方法需要iOS 12):
/// Construct a model with a default MLModelConfiguration object
+ (nullable instancetype)modelWithContentsOfURL:(NSURL *)url
error:(NSError **)error;
/// Construct a model given the location of its on-disk representation. Returns nil on error.
+ (nullable instancetype)modelWithContentsOfURL:(NSURL *)url
configuration:(MLModelConfiguration *)configuration
error:(NSError * _Nullable __autoreleasing *)error API_AVAILABLE(macos(10.14), ios(12.0), watchos(5.0), tvos(12.0));
前者是從文件路徑加載mlmodelc的方法,而后者多了一個(gè)configuration。讓我們看到這個(gè)MLModelConfiguration類(lèi):
@interface MLModelConfiguration : NSObject <NSCopying>
@property (readwrite) MLComputeUnits computeUnits;
@end
可以看到目前只有一個(gè)計(jì)算單元的配置屬性,該屬性是一個(gè)枚舉:
typedef NS_ENUM(NSInteger, MLComputeUnits) {
MLComputeUnitsCPUOnly = 0,
MLComputeUnitsCPUAndGPU = 1
,
MLComputeUnitsAll = 2
} API_AVAILABLE(macos(10.14), ios(12.0), watchos(5.0), tvos(12.0));
MLComputeUnits官方文檔對(duì)這三個(gè)配置的解釋如下:
Processing Unit Configurations:
- MLComputeAll:
The model is allowed to use all compute units available, including the neural engine.- MLComputeCPUOnly:
The model is only allowed to use the CPU.- MLComputeCPUAndGPU:
The model is allowed to use both the CPU and GPU, but not the neural engine.
翻譯一下:
- MLComputeCPUOnly:
只用CPU - MLComputeCPUAndGPU:
用CPU和GPU,不包括Apple Neural Engine - MLComputeAll:
所有能用的計(jì)算單元,包括Apple Neural Engine
我們回顧一下以往的發(fā)布會(huì),可以發(fā)現(xiàn),iPhone 8及以上版本的設(shè)備,才搭載了集成有Apple Neural Engine的芯片。
性能測(cè)試
我iPhone X和iPhone 7上進(jìn)行一些性能測(cè)試,我們的測(cè)試內(nèi)容為:
對(duì)同一張圖片,用同一個(gè)模型(這里用的是MobileNet.mlmodel),使用上述三種不同的計(jì)算單元,分別進(jìn)行1000次預(yù)測(cè)計(jì)算,統(tǒng)計(jì)總用時(shí)。
以下是我的測(cè)試結(jié)果:

結(jié)論:
- 似乎iPhone X搭載A11芯片在Core ML上并沒(méi)有起到很好的作用。不知道最新的A12是否有所改觀(guān)。
- 但是GPU加速后的運(yùn)算性能則明顯比只用CPU要好很多了。
多線(xiàn)程
既然代碼寫(xiě)到這里,我又測(cè)試了一下MLModel的線(xiàn)程安全問(wèn)題:
創(chuàng)建一個(gè)Model類(lèi)對(duì)象,然后創(chuàng)建1000個(gè)預(yù)測(cè)任務(wù),全部放到子線(xiàn)程隊(duì)列中并發(fā)計(jì)算。
測(cè)試結(jié)果發(fā)現(xiàn),在各個(gè)環(huán)境和配置下,并沒(méi)有出現(xiàn)什么問(wèn)題。我們可以猜測(cè)MLModel是線(xiàn)程安全的。
去官方文檔上找,并沒(méi)有找到多線(xiàn)程相關(guān)的說(shuō)明,因此實(shí)際上Core ML到底是否線(xiàn)程安全,還需要等官方文檔說(shuō)明。