WinML Initialization Flow and Project Conventions
mainWhen implementing LoadModelAsync, follow the project's approved initialization pattern to ensure hardware acceleration and compatibility.
Initialization Steps:
- Register Certified EPs: Use
Microsoft.Windows.AI.MachineLearning.ExecutionProviderCatalog.GetDefault().EnsureAndRegisterCertifiedAsync()to install/register hardware acceleration packages like DirectML. Fall back to CPU if this fails. - Configure SessionOptions: Create a
SessionOptionsobject and callso.RegisterOrtExtensions()to enable necessary operators. - Apply Execution Provider (EP) Policy: Use
sampleParams.WinMlSampleOptionsto decide how to select the EP:- Policy: Use
so.SetEpSelectionPolicy(options.Policy.Value)to let the system choose the best available EP. - Explicit: Use
so.AppendExecutionProviderFromEpName(options.EpName, options.DeviceType)to request a specific provider.
- Policy: Use
- Handle Model Compilation: If
options.CompileModelis true, useso.GetCompiledModel(modelPath, options.EpName)to replace the model path with a compiled artifact for faster subsequent runs. - Create Session: Instantiate
new InferenceSession(modelPath, so). - Notify UI: Call
sampleParams.NotifyCompletion()to signal the UI that the model is ready.
// Implementation snippet for InitializeSessionAsync
var catalog = Microsoft.Windows.AI.MachineLearning.ExecutionProviderCatalog.GetDefault();
await catalog.EnsureAndRegisterCertifiedAsync();
SessionOptions so = new();
so.RegisterOrtExtensions();
if (options.Policy != null) {
so.SetEpSelectionPolicy(options.Policy.Value);
} else if (options.EpName != null) {
so.AppendExecutionProviderFromEpName(options.EpName, options.DeviceType);
if (options.CompileModel) {
modelPath = so.GetCompiledModel(modelPath, options.EpName) ?? modelPath;
}
}
_session = new InferenceSession(modelPath, so);