使用 Windows ML 中包含的 ONNX 运行时运行 ONNX 模型

Windows ML 随附的 ONNX 运行时允许应用在本地 ONNX 模型上运行推理。

创建推理会话

API 与直接使用 ONNX 运行时时相同。 例如,若要创建推理会话:

// Create inference session using compiled model
using InferenceSession session = new(compiledModelPath, sessionOptions);

建议阅读 ONNX 运行时文档 ,了解有关如何在 Windows ML 中使用 ONNX 运行时 API 的详细信息。 对于每个模型,模型推理代码将有所不同。

编译模型

在推理会话中使用 ONNX 模型之前,通常必须将其编译为可在设备的基础硬件上高效执行的优化表示形式。

从 ONNX 运行时 1.22 起,有一些新 API 可以更好地封装编译步骤。 ONNX 运行时编译文档中提供了更多详细信息(请参阅 OrtCompileApi 结构)。

// Prepare compilation options
OrtModelCompilationOptions compileOptions = new(sessionOptions);
compileOptions.SetInputModelPath(modelPath);
compileOptions.SetOutputModelPath(compiledModelPath);

// Compile the model
compileOptions.CompileModel();

Note

编译可能需要几分钟才能完成。 因此,为确保任何 UI 保持响应性,请考虑在应用程序中将此作为后台操作执行。

小窍门

为了获得最佳性能,请编译模型一次,并重复使用编译的版本。 将已编译的模型存储在应用的本地数据文件夹中,以供后续运行。 请注意,对 EP 或运行时的更新可能需要重新编译。

另请参阅