Windows ML 入门

本主题介绍如何安装和使用 Windows ML 来发现、下载和注册执行提供程序(EP),以便与 Windows ML 随附的 ONNX 运行时配合使用。 Windows ML 处理包管理和硬件选择的复杂性,自动下载与设备硬件兼容的最新执行提供程序。

如果不熟悉 ONNX 运行时,建议阅读 ONNX 运行时文档。简言之,Windows ML 提供了 ONNX 运行时的共享 Windows 范围副本,以及动态下载执行提供程序(EP)的功能。

先决条件

  • 运行版本 24H2(内部版本 26100)或更高版本的 Windows 11 电脑
  • 下面所述的特定于语言的先决条件
  • .NET 6 或更高版本
  • 面向特定于 Windows 10 的 TFM(例如 net6.0-windows10.0.19041.0 或更高版本)

步骤 1:安装或更新 Windows 应用 SDK

模型目录 API 包含在 Windows 应用 SDK 2.0.0 或更高版本实验版本中。

请参阅 现有项目中的 Windows 应用 SDK ,了解如何将 Windows 应用 SDK 添加到项目,或者如果你已在使用 Windows 应用 SDK,请更新包。

步骤 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();

小窍门

在生产应用程序中,将 EnsureAndRegisterCertifiedAsync() 调用包装在 try-catch 块中以正常方式处理潜在的网络或下载失败。

后续步骤

注册执行提供程序后,即可在 Windows ML 中使用 ONNX 运行时 API! 你需要...

  1. 选择执行提供程序 - 告知运行时要使用的执行提供程序
  2. 获取模型 - 使用模型目录动态下载模型,或将其包含在本地
  3. 运行模型推理 - 编译、加载和推理模型

重要

使用 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

另请参阅