---
title: "Load a custom ONNX speech recognizer in C#"
url: https://recursiveai.org/onespeech/cookbook/run-custom-ctc-speech-graph/
description: "Load a custom float32 ONNX or OneModel CTC speech graph in C# with OneSpeech. Runnable .NET 10 fixture, vocabulary, frame timing and shape errors."
version: "1.1.0"
---

# Load a custom ONNX speech recognizer in C#

**OneSpeech** is a free, open-source speech recognition library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneSpeech) · [GitHub](https://github.com/recursive-ai-oss/onespeech-csharp) · [Docs](https://recursiveai.org/onespeech/docs/) · [Download example (.zip)](https://recursiveai.org/onespeech/cookbook/run-custom-ctc-speech-graph/run-custom-ctc-speech-graph.zip)

OneSpeech loads local float32 ONNX or OneModel files for CTC decoding (token scores to text). This example runs a constant OneModel fixture, not a trained speech model.

```shell
dotnet add package RecursiveAI.OneSpeech
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

`ctc.onemodel` is in the zip below. For a compatible `.onnx` file, set `Path = "model.onnx"` directly; the [docs](https://recursiveai.org/onespeech/docs/custom-models/) accept “caller-supplied float32 ONNX or OneModel files” and say, “It never downloads or converts weights.”

```csharp
using OneSpeech;
using OneSpeech.Custom;

using var recognizer = new GraphSpeechRecognizer(
    [new() { Path = "ctc.onemodel",
        Channels = 3, Stride = 100 }],
    GraphFrontEnd.RawWaveform,
    new TokenVocabulary(["a", " b", ""]), blankId: 2,
    frameDuration: TimeSpan.FromTicks(62500),
    model: new ModelInfo {
        Id = "fixture", Revision = "1",
        Tier = ModelTier.Tier1,
        Source = "Original fixture",
        License = "CC0-1.0",
        Attribution = "Cookbook example" });
Console.WriteLine(recognizer.Transcribe(
    new AudioBuffer(new float[400], 16000)).Text);
```

Unzip [the example](https://recursiveai.org/onespeech/cookbook/run-custom-ctc-speech-graph/run-custom-ctc-speech-graph.zip), then `dotnet run`.

Prints:

```text
a b
```

## The full program

The zip includes `ctc.onemodel`, `wrong-rank.onemodel` and the Python script that generated them. These original numerical fixtures are dedicated to the public domain under [CC0](https://creativecommons.org/publicdomain/zero/1.0/). No voice recording or downloaded weights are used.

`ctc.onemodel` declares input `[1,1,samples]` and output `[1,4,3]`. Its output is constant, so it ignores the PCM values. The four rows of logits (raw scores) are:

```text
        a    b  blank
        9   -9    -9
       -9   -9     9
       -9    9    -9
       -9   -9     9
```

The vocabulary is `0 = "a"`, `1 = " b"`, `2 = ""` (blank). Input is 400 zero-valued mono float samples at 16 kHz, created in code. `wrong-rank.onemodel` has the same scores but declares a rank-two `[4,3]` output. The full program runs the valid graph, then exercises a stride mismatch and the invalid output rank.

```csharp
using OneSpeech;
using OneSpeech.Custom;

var info = new ModelInfo { Id = "constant-ctc", Revision = "1",
    Source = "Original numerical fixture", License = "CC0-1.0",
    Attribution = "Cookbook example", Tier = ModelTier.Tier1 };
var vocabulary = new TokenVocabulary(["a", " b", ""]);
using var recognizer = new GraphSpeechRecognizer(
    [new() { Path = "ctc.onemodel", Channels = 3, Stride = 100 }],
    GraphFrontEnd.RawWaveform, vocabulary, blankId: 2,
    frameDuration: TimeSpan.FromTicks(62500), model: info);
var audio = new AudioBuffer(new float[400], 16000);
var transcript = recognizer.Transcribe(audio);
Console.WriteLine(transcript.Text);
foreach (var word in transcript.Words)
    Console.WriteLine($"{word.Text.Trim()}: {word.Start?.TotalMilliseconds:0.00}-{word.End?.TotalMilliseconds:0.00} ms ({word.TimingMethod})");
try { recognizer.Transcribe(new AudioBuffer(new float[800], 16000)); }
catch (InvalidModelShapeException error)
{ Console.WriteLine($"Stride mismatch: {error.GetType().Name}"); }
try
{
    using var invalid = new GraphSpeechRecognizer(
        [new() { Path = "wrong-rank.onemodel", Channels = 3 }],
        GraphFrontEnd.RawWaveform, vocabulary, 2,
        TimeSpan.FromTicks(62500), info);
}
catch (InvalidModelShapeException error)
{ Console.WriteLine($"Wrong rank: {error.GetType().Name}"); }
```

`dotnet run` prints:

```text
a b
a: 0.00-6.25 ms (Native)
b: 12.50-18.75 ms (Native)
Stride mismatch: InvalidModelShapeException
Wrong rank: InvalidModelShapeException
```

Invalid declared shapes or execution-time stride mismatches throw `InvalidModelShapeException`; file and format errors propagate from OneModel.

## Variations

### Supply an unknown-token surface

In the full program, replace the vocabulary declaration with this line. The same graph now renders token 1 as `[unknown]`; it does not guess byte-fallback decoding.

```csharp
var vocabulary = new TokenVocabulary(["a", " [unknown]", ""]);
```

The first three output lines become:

```text
a [unknown]
a: 0.00-6.25 ms (Native)
[unknown]: 12.50-18.75 ms (Native)
```

## Related recipes

- [Compose a custom transcription pipeline](https://recursiveai.org/onespeech/cookbook/compose-custom-transcription-pipeline/)
- [Get word timestamps](https://recursiveai.org/onespeech/cookbook/word-timestamps/)

## The short answer

Use `GraphSpeechRecognizer` with an explicit `EncoderGraph` contract, a `TokenVocabulary` including blank, a chosen frontend and the final frame duration on the audio clock. It does not download weights, convert a checkpoint or infer a tokenizer.

The download is an interface example with constant scores. It always emits `a b` for its supported input shape, including on silence. It demonstrates loading, CTC decoding and native frame timing, not recognition accuracy. Replace it with your own lawfully obtained trained graph that matches the [custom-model contract](https://recursiveai.org/onespeech/docs/custom-models/) for actual speech recognition.

## How do I run a custom ONNX speech recognizer in C#?

First check that the graph matches the [custom graph contract](https://recursiveai.org/onespeech/docs/custom-models/). Each encoder stage has one float32 input and output with batch one. Input is `[1, channels, frames]`. Intermediate outputs are channel-major; the final CTC output is `[1, frames, vocabularySize]` raw logits, with a column for blank.

Supply the file path and declare channels, stride and receptive field rather than relying on the filename. This example uses a raw-waveform frontend, one input channel, stride 100 and the default receptive field of one sample. With 400 samples, the expected output is four frames. At 16 kHz, each 100-sample step represents 6.25 milliseconds, so the supplied `frameDuration` is 62,500 ticks.

The fixture outputs the first token, blank, the second token, then blank. CTC removes blank and collapses repeated token runs. The resulting words retain the occupied frame intervals. Supplying 800 samples to this same constant graph would require eight output frames; the four-frame output is therefore refused, not stretched to fit.

## What vocabulary does a custom CTC model need?

The vocabulary maps each output ID to its written piece. It is immutable: construction copies the pieces. Include the blank piece, normally an empty string, and pass its numeric ID separately. The blank in this example is ID 2, not ID 0.

Pieces concatenate without normalization. The leading space in `" b"` creates a word boundary; changing it to `"b"` changes the written text. Optional metaspace decoding handles U+2581 markers when enabled explicitly. A vocabulary token must not contain multiple whitespace-separated words, because word timing needs disjoint token ranges.

Unknown-token handling is also your choice. The variation gives the second token the visible surface `[unknown]`. The recognizer prints that surface; it does not reconstruct bytes or infer an unknown-token policy. The same responsibility applies to special tokens: supply the text or empty surface intended for your graph’s IDs.

## Why does my custom speech graph fail with a shape error?

`InvalidModelShapeException` covers contract violations. Declared batch, rank and channel dimensions are checked at load. Output size and temporal stride are checked during execution. The complete example includes both a rank-two output that fails at load and a valid graph whose fixed frame count fails on longer input.

A file-format or file-reading error remains the underlying OneModel loading error. Do not treat every loading failure as a shape problem or silently substitute another model: the vocabulary, frontend and timing declaration must belong to the exact graph being loaded.

Input must be finite mono PCM at 16 kHz. Raw waveform input is unchanged; normalization is not inferred. The documented mel frontends have different feature layouts, so choosing a mel frontend for a raw-waveform graph is not an interchangeable preprocessing option. Calls shorter than 400 samples produce no words. Calls longer than 30 seconds use VAD-first chunks; the tiny fixture is deliberately limited to its declared four-frame execution and is not a long-form recognizer.

Language hints are output labels only, and must be declared in the constructor before use. There is no inferred translation or language identification head. Dispose the recognizer when done; it owns the loaded graph sessions and is not thread-safe.
