---
title: "Calculate CTC loss for padded sequences in C#"
url: https://recursiveai.org/onemodel/cookbook/calculate-ctc-loss-for-padded-sequences/
description: "Calculate CTC loss on a variable-length batch in C# with OneModel. Pack the target labels and pass per-sequence frame counts so padding cannot affect the loss."
version: "1.3.0"
---

# Calculate CTC loss for padded sequences in C#

**OneModel** is a free, open-source neural-network library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneModel) · [GitHub](https://github.com/recursive-ai-oss/onemodel-csharp) · [Docs](https://recursiveai.org/onemodel/docs/) · [Download example (.zip)](https://recursiveai.org/onemodel/cookbook/calculate-ctc-loss-for-padded-sequences/calculate-ctc-loss-for-padded-sequences.zip)

CTC scores a label sequence without frame-by-frame labels. Pass valid frame counts to `Ops.CtcLoss` to exclude padding.

```shell
dotnet add package RecursiveAI.OneModel
```

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

```csharp
using RecursiveAI.OneModel.Tensors;

// 3 frames, 2 sequences, 2 classes.
float half = MathF.Log(0.5f);
using var frames = Tensor.FromSpan<float>(
    Enumerable.Repeat(half, 12).ToArray(),
    Shape.Create(3, 2, 2));
using var loss = Ops.CtcLoss(frames,
    targets: [1, 1, 1],
    inputLengths: [2, 3],
    targetLengths: [1, 2],
    reduction: CtcReduction.None);
foreach (float value in loss.Data<float>())
    Console.WriteLine(FormattableString.Invariant(
        $"{value:F6}"));
```

[The example](https://recursiveai.org/onemodel/cookbook/calculate-ctc-loss-for-padded-sequences/calculate-ctc-loss-for-padded-sequences.zip) is the full program below: unzip it and `dotnet run`. To run only the code above, paste it into Program.cs of a new `dotnet new console` project and `dotnet run`.

The input holds log-probabilities shaped `[time, batch, classes]` with class `0` as the blank by default; if you have logits, apply `Ops.LogSoftmax` along the class axis first.

Prints:

```text
0.287682
2.079442
```

## Full program

```csharp
using RecursiveAI.OneModel.Tensors;

// 3 frames, 2 sequences, 2 classes.
float half = MathF.Log(0.5f);
using var frames = Tensor.FromSpan<float>(
    Enumerable.Repeat(half, 12).ToArray(),
    Shape.Create(3, 2, 2));
using var loss = Ops.CtcLoss(frames,
    targets: [1, 1, 1],
    inputLengths: [2, 3],
    targetLengths: [1, 2],
    reduction: CtcReduction.None);
foreach (float value in loss.Data<float>())
    Console.WriteLine(FormattableString.Invariant(
        $"{value:F6}"));

// Change only the padded frame of sequence 0.
using var changed = Tensor.FromSpan<float>(
    [half, half, half, half,
     half, half, half, half,
     MathF.Log(0.99f), MathF.Log(0.01f), half, half],
    Shape.Create(3, 2, 2));
using var changedLoss = Ops.CtcLoss(changed,
    targets: [1, 1, 1], inputLengths: [2, 3],
    targetLengths: [1, 2], reduction: CtcReduction.None);
if (!loss.Data<float>().SequenceEqual(changedLoss.Data<float>()))
    throw new InvalidOperationException("Padding changed the loss.");
Console.WriteLine("Changing the padded frame leaves both losses unchanged.");
```

`dotnet run` prints:

```text
0.287682
2.079442
Changing the padded frame leaves both losses unchanged.
```

Sequence 0 uses only its first two frames; sequence 1 uses all three. The full program changes the last frame for sequence 0 and gets exactly the same losses. A length outside the tensor’s time dimension or a target count that doesn’t match the packed labels throws `ArgumentException`.

## Variations

**Return one loss for the batch.** Add this to the example to use the default mean, which divides each loss by its target length (at least one), then averages across the batch.

```csharp
using var mean = Ops.CtcLoss(frames,
    targets: [1, 1, 1], inputLengths: [2, 3],
    targetLengths: [1, 2]);
Console.WriteLine(FormattableString.Invariant(
    $"{mean.Data<float>()[0]:F6}"));
```

```text
0.663701
```

## Related recipes

- [Batch variable-width images into a tensor](https://recursiveai.org/onemodel/cookbook/batch-variable-width-image-tensors/)
- [Calculate binary cross-entropy with logits](https://recursiveai.org/onemodel/cookbook/calculate-binary-cross-entropy-from-logits/)

## The short answer

Call `Ops.CtcLoss` with a Float32 tensor shaped `[time, batch, classes]`, packed target labels, and two lengths per sequence: the number of valid input frames and the number of target labels. The tensor holds log-probabilities, not raw scores; if you start with logits, apply `Ops.LogSoftmax` along the class axis first. Pass `CtcReduction.None` for one loss per sequence. Class `0` is the blank by default; leave it out of the targets.

For example, for three frames, two sequences, and two classes, a tensor of all-zero logits gives the same uniform class probabilities as the hand-built example:

```csharp
using var logits = Tensor.Zeros(
    DType.F32, Shape.Create(3, 2, 2));
using var logProbs = Ops.LogSoftmax(logits, axis: -1);
```

Pass `logProbs` instead of `frames` to the same `CtcLoss` call.

## How does CTC loss handle padding and target lengths?

`inputLengths[b]` sets how much of the time axis to read for sequence `b`. Use the valid frame count at the **model output**, not the input sample count; an encoder may have reduced the number of steps. The example uses `[2, 3]`, so time index `2` is padding for sequence 0 but real input for sequence 1. Padding frames go at the end; a blank class within valid frames is part of the alignment, not a padding marker.

`targetLengths[b]` tells the loss how many IDs to take from the flat `targets` array. Here `[1, 2]` splits `[1, 1, 1]` into target `[1]` for sequence 0 and `[1, 1]` for sequence 1. Don’t add target padding or blank IDs to that array. CTC inserts blanks as part of its search over frame-to-label alignments.

## How is CTC loss calculated?

CTC sums the probabilities of all paths that collapse to the target, then takes the negative log of that sum. To collapse a path, merge adjacent repeats and then discard blanks. In the first two-frame example, `[0, 1]`, `[1, 0]`, and `[1, 1]` all collapse to `[1]`. Each has probability `0.25`, so the loss is `−log(0.75)`. In the second sequence, only `[1, 0, 1]` collapses to `[1, 1]` in three frames. Its probability is `0.125`, giving the second loss. See [Sequence Modeling With CTC](https://distill.pub/2017/ctc/#loss-function) for the alignment rule and [OneModel’s CTC documentation](https://recursiveai.org/onemodel/docs/ctc/) for the API.

## Why is CTC loss infinite?

A target may have no valid alignment. For example, two frames can’t produce two consecutive copies of label `1`: the path needs a third frame to separate them with a blank. If you see positive infinity, check that every sequence has at least as many valid output frames as target IDs, plus one extra frame for every adjacent repeated pair. Don’t count padding toward that minimum. `zeroInfinity: true` replaces an infinite loss with zero; it doesn’t fix the input length or make the target alignable.
