Retrieved article excerpt
Open article · Retrieved 2026-10-30T21:24:14.000602+00:00
[Fast forced alignment: a waveform aligned to the words “The statues there are broken,” with “statues” highlighted.](https://bryanthornbury.com/posts/fast-forced-alignment/)
# Fast Forced Aligner
Read the blog post: [Fast Forced Alignment: Finding Where the Words Go](https://bryanthornbury.com/posts/fast-forced-alignment/).
**Turn CTC frame scores and a known transcript into batched GPU alignments.**
`fast_forced_aligner` takes your model's log probabilities and transcript token
IDs, then returns a token label and score for every audio frame. Use your existing
CTC model, batch recordings of different lengths without padding, and keep the
results on the GPU. Both an optimized alignment kernel and conventional CTC
dynamic programming are included behind the same Python API.
The package provides forced alignment from existing CTC emissions. Acoustic
inference belongs to the caller's model; the examples use stock Hugging Face
Transformers models to produce those emissions.
On our ten-workload benchmark suite, with **prevalidated inputs**, optimized
alignment is **11.50× faster than corrected ctc-forced-aligner CPU8**
and **208.18× faster than k2 CUDA**.
Optimized alignments match conventional DP on all 3,482
distinct benchmark inputs; [adversarial near-tie cases can differ](https://github.com/brthor/fast-forced-aligner#accuracy-relative-to-conventional-dp).
[Install](https://github.com/brthor/fast-forced-aligner#install-with-pip) · [Quick start](https://github.com/brthor/fast-forced-aligner#align-ctc-emissions) ·
[Throughput](https://github.com/brthor/fast-forced-aligner#higher-throughput-loops) ·
[Coming from TorchAudio](https://github.com/brthor/fast-forced-aligner#coming-from-torchaudio) ·
[How it works](https://github.com/brthor/fast-forced-aligner#how-the-speedups-work) · [Benchmarks](https://github.com/brthor/fast-forced-aligner#performance) ·
[Accuracy](https://github.com/brthor/fast-forced-aligner#accuracy-relative-to-conventional-dp) · [Citation](https://github.com/brthor/fast-forced-aligner#citation) ·
[GitHub](https://github.com/brthor/fast-forced-aligner)
[Total alignment time across ten workloads. Our optimized and conventional kernels appear first in green at 30.4 ms and 58.9 ms. NeMo uses the independently confirmed bucketed-B64 configurations. Preparation is included; inputs are prevalidated. Lower time is better.](https://github.com/brthor/fast-forced-aligner/blob/master/assets/performance.png)
## Install with pip
With Python 3.11+, Git, a compatible NVIDIA driver, and the CUDA 12.8 development
toolkit installed:
```
python -m pip install torch==2.8.0 --index-url https://download.pytorch.org/whl/cu128
python -m pip install "fast_forced_aligner @ git+https://github.com/brthor/fast-forced-aligner.git"
```
The package is not yet on PyPI; this installs directly from GitHub. For a
reproducible installation, append `@FULL_COMMIT_SHA` to the `.git` URL, replacing
`FULL_COMMIT_SHA` with the commit you want. CUDA
source is bundled and compiled on first use, requiring **`nvcc` and a C++ compiler**.
PyTorch's CUDA runtime alone is insufficient. The
[stock-model Docker example](https://github.com/brthor/fast-forced-aligner/blob/master/examples/transformers_ctc/README.md) provides the
toolchain in a PyTorch development image. See [build requirements](https://github.com/brthor/fast-forced-aligner#cuda-build-and-environment)
for the tested environment and cache configuration.
## Align CTC emissions
```
import torch
from fast_forced_aligner import align
# Replace these illustrative tensors with your model's log probabilities and
# transcript token IDs. Each list element is one unpadded recording.
emissions = [torch.randn(n, 32, device="cuda").log_softmax(-1) for n in (500, 320)]
targets = [
torch.tensor(ids, dtype=torch.int64, device="cuda")
for ids in ([3, 7, 7, 12], [4, 9, 2])
]
result = align(emissions, targets, blank_id=0)
result.raise_for_status()
path = result.paths[0] # CUDA int64 [500], including blanks and repetitions
# Select conventional full-record DP through the same interface.
reference = align(emissions, targets, blank_id=0, mode="conventional")
reference.raise_for_status()
```
Inputs must be contiguous CUDA FP32 emissions and CUDA int64 target IDs on one
device. Use the blank ID and transcript tokenizer from the model that produced
the emissions. Outputs retain blanks and repeated labels; each `result.paths[i]`
is a view of that recording's frame labels. This quick start uses default input checks.
**Try real audio:** the [stock Transformers example](https://github.com/brthor/fast-forced-aligner/blob/master/examples/transformers_ctc/README.md)
installs the package with pip in a PyTorch development image, uses the standard
`facebook/wav2vec2-base-960h` model, streams LibriSpeech examples, and reports
alignment rows/second:
```
git clone https://github.com/brthor/fast-forced-aligner.git
cd fast-forced-aligner
./examples/transformers_ctc/run.sh build
./examples/transformers_ctc/run.sh --rows 4
```
Docker with NVIDIA GPU support is required. See the
[Dockerfile](https://github.com/brthor/fast-forced-aligner/blob/master/examples/transformers_ctc/Dockerfile) for installation and
[align.py](https://github.com/brthor/fast-forced-aligner/blob/master/examples/transformers_ctc/align.py) for the model-to-alignment flow.
Model inference is outside its alignment timer.
## Higher-throughput loops
For throughput, submit several batches before checking their statuses. This
example keeps up to eight results pending and copies their statuses to the CPU
together, so there is one completion check per window instead of one per call.
It still checks every result before yielding it, including the final partial window.
```
from collections.abc import Iterable, Iterator
from itertools import islice, repeat
import torch
from fast_forced_aligner import AlignmentBatch, align
Batch = tuple[list[torch.Tensor], list[torch.Tensor]]
def align_stream(batches: Iterable[Batch], *, blank_id: int = 0) -> Iterator[AlignmentBatch]:
"""Align batches on one CUDA device and stream, deferring host checks."""
batches = iter(batches)
while window := list(islice(batches, 8)):
pending = [
align(emissions, targets, blank_id=blank_id)
for emissions, targets in window
]
statuses = torch.cat([result.status for result in pending]).cpu().tolist()
failed = [i for i, status in enumerate(statuses) if status != 0]
if failed:
raise RuntimeError(f"Alignment failed at recording indices {failed} within this window")
yield from pending
# Demonstration: reuse the quick-start inputs.
for result in align_stream(repeat((emissions, targets), 16)):
paths = result.paths # Consume the checked CUDA paths here.
```
In a real pipeline, replace `repeat(...)` with your batch iterator. Default target
validation runs on the GPU without a host wait; invalid targets and insufficient
frame counts are reported by the same status check as alignment failures. Use
`check_inputs=False` only when your pipeline already guarantees the
[input contract](https://github.com/brthor/fast-forced-aligner#validation-and-repeated-processing) for **every batch**.
Keep inputs and processing on the same CUDA device and stream for this example.
Larger batches and fewer host waits can improve throughput, at the cost of more
pending output memory and later error reporting. Eight calls per window is an
illustrative choice, not a measured optimum.
## Coming from TorchAudio
Both functions below accept the same list of CUDA emissions and target tensors,
and return one `(labels, scores)` pair per recording, each with shape `[frames]`.
TorchAudio 2.8's `functional.forced_align` supports one recording per call, so
its function loops over the batch; Fast Forced Aligner processes the batch in
one call. The [TorchAudio 2.8 API is deprecated](https://docs.pytorch.org/audio/2.8/generated/torchaudio.functional.forced_align.html);
this comparison is for users familiar with that interface. It requires TorchAudio
2.8.0 built for the same PyTorch/CUDA environment; the core package does not
depend on TorchAudio.
```
import torch
import torchaudio
from fast_forced_aligner import align
def align_ours(
emissions: list[torch.Tensor], targets: list[torch.Tensor], blank_id: int = 0,
) -> list[tuple[torch.Tensor, torch.Tensor]]:
result = align(emissions, targets, blank_id=blank_id)
result.raise_for_status()
return list(zip(result.paths, result.scores.split(result.lengths), strict=True))
def align_torchaudio(
emissions: list[torch.Tensor], targets: list[torch.Tensor], blank_id: int = 0,
) -> list[tuple[torch.Tensor, torch.Tensor]]:
results = []
for log_probs, tokens in zip(emissions, targets, strict=True):
labels, scores = torchaudio.functional.forced_align(
log_probs.unsqueeze(0), tokens.unsqueeze(0), blank=blank_id,
)
results.append((labels[0], scores[0]))
return results
emissions = [torch.randn(n, 32, device="cuda").log_softmax(-1) for n in (500, 320)]
targets = [
torch.tensor(ids, dtype=torch.int64, device="cuda")
for ids in ([3, 7, 7, 12], [4, 9, 2])
]
ours = align_ours(emissions, targets)
theirs = align_torchaudio(emissions, targets)
print(ours[0][0].shape, theirs[0][0].shape) # both torch.Size([500])
```
The keyword `blank` becomes `blank_id`. Each unpadded tensor supplies its own
length, so our API needs no separate length arrays. Both outputs retain blanks
and repetitions, and scores are the selected input emission at each frame.
Matching output formats do not promise identical paths near numerical ties;
see [accuracy](https://github.com/brthor/fast-forced-aligner#accuracy-relative-to-conventional-dp). To select our full-record
DP kernel, add `mode="conventional"` to the `align` call.
## How the speedups work
There are two contributions: efficient batched CUDA execution, and an optimized
algorithm that can avoid much of the full-record DP work. Both kernels start
from the same emissions and transcript, construct the CTC topology, and return
complete frame paths and selected scores.
| Mode | Computation | When to use it |
| --- | --- | --- |
| `optimized` (default) | Parallel chunks, greedy shortcuts, boundary repair, and full-record DP fallback | High aggregate throughput; review the numerical differences below |
| `conventional` | Full-record CTC Viterbi DP with optimized CUDA execution | The ordinary full-record FP32 recurrence is required |
### Conventional: efficient execution of full-record DP
The transcript is expanded with blanks into a CTC state sequence. The kernel
advances the full recurrence through the recording, then recovers the frame path.
It batches variable-length recordings on the GPU, reads their resident emissions,
and uses specialized CTC kernels with parallel traceback for long recordings.
The specialized implementation avoids constructing a general-purpose FSA graph.
This execution layer is useful on its own: conventional mode processes the
benchmark suite in **58.91 ms**, versus **349.97 ms** for corrected CPU8 and
**6,337.72 ms** for k2 CUDA, with the timing scope described below.
The large speedups over external toolkits therefore reflect implementation and
batching improvements as well as reduced DP work. They are not a measurement of
the chunking algorithm's contribution alone.
### Optimized: skip work when chunks can be joined
Optimized mode solves relaxed **128-frame chunks in parallel**. Eligible greedy
paths bypass chunk DP; other chunks use the recurrence. The kernel checks joins,
repairs connected incompatible regions, and falls back to full-record DP when
needed. Bounded repair, overlapping fallback work, and reuse of compatible
complete DP frontiers reduce repeated computation. Both modes use parallel
long-path traceback where applicable.
On the complete benchmark suite, this gives a further **1.93× speedup ov