本主题介绍如何安装和使用 Windows ML 来发现、下载和注册执行提供程序(EP),以便与 Windows ML 随附的 ONNX 运行时配合使用。 Windows ML 处理包管理和硬件选择的复杂性,自动下载与设备硬件兼容的最新执行提供程序。
如果不熟悉 ONNX 运行时,建议阅读 ONNX 运行时文档。简言之,Windows ML 提供了 ONNX 运行时的共享 Windows 范围副本,以及动态下载执行提供程序(EP)的功能。
先决条件
- .NET 6 或更高版本
- 面向特定于 Windows 10 的 TFM(例如
net6.0-windows10.0.19041.0 或更高版本)
在 x64 和 ARM64 设备上,Python 版本 3.10 到 3.13。
步骤 1:安装或更新 Windows 应用 SDK
模型目录 API 包含在 Windows 应用 SDK 2.0.0 或更高版本的实验版本中。
Python 绑定利用适用于 Windows 应用 SDK 投影的 pywinrt 项目。 确保 Python 安装不是来自 Microsoft 应用商店(可以从 python.org 或通过 winget 安装未打包的版本)。 该示例依赖于使用 Windows 应用 SDK 动态依赖项 API,该 API 仅适用于未打包的应用。
请使用以下命令安装 python 包:
pip install wasdk-Microsoft.Windows.AI.MachineLearning[all] wasdk-Microsoft.Windows.ApplicationModel.DynamicDependency.Bootstrap
# The onnxruntime-winml package is not published to PyPI yet. Please install it from the ort-nightly feed
pip install --pre --index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/ORT-Nightly/pypi/simple/ --extra-index-url https://pypi.org/simple onnxruntime-winml
请确保 wasdk- 包的版本与 WindowsAppRuntime 的版本匹配。
步骤 2:下载和注册 EP
最简单的入门方法是让 Windows ML 自动发现、下载和注册所有兼容执行提供程序的最新版本。 在执行提供程序需要注册到 Windows ML 内的 ONNX 运行时,然后才能使用它们。 如果他们尚未下载,则需要先下载。 调用 EnsureAndRegisterCertifiedAsync() 将在一个步骤中执行这两项作。
using Microsoft.ML.OnnxRuntime;
using Microsoft.Windows.AI.MachineLearning;
// First we create a new instance of EnvironmentCreationOptions
EnvironmentCreationOptions envOptions = new()
{
logId = "WinMLDemo", // Use an ID of your own choice
logLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_ERROR
};
// And then use that to create the ORT environment
using var ortEnv = OrtEnv.CreateInstanceWithOptions(ref envOptions);
// Get the default ExecutionProviderCatalog
var catalog = ExecutionProviderCatalog.GetDefault();
// Ensure and register all compatible execution providers with ONNX Runtime
// This downloads any necessary components and registers them
await catalog.EnsureAndRegisterCertifiedAsync();
#include <winrt/Microsoft.Windows.AI.MachineLearning.h>
#include <winml/onnxruntime_cxx_api.h>
// First we need to create an ORT environment
Ort::Env env(ORT_LOGGING_LEVEL_ERROR, "WinMLDemo"); // Use an ID of your own choice
// Get the default ExecutionProviderCatalog
winrt::Microsoft::Windows::AI::MachineLearning::ExecutionProviderCatalog catalog =
winrt::Microsoft::Windows::AI::MachineLearning::ExecutionProviderCatalog::GetDefault();
// Ensure and register all compatible execution providers with ONNX Runtime
catalog.EnsureAndRegisterCertifiedAsync().get();
import sys
from pathlib import Path
import traceback
_winml_instance = None
class WinML:
def __new__(cls, *args, **kwargs):
global _winml_instance
if _winml_instance is None:
_winml_instance = super(WinML, cls).__new__(cls, *args, **kwargs)
_winml_instance._initialized = False
return _winml_instance
def __init__(self):
if self._initialized:
return
self._initialized = True
self._fix_winrt_runtime()
from winui3.microsoft.windows.applicationmodel.dynamicdependency.bootstrap import (
InitializeOptions,
initialize
)
import winui3.microsoft.windows.ai.machinelearning as winml
self._win_app_sdk_handle = initialize(options=InitializeOptions.ON_NO_MATCH_SHOW_UI)
self._win_app_sdk_handle.__enter__()
catalog = winml.ExecutionProviderCatalog.get_default()
self._providers = catalog.find_all_providers()
self._ep_paths : dict[str, str] = {}
for provider in self._providers:
provider.ensure_ready_async().get()
if provider.library_path == '':
continue
self._ep_paths[provider.name] = provider.library_path
self._registered_eps : list[str] = []
def __del__(self):
self._providers = None
self._win_app_sdk_handle.__exit__(None, None, None)
def _fix_winrt_runtime(self):
"""
This function removes the msvcp140.dll from the winrt-runtime package.
So it does not cause issues with other libraries.
"""
from importlib import metadata
site_packages_path = Path(str(metadata.distribution('winrt-runtime').locate_file('')))
dll_path = site_packages_path / 'winrt' / 'msvcp140.dll'
if dll_path.exists():
dll_path.unlink()
def register_execution_providers_to_ort(self) -> list[str]:
import onnxruntime as ort
for name, path in self._ep_paths.items():
if name not in self._registered_eps:
try:
ort.register_execution_provider_library(name, path)
self._registered_eps.append(name)
except Exception as e:
print(f"Failed to register execution provider {name}: {e}", file=sys.stderr)
traceback.print_exc()
return self._registered_eps
WinML().register_execution_providers_to_ort()
小窍门
在生产应用程序中,将 EnsureAndRegisterCertifiedAsync() 调用包装在 try-catch 块中以正常方式处理潜在的网络或下载失败。
后续步骤
注册执行提供程序后,即可在 Windows ML 中使用 ONNX 运行时 API! 你需要...
-
选择执行提供程序 - 告知运行时要使用的执行提供程序
-
获取模型 - 使用模型目录动态下载模型,或将其包含在本地
-
运行模型推理 - 编译、加载和推理模型
重要
使用 Microsoft.ML.OnnxRuntime.Tensors API 的 C# 项目必须手动引用版本 9.0.0 或更高版本的 System.Numerics.Tensors NuGet 包。 如果没有此 NuGet 包引用,代码将遇到以下运行时错误: Could not load file or assembly 'System.Numerics.Tensors, Version=9.0.0.0
另请参阅