使用 Windows ML 中包含的 ONNX 运行时选择执行提供程序

Windows ML 随附的 ONNX 运行时允许应用基于 设备策略 或显式配置执行提供程序(EP),从而更好地控制提供程序选项和使用哪些设备。

建议从显式选择 EP 开始,以便可以在结果中具有更大的可预测性。 完成此作后,可以尝试 使用设备策略 以自然、面向结果的方式选择执行提供程序。

显式选择 EP

若要显式选择 EP,请使用环境的 GetEpDevices 函数枚举所有可用设备,然后选择要使用的 EP 设备。 然后使用 AppendExecutionProvider (C#) 或 AppendExecutionProvider_V2 (C++) 追加特定设备,并向所需的 EP 提供自定义提供程序选项。 可 在此处查看所有受支持的 EP

using Microsoft.ML.OnnxRuntime;
using System;
using System.Linq;
using System.Collections.Generic;

// Assuming you've created an OrtEnv named 'ortEnv'
// 1. Enumerate devices
var epDevices = ortEnv.GetEpDevices();

// 2. Filter to your desired execution provider
var selectedEpDevices = epDevices
    .Where(d => d.EpName == "ReplaceWithExecutionProvider")
    .ToList();

if (selectedEpDevices.Count == 0)
{
    throw new InvalidOperationException("ReplaceWithExecutionProvider is not available on this system.");
}

// 3. Configure provider-specific options (varies based on EP)
// and append the EP with the correct devices (varies based on EP)
var sessionOptions = new SessionOptions();
var epOptions = new Dictionary<string,string>{ ["provider_specific_option"] = "4" };
sessionOptions.AppendExecutionProvider(ortEnv, new[] { selectedEpDevices.First() }, epOptions);

浏览 受支持 EP 文档中的所有可用 EP。有关 EP 选择的更多详细信息,请参阅 ONNX 运行时 OrtApi 文档

使用设备策略进行执行提供程序选择

除了显式选择 EP 之外,还可以使用设备策略,这是一种自然的、面向结果的方式,用于指定希望 AI 工作负载如何运行。 为此,请使用 SessionOptions.SetEpSelectionPolicy传入 OrtExecutionProviderDevicePolicy 值。 可以使用多种值进行自动选择,例如MAX_PERFORMANCEPREFER_NPUMAX_EFFICIENCY等等。 有关可以使用的其他值,请参阅 ONNX OrtExecutionProviderDevicePolicy 文档

// Configure the session to select an EP and device for MAX_EFFICIENCY which typically
// will choose an NPU if available with a CPU fallback.
var sessionOptions = new SessionOptions();
sessionOptions.SetEpSelectionPolicy(ExecutionProviderDevicePolicy.MAX_EFFICIENCY);

后续步骤

选择执行提供程序后,即可 使用 ONNX Runtime 在模型上运行推理