Windows ML 随附的 ONNX 运行时允许应用在本地 ONNX 模型上运行推理。
创建推理会话
API 与直接使用 ONNX 运行时时相同。 例如,若要创建推理会话:
// Create inference session using compiled model
using InferenceSession session = new(compiledModelPath, sessionOptions);
// Create inference session using compiled model
Ort::Session session(env, compiledModelPath.c_str(), sessionOptions);
import onnxruntime as ort
# Create inference session using compiled model
session = ort.InferenceSession(output_model_path, sess_options=options)
建议阅读 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();
const OrtCompileApi* compileApi = ortApi.GetCompileApi();
// Prepare compilation options
OrtModelCompilationOptions* compileOptions = nullptr;
OrtStatus* status = compileApi->CreateModelCompilationOptionsFromSessionOptions(env, sessionOptions, &compileOptions);
status = compileApi->ModelCompilationOptions_SetInputModelPath(compileOptions, modelPath.c_str());
status = compileApi->ModelCompilationOptions_SetOutputModelPath(compileOptions, compiledModelPath.c_str());
// Compile the model
status = compileApi->CompileModel(env, compileOptions);
// Clean up
compileApi->ReleaseModelCompilationOptions(compileOptions);
input_model_path = "path_to_your_model.onnx"
output_model_path = "path_to_your_compiled_model.onnx"
model_compiler = ort.ModelCompiler(
options,
input_model_path,
embed_compiled_data_into_model=True,
external_initializers_file_path=None,
)
model_compiler.compile_to_file(output_model_path)
if not os.path.exists(output_model_path):
# For some EP, there might not be a compilation output.
# In that case, use the original model directly.
output_model_path = input_model_path
Note
编译可能需要几分钟才能完成。 因此,为确保任何 UI 保持响应性,请考虑在应用程序中将此作为后台操作执行。
小窍门
为了获得最佳性能,请编译模型一次,并重复使用编译的版本。 将已编译的模型存储在应用的本地数据文件夹中,以供后续运行。 请注意,对 EP 或运行时的更新可能需要重新编译。
另请参阅