本主題說明如何安裝和使用 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 或更新版本
Python 3.10 至 3.13 版,適用於 x64 和 ARM64 裝置。
步驟 1:安裝或更新 Windows 應用程式 SDK
模型目錄 API 包含在 Windows 應用程式 SDK 2.0.0 或更新版本的實驗版本中。
Python 繫結會利用 pywinrt 專案進行 Windows 應用程式 SDK 投影。 請確保你的 Python 安裝不是來自 Microsoft 商店(你可以從 python.org 或 winget 安裝未打包版本)。 範例依賴使用 Windows App 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# 專案必須手動參考 System.Numerics.Tensors NuGet 套件 9.0.0 版或更新版本。 如果沒有此 NuGet 套件參考,您的程式碼將會發生下列執行階段錯誤: Could not load file or assembly 'System.Numerics.Tensors, Version=9.0.0.0。
另請參閱