运行 coreml 在后台时出错:Error computing NN outputs error

Error when running coreml in the background: Error computing NN outputs error

我是 运行 一个来自 keras 的 mlmodel iPhone 6。预测经常失败并出现错误 Error computing NN outputs。有谁知道可能是什么原因,如果有什么我可以做的吗?

do {
    return try model.prediction(input1: input)
} catch let err {
    fatalError(err.localizedDescription) // Error computing NN outputs error
}

编辑: 我试过 apple's sample project 那个在后台工作所以它似乎特定于我们的项目或模型类型。

我自己也在相似的 "seemingly random" 次遇到了同样的错误。一些调试跟踪确定它是由应用程序有时在发送到后台时尝试加载其 coreml 模型,然后在重新加载到前台时崩溃或冻结引起的。

消息 Error computing NN outputs error 之前是:

Execution of the command buffer was aborted due to an error during execution. Insufficient Permission (to submit GPU work from background) (IOAF code 6)

我不需要(或不希望)在应用程序处于后台时使用该模型,因此我检测到应用程序何时进入/退出后台,设置标志并在尝试之前使用保护语句调用模型。

  1. 检测何时使用 AppDelegate.swift 文件中的 applicationWillResignActive 进入后台并设置 Bool 标志,例如appInBackground = true。有关详细信息,请参阅此内容:

  2. 检测何时应用re-enters前台在同一个AppDelegate.swift文件中使用applicationDidBecomeActive,并重置标志appInBackground = false

  3. 然后在调用模型的函数中,就在调用模型之前,使用如下语句:

    guard appInBackground == false else { return } // new line to add guard let model = try? VNCoreMLModel(for modelName.model) else { fatalError("could not load model") // original line to load model

我怀疑这是最优雅的解决方案,但它对我有用。

我还没有确定为什么有时会尝试在后台加载模型。

在您 link 的 Apple 示例中,看起来他们的应用程序只调用模型来响应用户输入,因此它永远不会尝试在后台加载模型。因此,我的情况有所不同......可能还有你的情况?

最后我们设置usesCPUOnly标志就够了。 iOS 似乎禁止在后台使用 GPU。 Apple 实际上也在他们的 documentation 中写到了这一点。要指定此标志,我们不能再使用生成的模型 class,而是必须调用原始 coreml classes。我可以想象这会在未来的版本中发生变化。下面的代码片段取自生成的模型 class,但添加了指定的 MLPredictionOptions

let options = MLPredictionOptions()
options.usesCPUOnly = true // Can't use GPU in the background

// Copied from from the generated model class
let input = model_input(input: mlMultiArray)
let output = try generatedModel.model.prediction(from: input, options: options)
let result = model_output(output: output.featureValue(for: "output")!.multiArrayValue!).output