Skip to content

Add C# Windows ML samples over the CsWin32 Runtime and Task bindings - #35

Merged
Nick Eubanks (nieubank) merged 10 commits into
release/2.9-experimentalfrom
adrastogi/csharp-samples
Nov 17, 2026
Merged

Nick Eubanks (nieubank) merged 10 commits into
release/2.9-experimentalfrom
adrastogi/csharp-samples

Conversation

@adrastogi

@adrastogi adrastogi commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

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.MachineLearning package (metadata\win32\Microsoft.Windows.AI.MachineLearning.Runtime.winmd).

  • Image classification (Samples/Runtime/get-started/image-classification/csharp): the C++ sample's flow, with --device cpu|gpu|npu, --ep, --performance|--efficiency and --verbose.
  • Hello language model (Samples/Runtime/language/hello-language-model/csharp): a raw Runtime token loop over an ONNX or GGUF decoder.
  • Model-backed text generation (Samples/Tasks/model-backed/text-generation/csharp): the model-provider route (--capacity, --program-cache, --cache-weights), plus the llama.cpp route with --llama, --draft-model and --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++ shared headers.
  • build.ps1 in Runtime and Tasks builds the C# projects with dotnet build after the C++ projects. -Sample all skips them with a warning if the .NET SDK isn't installed.
  • The run scripts accept -Language cpp|csharp.
  • GetTopK in common.h now 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 webgpu pins WebGPU through IWinMLOrtCompatibility, 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/Runtime gives them an idiomatic C# surface: IDisposable objects, exceptions that keep the HRESULT, .NET names, zero-copy Span access to CPU tensors, and text generation as an IAsyncEnumerable with cancellation. All unsafe code 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 the Runtime wrapper), Samples/Runtime/shared/common.h
  • Samples/Runtime and Samples/Tasks: build.ps1, run scripts, Directory.Build.props, .slnx, READMEs
  • Samples/Directory.Packages.props (adds CsWin32 0.3.369), docs/Runtime/overview.md, docs/Runtime/tutorials/README.md

Checklist

  • I built the Runtime and Tasks samples locally (build.ps1 -Sample all, C++ and C#) with Visual Studio and the .NET 8 SDK
  • I ran the affected sample(s) end-to-end on Windows 11 (x64 and ARM64)
  • C++ changes follow the repo .clang-format
  • I updated the relevant per-sample README.md
  • I did not check in large model artifacts, build outputs, or secrets

Testing notes

Tested with Microsoft.Windows.AI.MachineLearning 2.9.31-experimental and LibLlama.Core 0.7.0.102-experimental, placed in localpackages because they weren't on nuget.org yet. Each C# run was compared with the C++ sample on the same machine.

  • x64, CPU only: both catalogs build with 0 warnings and 0 errors. Image classification and llama.cpp text generation match C++ exactly. Error exit codes match C++.
  • ARM64, NVIDIA RTX GPU (52 runs). Both catalogs build with 0 warnings and 0 errors. C# matches C++ on:
    • image classification on CPU, GPU, and GPU pinned to WebGPU (top-5 identical);
    • hello language model on CPU and GPU;
    • the GGUF model-provider route on the GPU, including the program cache and --cache-weights (cold to warm start, about 36 s to 7.5 s in both languages);
    • llama.cpp on CPU, on GPU, and with a draft model.
  • Wrapper-based samples: rerun on x64 CPU (output byte-identical to the previous C# samples) and on the ARM64 GPU, where all 20 C#/C++ comparisons matched, including hello language model with an ONNX model. Ctrl+C cancels C# text generation cleanly.
  • Not tested: NPU inference, because no NPU execution provider was available.
  • Environment note: llama.cpp on the GPU needed the CUDA backend's cuBLAS DLLs deployed next to the app, in both C++ and C#.

adrastogi and others added 7 commits November 13, 2026 11:05
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]>
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]>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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

Comment thread Samples/Runtime/build.ps1 Resolved
adrastogi and others added 2 commits November 13, 2026 15:54
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]>
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants