TensorStack.OnnxRuntime
0.16.0
Prefix Reserved
dotnet add package TensorStack.OnnxRuntime --version 0.16.0
NuGet\Install-Package TensorStack.OnnxRuntime -Version 0.16.0
<PackageReference Include="TensorStack.OnnxRuntime" Version="0.16.0" />
<PackageVersion Include="TensorStack.OnnxRuntime" Version="0.16.0" />
<PackageReference Include="TensorStack.OnnxRuntime" />
paket add TensorStack.OnnxRuntime --version 0.16.0
#r "nuget: TensorStack.OnnxRuntime, 0.16.0"
#:package TensorStack.OnnxRuntime@0.16.0
#addin nuget:?package=TensorStack.OnnxRuntime&version=0.16.0
#tool nuget:?package=TensorStack.OnnxRuntime&version=0.16.0
TensorStack.OnnxRuntime
TensorStack.OnnxRuntime is the ONNX Runtime layer for .NET, with the Vision pipelines for upscaling, interpolation, extraction, background removal and pose detection, and the LLM pipelines for text generation, speech and vision-language models.
Deprecated: ONNX Runtime DirectML has been deprecated, and there is currently no suitable replacement that works across GPU vendors. For cross-vendor GPU inference on Windows we recommend moving to one of our Vulkan backends: TensorStack.StableDiffusionCpp, TensorStack.LlamaCpp, TensorStack.AudioCpp or TensorStack.VisionCpp.
Nuget Package
It manages devices, execution providers and model sessions, and handles input type conversion and the creation, use and disposal of OrtValue objects.
Providers
Provider uses the DirectML execution provider, and initializes itself on first use.
// Best GPU
ExecutionProvider provider = Provider.GetProvider();
// By device type, or device type and id
ExecutionProvider cpuProvider = Provider.GetProvider(DeviceType.CPU);
ExecutionProvider gpuProvider = Provider.GetProvider(DeviceType.GPU, deviceId: 1);
// List devices
foreach (var device in Provider.GetDevices())
{
Console.WriteLine($"{device.Type}: {device.Name}");
}
Model Sessions
ModelSession loads an ONNX model from a ModelConfig and runs inference.
var config = new ModelConfig
{
Path = "model.onnx",
ExecutionProvider = Provider.GetProvider()
};
using (var session = new ModelSession(config))
{
ModelMetadata metadata = await session.LoadAsync();
using (var parameters = new ModelParameters(metadata))
{
// Inputs are added in model input order
parameters.AddInput(imageTensor.GetChannels(3), Normalization.ZeroToOne);
parameters.AddOutput(new[] { 1, 3, height * 4, width * 4 });
using (var results = await session.RunInferenceAsync(parameters))
{
// Read outputs
}
}
}
Vision
ONNX image and video pipelines for upscaling, frame interpolation, feature extraction (depth, edges etc), background removal and pose detection.
Every pipeline takes an image, a buffered video (VideoSequence) or a video stream (IAsyncEnumerable<VideoFrame>), so long videos can be processed frame by frame with minimal memory use.
Loading and saving media uses TensorStack.Media.
Quick Start
Upscale an image and a video using RealESR-General-4x
// 1. Create the Upscale Pipeline
using (var pipeline = UpscalePipeline.Create(new UpscalerConfig
{
ScaleFactor = 4,
Normalization = Normalization.ZeroToOne,
ExecutionProvider = Provider.GetProvider(),
Path = @"M:\Models\RealESR-General-4x\model.onnx"
}))
{
// 2. Upscale an Image
var inputImage = new ImageInput("Input.png");
var upscaledImage = await pipeline.RunAsync(new UpscaleImageOptions
{
Image = inputImage
});
await upscaledImage.SaveAsync("Output.png");
// 3. Upscale a Video (Streaming mode)
var inputStream = await VideoInputStream.CreateAsync("Input.mp4");
var upscaledVideo = pipeline.RunAsync(new UpscaleStreamOptions
{
Stream = inputStream.GetAsync()
});
await upscaledVideo.SaveAsync("Output.mp4", audioSourceFile: "Input.mp4"); // audio from the source video (optional)
}
Upscale
UpscalerConfig
Path- Path to the ONNX modelExecutionProvider- Hardware provider, see TensorStack.OnnxRuntimeScaleFactor- Upscale factor (e.g. 2x, 4x)Normalization/OutputNormalization- Input and output value range (ZeroToOneorOneToOne)Channels- Model channels (default 3)SampleSize- Fixed model input size,0for dynamic
Upscale Image
var output = await pipeline.RunAsync(new UpscaleImageOptions
{
Image = new ImageInput("Input.png")
});
await output.SaveAsync("Output.png");
Upscale Video (Buffered)
Buffers all frames in memory. Suitable for short videos, AI-generated content, low-resolution videos or GIFs.
var outputVideo = await pipeline.RunAsync(new UpscaleVideoOptions
{
Video = new VideoInput("Input.gif")
});
await outputVideo.SaveAsync("Output.mp4");
Upscale Video (Stream)
Processes frames one by one for minimal memory usage. Ideal for high-resolution or long videos.
var inputStream = await VideoInputStream.CreateAsync("Input.mp4");
var outputStream = pipeline.RunAsync(new UpscaleStreamOptions
{
Stream = inputStream.GetAsync()
});
await outputStream.SaveAsync("Output.mp4");
Tiling
Tiling processes images and frames in smaller sections instead of all at once, reducing memory use on large images and high-resolution video.
IsTileEnabled- Enable tilingMaxTileSize- The maximum size of each tile in pixels, smaller tiles use less memory but may take longerTileOverlap- The number of overlapping pixels between tiles, more overlap prevents visible seams
var output = await pipeline.RunAsync(new UpscaleImageOptions
{
Image = inputImage,
IsTileEnabled = true,
MaxTileSize = 512,
TileOverlap = 16
});
Upscale Models
Some known and tested models:
- TensorStack/Upscale-amuse
- wuminghao/swinir
- rocca/swin-ir-onnx
- Xenova/swin2SR-classical-sr-x2-64
- Xenova/swin2SR-classical-sr-x4-64
- Neus/GFPGANv1.4
Interpolation
Increases the frame rate of a video by generating frames in between.
using (var pipeline = InterpolationPipeline.Create(Provider.GetProvider()))
{
var inputVideo = new VideoInput("Input.mp4");
var outputVideo = await pipeline.RunAsync(new InterpolationVideoOptions
{
Multiplier = 3,
Video = inputVideo
});
await outputVideo.SaveAsync("Output.mp4");
}
InterpolationPipeline.Create(provider) loads Interpolation.onnx from the working directory, use InterpolationPipeline.Create(ModelConfig) for another path.
Extraction
ExtractorPipeline runs image-to-image feature models such as depth, edge or line art detection, commonly used as ControlNet inputs.
using (var pipeline = ExtractorPipeline.Create(new ExtractorConfig
{
Normalization = Normalization.ZeroToOne,
OutputNormalization = Normalization.OneToOne,
OutputChannels = 1,
ExecutionProvider = Provider.GetProvider(),
Path = @"M:\Models\Depth\model.onnx"
}))
{
var output = await pipeline.RunAsync(new ExtractorImageOptions
{
Image = new ImageInput("Input.png")
});
await output.SaveAsync("Depth.png");
}
ExtractorVideoOptions and ExtractorStreamOptions process video the same way as upscaling. Other options: IsInverted, MergeInput and tiling.
Background Removal
BackgroundPipeline uses a segmentation model to remove or isolate the background of an image.
using (var pipeline = BackgroundPipeline.Create(new ExtractorConfig
{
ExecutionProvider = Provider.GetProvider(),
Path = @"M:\Models\Background\model.onnx"
}))
{
var output = await pipeline.RunAsync(new BackgroundImageOptions
{
Mode = BackgroundMode.RemoveBackground,
Image = new ImageInput("Input.png")
});
await output.SaveAsync("Output.png");
}
Pose Detection
PosePipeline detects body poses and renders them as a pose skeleton image.
using (var pipeline = PosePipeline.Create(new ExtractorConfig
{
ExecutionProvider = Provider.GetProvider(),
Path = @"M:\Models\Pose\model.onnx"
}))
{
var output = await pipeline.RunAsync(new PoseImageOptions
{
Image = new ImageInput("Input.png"),
BodyConfidence = 0.4f,
JointConfidence = 0.1f
});
await output.SaveAsync("Pose.png");
}
PoseVideoOptions and PoseStreamOptions process video.
Combining Pipelines
Pipelines can be chained using IAsyncEnumerable streams, so a workflow such as upscaling and frame interpolation runs in a single pass without storing intermediate results in memory.
In this example the video is upscaled by 4x and its frame rate is increased by 3x:
var provider = Provider.GetProvider();
var upscaleConfig = new UpscalerConfig
{
ScaleFactor = 4,
ExecutionProvider = provider,
Normalization = Normalization.ZeroToOne,
Path = @"M:\Models\RealESR-General-4x\model.onnx"
};
using (var upscalePipeline = UpscalePipeline.Create(upscaleConfig))
using (var interpolationPipeline = InterpolationPipeline.Create(provider))
{
// Read Stream [512 x 512 @ 8fps]
var videoInput = await VideoInputStream.CreateAsync("Input.mp4");
var videoStream = videoInput.GetAsync();
// Upscale Stream
videoStream = upscalePipeline.RunAsync(new UpscaleStreamOptions
{
Stream = videoStream
});
// Interpolate Stream
videoStream = interpolationPipeline.RunAsync(new InterpolationStreamOptions
{
Multiplier = 3,
Stream = videoStream,
FrameRate = videoInput.FrameRate,
FrameCount = videoInput.FrameCount
});
// Save Stream [2048 x 2048 @ 24fps]
await videoStream.SaveAsync("Output.mp4");
}
LLM
ONNX pipelines for small language, vision and speech models: text generation, speech recognition, text to speech, image captioning/OCR/detection and summarization, with greedy and beam search decoding.
For GGUF language models with tool calls and image/audio input see TensorStack.LlamaCpp.
Loading and saving images and audio uses TensorStack.Media.
Pipelines
| Pipeline | Models | Use | Model files |
|---|---|---|---|
LlamaPipeline |
Llama 3.2 | Text generation | model.onnx, tokenizer.json |
Phi3Pipeline |
Phi-3 mini, medium | Text generation | model.onnx, tokenizer.json (or tokenizer.model) |
WhisperPipeline |
Whisper tiny to large-v3, turbo | Speech recognition and translation | encoder_model.onnx, decoder_model_merged.onnx, tokenizer.json (or vocab.json + merges.txt + tokenizer_config.json) |
SupertonicPipeline |
Supertonic, Supertonic 3 | Text to speech | duration_predictor.onnx, text_encoder.onnx, vector_estimator.onnx, vocoder.onnx, unicode_indexer.json, voice_styles/*.json |
FlorencePipeline |
Florence-2 base, large | Captioning, OCR, object detection, grounding and segmentation | vision_encoder.onnx, embed_tokens.onnx, encoder_model.onnx, decoder_model_merged.onnx, tokenizer.json (or vocab.json + merges.txt + tokenizer_config.json) |
SummaryPipeline |
T5 | Text summarization | encoder_model.onnx, decoder_model_merged.onnx, tokenizer.json (or spiece.model) |
Model sizes (layers, heads, cache dimensions, mel bins) are read from the ONNX models, the Create model type is only a fallback.
Tokenizers are read from the Hugging Face tokenizer.json when the model folder has one, falling back to the older vocabulary/merges or SentencePiece files.
Execution Providers
Each Create has an overload taking a provider per model. Run vision and audio encoders on the GPU and language model decoders on the CPU, DirectML returns incorrect tokens for some decoders.
var gpu = Provider.GetProvider(DeviceType.GPU);
var cpu = Provider.GetProvider(DeviceType.CPU);
var pipeline = WhisperPipeline.Create(gpu, cpu, "M:\\Models\\Whisper-Base", WhisperType.Base);
Decoding
Each text pipeline has two RunAsync overloads:
GenerateOptions(WhisperOptions,FlorenceOptions) returns a singleGenerateResultusing greedy decodingSearchOptions(WhisperSearchOptions,FlorenceSearchOptions) returns aGenerateResult[], best first, using beam search
| Option | Description |
|---|---|
MinLength / MaxLength |
The generated length in tokens |
Beams |
Number of beams for beam search |
TopK / TopP / Temperature |
Beam search candidate sampling |
LengthPenalty |
Beam score length penalty (1 = none, higher favours longer results) |
NoRepeatNgramSize |
Blocks a repeat of any n-gram of this size, 0 to disable |
EarlyStopping |
None, BestBeam or BeamCount |
Seed |
Random seed for beam search sampling, negative for random |
GenerateResult.Score is the sum of the token log probabilities. Progress callbacks report the text as it is generated, IsReset is set when the best beam changes and the full text is reported again.
Llama
var provider = Provider.GetProvider(DeviceType.CPU);
using (var pipeline = LlamaPipeline.Create(provider, "M:\\Models\\Llama-3.2-1B-Instruct"))
{
var result = await pipeline.RunAsync(new GenerateOptions
{
Prompt = "<|start_header_id|>user<|end_header_id|>\n\nWhat is an apple?<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n",
MaxLength = 200,
MinLength = 0
});
Console.WriteLine(result.Result);
}
BOS is added to the prompt, generation stops at <|eot_id|>, <|eom_id|> or <|end_of_text|>.
GetLastHiddenStateAsync returns the prompt's last hidden state for use as a text encoder.
Phi-3
var provider = Provider.GetProvider(DeviceType.CPU);
using (var pipeline = Phi3Pipeline.Create(provider, "M:\\Models\\Phi-3-medium-128k-instruct", PhiType.Medium))
{
var results = await pipeline.RunAsync(new SearchOptions
{
Prompt = "<|user|>\nWhat is an apple?<|end|>\n<|assistant|>\n",
Beams = 3,
TopK = 3,
MaxLength = 200,
MinLength = 0
});
foreach (var result in results)
Console.WriteLine(result.Result);
}
Whisper
var gpu = Provider.GetProvider(DeviceType.GPU);
var cpu = Provider.GetProvider(DeviceType.CPU);
using (var pipeline = WhisperPipeline.Create(gpu, cpu, "M:\\Models\\Whisper-Base", WhisperType.Base))
{
var result = await pipeline.RunAsync(new WhisperOptions
{
Task = TaskType.Transcribe,
Language = LanguageType.EN,
AudioInput = await AudioInput.CreateAsync("Speech.mp3"), // 16 kHz mono
MinLength = 0,
MaxLength = 448,
NoRepeatNgramSize = 0
});
Console.WriteLine(result.Result);
}
- Audio must be 16 kHz,
AudioInput.CreateAsyncloads at 16 kHz by default, other audio can be converted withaudioTensor.Resample(16000) - Long audio is split into chunks of up to
ChunkSizeseconds (max 30) at the quietest point near each boundary TaskType.Translatetranslates to English- The mel filters are computed, large-v3 and turbo use 128 mel bins (read from
preprocessor_config.jsonor the model)
Supertonic
var provider = Provider.GetProvider(DeviceType.GPU);
using (var pipeline = SupertonicPipeline.Create("M:\\Models\\Supertonic", provider))
{
var audio = await pipeline.RunAsync(new SupertonicOptions
{
TextInput = "On a quiet morning in the old town, a clockmaker named Ellis unlocked his tiny shop.",
VoiceStyle = "Female1",
Language = "en", // Supertonic 3, null for Supertonic 1
Steps = 5,
Speed = 1f
});
await audio.SaveAsync("Output.wav");
}
Text is split into sentences of up to 300 characters (120 for Korean) with SilenceDuration seconds between them. pipeline.VoiceStyles lists the available voices.
Florence-2
var gpu = Provider.GetProvider(DeviceType.GPU);
var cpu = Provider.GetProvider(DeviceType.CPU);
using (var pipeline = FlorencePipeline.Create(gpu, cpu, gpu, gpu, "M:\\Models\\Florence-2-large", FlorenceType.Large))
{
var result = await pipeline.RunAsync(new FlorenceOptions
{
TaskType = TaskType.OD,
Image = new ImageInput("Image.png"),
MinLength = 0,
MaxLength = 1024
});
foreach (var coordinate in result.CoordinateResults)
Console.WriteLine($"{coordinate.Label}: {coordinate.CoordinateBox}");
}
- Text tasks (
CAPTION,DETAILED_CAPTION,MORE_DETAILED_CAPTION,OCR) returnResult - Region tasks (
OD,DENSE_REGION_CAPTION,REGION_PROPOSAL,CAPTION_TO_PHRASE_GROUNDING,OCR_WITH_REGIONetc) returnCoordinateResultsin source image pixels - Region input tasks (
REGION_TO_CATEGORY,REGION_TO_DESCRIPTION,REGION_TO_OCR,REGION_TO_SEGMENTATION) takeRegion CAPTION_TO_PHRASE_GROUNDING,OPEN_VOCABULARY_DETECTIONandREFERRING_EXPRESSION_SEGMENTATIONtakePrompt
Summary
var gpu = Provider.GetProvider(DeviceType.GPU);
var cpu = Provider.GetProvider(DeviceType.CPU);
using (var pipeline = SummaryPipeline.Create(gpu, cpu, "M:\\Models\\text_summarization"))
{
var result = await pipeline.RunAsync(new GenerateOptions
{
Prompt = "summarize: " + text,
MinLength = 10,
MaxLength = 200,
NoRepeatNgramSize = 3
});
Console.WriteLine(result.Result);
}
T5 models expect the task prefix (summarize: ) on the prompt.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0-windows10.0.17763 is compatible. |
-
net10.0-windows10.0.17763
- Microsoft.ML.OnnxRuntime.DirectML (>= 1.24.4)
- Microsoft.ML.OnnxRuntime.Managed (>= 1.30.0)
- Microsoft.ML.Tokenizers (>= 3.0.0)
- SkiaSharp (>= 4.155.0)
- TensorStack.Common (>= 0.16.0)
NuGet packages (2)
Showing the top 2 NuGet packages that depend on TensorStack.OnnxRuntime:
| Package | Downloads |
|---|---|
|
TensorStack.OnnxRuntime.Vision
Image and video upscaling for .NET using ONNX Runtime. |
|
|
TensorStack.OnnxRuntime.LLM
Text generation, speech recognition, text to speech and vision-language pipelines for .NET using ONNX Runtime. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated | |
|---|---|---|---|
| 0.16.0 | 146 | 11/30/2026 | |
| 0.15.3 | 130 | 11/27/2026 | |
| 0.15.1 | 141 | 11/21/2026 | |
| 0.15.0 | 138 | 11/18/2026 | |
| 0.14.14 | 139 | 11/17/2026 | |
| 0.14.13 | 136 | 11/16/2026 | |
| 0.14.12 | 138 | 11/15/2026 | |
| 0.14.11 | 132 | 11/15/2026 | |
| 0.14.10 | 140 | 11/14/2026 | |
| 0.14.9 | 137 | 11/13/2026 | |
| 0.14.8 | 133 | 11/10/2026 | |
| 0.14.7 | 131 | 11/8/2026 | |
| 0.14.6 | 139 | 11/5/2026 | |
| 0.14.5 | 158 | 11/1/2026 | |
| 0.14.4 | 210 | 10/29/2026 | |
| 0.14.3 | 146 | 10/28/2026 | |
| 0.14.2 | 188 | 10/20/2026 | |
| 0.14.1 | 175 | 10/16/2026 | |
| 0.13.13 | 163 | 10/11/2026 | |
| 0.13.12 | 154 | 10/10/2026 |