Repository navigation
Add C# Windows ML samples over the CsWin32 Runtime and Task bindings - #35
Merged
Nick Eubanks (nieubank) merged 10 commits intoNov 17, 2026
Merged
Conversation
Rebase the C# image classification sample onto Windows ML 2.8, whose pinned package ships the Runtime Win32 metadata, and add two more C# samples. - Shared C# helpers (Samples/Runtime/shared/csharp): one props file for every C# sample, plus helpers matching the C++ ones for --device cpu|gpu|npu, --ep (Windows ML execution-provider catalog + ONNX Runtime registration), --performance/--efficiency (DXCore adapter ranking), and --verbose (ONNX Runtime logging and IWinMLStageExecutionDiagnostics). - Image classification (C#): now at parity with the C++ sample's options and output, and built by build.ps1 -Sample all. - Hello LanguageModel (C#): ONNX decoder with state pairs or GGUF through llama.cpp, streaming a greedy reply. - Model-backed text generation Task (C#): model provider route and explicit llama.cpp route with optional speculative decoding. - Run scripts take -Language cpp|csharp; GetTopK orders ties by class index. Co-authored-by: Copilot App <[email protected]>
build.ps1 in Samples\Runtime and Samples\Tasks builds C++ projects first and C# projects with dotnet build; -Sample all skips the C# samples with a warning when the .NET SDK is missing. Document the .NET 8 prerequisite, skip adapters whose hardware ID can't be read, and guard the IUnknown argument helper. Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
CsWin32 0.3.369 (microsoft/CsWin32#1870) generates IUnknown* parameters from the Windows SDK metadata as pointers, so the samples pass the DXCore adapter to CreateExecutionTargetFromAdapter directly. The docs now require 0.3.369 or later. Co-authored-by: Copilot App <[email protected]>
Pin --ep webgpu through IWinMLOrtCompatibility like the other providers, since the Runtime now acquires and registers WebGPU for the pinned target, and add --cache-weights to the C# text generation sample. Co-authored-by: Copilot App <[email protected]>
The C++ sample returns the failing HRESULT from wmain. The C# sample now does the same, and the shared C# provider helpers throw the HRESULTs the C++ helpers return (ERROR_NOT_SUPPORTED and ERROR_NOT_FOUND). Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
There was a problem hiding this comment.
🟡 Changes recommended
Both build scripts treat the presence of dotnet.exe as SDK availability, causing runtime-only machines to fail during C# builds instead of skipping them with a warning.
1 open issue
What changed in this PR
Adds C# counterparts to three Windows ML samples, demonstrating direct use of CsWin32-generated Runtime and Task bindings alongside the existing C++ and Python examples.
Changes:
- Adds image classification, raw language-model generation, and model-backed text generation samples.
- Shares C# device selection, execution-provider registration, diagnostics, and COM ownership helpers.
- Integrates C# builds and language selection into scripts, updates documentation, and makes C++ top-k ties deterministic.
| File | Description |
|---|---|
Samples/Tasks/windows-ml-tasks.slnx |
Includes the C# project and README. |
Samples/Tasks/run_model_text_generation.ps1 |
Adds C# language selection. |
Samples/Tasks/run_llama_text_generation.ps1 |
Routes C# runs through --llama. |
Samples/Tasks/README.md |
Documents C# build requirements. |
Samples/Tasks/model-backed/text-generation/README.md |
Introduces the C# sample. |
Samples/Tasks/model-backed/text-generation/csharp/task-model-text-generation-csharp.csproj |
Configures the project and llama.cpp dependency. |
Samples/Tasks/model-backed/text-generation/csharp/README.md |
Explains both generation routes and usage. |
Samples/Tasks/model-backed/text-generation/csharp/Program.cs |
Implements streaming generation, caching, cancellation, and speculative decoding. |
Samples/Tasks/model-backed/text-generation/csharp/NativeMethods.txt |
Selects Task and tokenizer bindings. |
Samples/Tasks/model-backed/README.md |
Lists C# support and run commands. |
Samples/Tasks/Directory.Build.props |
Limits native settings to non-C# projects. |
Samples/Tasks/build.ps1 |
Adds .NET builds for the C# sample. |
Samples/Runtime/windows-ml-runtime.slnx |
Includes both C# Runtime projects. |
Samples/Runtime/shared/csharp/WinMLSamples.CSharp.props |
Shares dependencies, architecture, output paths, and bindings configuration. |
Samples/Runtime/shared/csharp/StageDiagnostics.cs |
Reports stage placement and provider diagnostics. |
Samples/Runtime/shared/csharp/SampleAssets.cs |
Locates downloaded model assets. |
Samples/Runtime/shared/csharp/README.md |
Documents shared helpers and binding requirements. |
Samples/Runtime/shared/csharp/NativeMethods.txt |
Selects shared Runtime, DXCore, and COM bindings. |
Samples/Runtime/shared/csharp/NativeMethods.json |
Configures unmanaged bindings and preserved HRESULTs. |
Samples/Runtime/shared/csharp/ExecutionTargets.cs |
Ranks adapters and creates execution targets. |
Samples/Runtime/shared/csharp/ExecutionProviders.cs |
Prepares catalog providers and verbose logging. |
Samples/Runtime/shared/csharp/DeviceOptions.cs |
Parses shared device and provider options. |
Samples/Runtime/shared/csharp/ComObjects.cs |
Manages owned COM interface references. |
Samples/Runtime/shared/common.h |
Orders equal top-k scores by index. |
Samples/Runtime/run_image_classification.ps1 |
Adds C# language selection. |
Samples/Runtime/run_hello_language_model.ps1 |
Adds C# language selection. |
Samples/Runtime/README.md |
Lists the new C# Runtime samples. |
Samples/Runtime/language/hello-language-model/README.md |
Introduces C# build and run commands. |
Samples/Runtime/language/hello-language-model/csharp/README.md |
Documents the decoder flow and requirements. |
Samples/Runtime/language/hello-language-model/csharp/Program.cs |
Handles options and generation results. |
Samples/Runtime/language/hello-language-model/csharp/NativeMethods.txt |
Selects schema, state, and tokenizer bindings. |
Samples/Runtime/language/hello-language-model/csharp/LanguageModel.cs |
Implements model loading and greedy token generation. |
Samples/Runtime/language/hello-language-model/csharp/hello-language-model-csharp.csproj |
Configures the project and llama.cpp dependency. |
Samples/Runtime/get-started/image-classification/README.md |
Introduces the C# classifier. |
Samples/Runtime/get-started/image-classification/csharp/README.md |
Documents bindings, devices, and usage. |
Samples/Runtime/get-started/image-classification/csharp/Program.cs |
Implements image decoding, inference, and prediction ranking. |
Samples/Runtime/get-started/image-classification/csharp/NativeMethods.txt |
Selects image-tensor and WIC bindings. |
Samples/Runtime/get-started/image-classification/csharp/image-classification-csharp.csproj |
Configures the C# classifier project. |
Samples/Runtime/Directory.Build.props |
Separates native settings from C# projects. |
Samples/Runtime/build.ps1 |
Adds .NET builds for C# Runtime samples. |
Samples/Directory.Packages.props |
Pins the CsWin32 dependency. |
docs/Runtime/tutorials/README.md |
Adds C# SDK prerequisites. |
docs/Runtime/overview.md |
Updates binding requirements and sample availability. |
Review effort: Balanced
The .NET runtime alone also installs dotnet.exe. The build scripts now look for a .NET 8 or later SDK with dotnet --list-sdks, so -Sample all skips the C# samples with a warning on runtime-only machines. Co-authored-by: Copilot App <[email protected]>
The C# samples called the Runtime C API through raw CsWin32 bindings, so their code read like interop: factory functions with pointer out parameters, unsafe blocks, and hand-mapped HRESULT checks. Add a source-only wrapper under Samples/Runtime/shared/csharp/Runtime that gives the API an idiomatic C# surface over the same bindings and the published package: - IDisposable objects with deterministic release; objects a property returns stay owned by their parent. - Exceptions that keep the HRESULT; success codes never throw. - .NET names, strings, and spans. - Zero-copy access to CPU tensors through TensorLock<T>, with a read-only span for read locks and Commit for writes to device tensors. - DXCore adapter ranking and execution target helpers. - Text generation as an IAsyncEnumerable with cancellation, run on a dedicated session thread, plus an allocation-free synchronous loop. All unsafe code stays inside the wrapper. It is sample code, not a supported API. Its names follow .NET conventions so the samples could move to a C# projection with few changes if one ships. Port the image classification, Hello LanguageModel, and text generation samples to the wrapper. Their options, output, and exit codes are unchanged. Image decoding uses Windows.Graphics.Imaging. Tested on x64 CPU and on an ARM64 NVIDIA GPU against the C++ samples: image classification on CPU, GPU, and pinned WebGPU; Hello LanguageModel with GGUF and ONNX models; model-provider text generation with a program cache; and llama.cpp with and without a draft model. NPU wasn't tested. Co-authored-by: Copilot App <[email protected]>
5 tasks done
Picks up the ONNX Runtime WinML CG execution provider sample and the pin to Windows ML 2.9.36 experimental. Samples/Runtime/build.ps1 keeps the C# sample entries and adds onnx-runtime-winmlcgep to the sample list. Co-authored-by: Copilot App <[email protected]>
Nick Eubanks (nieubank)
approved these changes
Nov 17, 2026
Merged
5 tasks done
5 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

Summary
Adds C# versions of three Windows ML samples. They call the Runtime and Task APIs through the C# bindings that CsWin32 generates from the Win32 metadata in the
Microsoft.Windows.AI.MachineLearningpackage (metadata\win32\Microsoft.Windows.AI.MachineLearning.Runtime.winmd).Samples/Runtime/get-started/image-classification/csharp): the C++ sample's flow, with--device cpu|gpu|npu,--ep,--performance|--efficiencyand--verbose.Samples/Runtime/language/hello-language-model/csharp): a raw Runtime token loop over an ONNX or GGUF decoder.Samples/Tasks/model-backed/text-generation/csharp): the model-provider route (--capacity,--program-cache,--cache-weights), plus the llama.cpp route with--llama,--draft-modeland--device.Shared pieces:
Samples/Runtime/shared/csharp: build settings, DXCore adapter ranking, execution-provider registration through the Windows ML catalog, stage diagnostics, and COM ownership helpers. These mirror the C++sharedheaders.build.ps1in Runtime and Tasks builds the C# projects withdotnet buildafter the C++ projects.-Sample allskips them with a warning if the .NET SDK isn't installed.-Language cpp|csharp.GetTopKincommon.hnow breaks ties by index, so C# and C++ output compare deterministically.The samples require CsWin32 0.3.369 or later. Earlier versions projected
IUnknown*parameters from the Windows SDK metadata by value (microsoft/CsWin32#1874).The C# matches the 2.9 C++ samples:
--ep webgpupins WebGPU throughIWinMLOrtCompatibility, and image classification exits with the failing HRESULT.The samples don't call the generated bindings directly. A source-only wrapper in
Samples/Runtime/shared/csharp/Runtimegives them an idiomatic C# surface:IDisposableobjects, exceptions that keep the HRESULT, .NET names, zero-copySpanaccess to CPU tensors, and text generation as anIAsyncEnumerablewith cancellation. Allunsafecode stays inside the wrapper. It's sample code, not a supported API.Related issue
None.
Affected samples
Samples/Runtime/get-started/image-classification/csharp(new)Samples/Runtime/language/hello-language-model/csharp(new)Samples/Tasks/model-backed/text-generation/csharp(new)Samples/Runtime/shared/csharp(new, including theRuntimewrapper),Samples/Runtime/shared/common.hSamples/RuntimeandSamples/Tasks:build.ps1, run scripts,Directory.Build.props,.slnx, READMEsSamples/Directory.Packages.props(adds CsWin32 0.3.369),docs/Runtime/overview.md,docs/Runtime/tutorials/README.mdChecklist
build.ps1 -Sample all, C++ and C#) with Visual Studio and the .NET 8 SDK.clang-formatREADME.mdTesting notes
Tested with Microsoft.Windows.AI.MachineLearning 2.9.31-experimental and LibLlama.Core 0.7.0.102-experimental, placed in
localpackagesbecause they weren't on nuget.org yet. Each C# run was compared with the C++ sample on the same machine.--cache-weights(cold to warm start, about 36 s to 7.5 s in both languages);