이 항목에서는 Windows ML과 함께 제공되는 ONNX 런타임에서 사용하기 위해 Windows ML을 설치하고 사용하여 실행 공급자(EP)를 검색, 다운로드 및 등록하는 방법을 보여 줍니다. Windows ML은 패키지 관리 및 하드웨어 선택의 복잡성을 처리하여 디바이스의 하드웨어와 호환되는 최신 실행 공급자를 자동으로 다운로드합니다.
ONNX 런타임에 익숙하지 않은 경우 ONNX 런타임 문서를 읽는 것이 좋습니다. 즉, Windows ML은 ONNX 런타임의 공유 Windows 전체 복사본과 EP(실행 공급자)를 동적으로 다운로드하는 기능을 제공합니다.
필수 조건
- Windows 10 버전 1809(빌드 17763) 이상 또는 Windows Server 2019 이상
- 아래에 표시된 언어별 필수 구성 요소
- .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 패키지를 설치하세요.
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를 사용할 준비가 된 것입니다. 다음을 수행할 수 있습니다.
-
실행 공급자 선택 - 사용하려는 실행 공급자를 런타임에 알릴 수 있습니다.
-
모델 가져오기 - 모델 카탈로그를 사용하여 동적으로 모델을 다운로드하거나 로컬로 포함
-
모델 유추 실행 - 모델 컴파일, 로드 및 유추
중요합니다
API를 Microsoft.ML.OnnxRuntime.Tensors 사용하는 C# 프로젝트는 System.Numerics.Tensors NuGet 패키지 버전 9.0.0 이상에서 수동으로 참조해야 합니다. 이 NuGet 패키지 참조가 없으면 코드에 다음과 같은 런타임 오류가 발생 Could not load file or assembly 'System.Numerics.Tensors, Version=9.0.0.0합니다.
참고하십시오