共用方式為


使用 Windows ML 中包含的 ONNX 執行階段選取執行提供者

Windows ML 隨附的 ONNX 執行階段可讓應用程式根據 裝置原則 或明確地設定執行提供者 (EP),以進一步控制提供者選項,以及應該使用哪些裝置。

我們建議您從明確選擇 EP 開始,以便您在結果中具有更高的可預測性。 完成這項工作後,您可以嘗試 使用裝置原則, 以自然、以結果為導向的方式選取執行提供者。

明確選擇 EP

若要明確選取 EP,請使用環境的 GetEpDevices 函式來列舉所有可用的裝置,然後選取您要使用的 EP 裝置。 然後使用 AppendExecutionProvider (C#)或 AppendExecutionProvider_V2(C++)來附加特定裝置,並為所需的 EP 提供自訂的提供者選項。 您可以在此處查看我們 所有支持的 EP

這很重要

裝置列表可動態變動:當 Windows ML 執行提供者自動更新或驅動程式更新時,EpDevice 清單可在執行時動態變動。 你的程式碼應該具備韌性,能應對新的或意外的 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 and device type
var selectedEpDevices = epDevices
    .Where(d =>
        d.EpName == "ReplaceWithExecutionProvider"
        && d.HardwareDevice.Type == OrtHardwareDeviceType.NPU)
    .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_PERFORMANCE、 、 PREFER_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 執行階段在模型上執行推論了!