Metadata-Version: 2.4
Name: kaldi-rust
Version: 0.1.0a5
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: 3
Requires-Dist: montreal-forced-aligner==3.4.4 ; extra == 'mfa'
Requires-Dist: pgvector ; extra == 'mfa'
Requires-Dist: zstandard>=0.22 ; extra == 'mfa'
Requires-Dist: numpy ; extra == 'torch'
Requires-Dist: torch>=2 ; extra == 'torch'
Provides-Extra: mfa
Provides-Extra: torch
License-File: LICENSE
License-File: licenses/Kaldi-COPYING.txt
License-File: licenses/Kaldi-port-notices.txt
License-File: licenses/OpenFst-COPYING.txt
License-File: licenses/Rust-dependencies.txt
License-File: licenses/Rust-Std-COPYRIGHT.html
Summary: Rust implementations of Kaldi speech recognition training, decoding and alignment tools
License-Expression: Apache-2.0
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM

# kaldi-rust

kaldi-rust packages Rust implementations of Kaldi speech tools as a Python wheel. It supports transcript alignment with Montreal Forced Aligner (MFA), GMM acoustic model training, basic chain TDNN training, and speech recognition with a word-search graph.

## Contents

- [Align speech with Montreal Forced Aligner](#align-speech-with-montreal-forced-aligner)
  - [Install the wheel and MFA](#1-install-the-wheel-and-mfa)
  - [Prepare a recording and transcript](#2-prepare-a-recording-and-transcript)
  - [Get the acoustic model and dictionary](#3-get-the-acoustic-model-and-dictionary)
  - [Run alignment and read the TextGrid](#4-run-alignment-and-read-the-textgrid)
- [Install the standalone Kaldi tools](#install-the-standalone-kaldi-tools)
- [Train a chain TDNN on CPU or GPU](#train-a-chain-tdnn-on-cpu-or-gpu)
- [Supported workflows](#supported-workflows)
- [Compatibility milestones](#compatibility-milestones)
- [Related implementations](#related-implementations)
- [Speech recognition experiments](#speech-recognition-experiments)
- [License](#license)

## Align speech with Montreal Forced Aligner

This walkthrough aligns the spoken sentence “Where is my brother now?” and produces a Praat TextGrid with a start and end time for each word and phone. MFA reads the corpus and exports the TextGrid. kaldi-rust compiles the transcript graph and aligns it against acoustic scores from a pretrained English GMM. You can run the example without training a model.

### 1. Install the wheel and MFA

The checked-in wheel and automatic MFA runtime target **Apple Silicon macOS with native CPython 3.12** for this walkthrough. Start in a terminal with Git and uv installed. uv can fetch the requested Python version. [Install uv](https://docs.astral.sh/uv/getting-started/installation/)

```sh
git clone https://github.com/byseon/kaldi-rust.git
cd kaldi-rust
uv venv --python 3.12 .venv
source .venv/bin/activate
uv pip install './dist/kaldi_rust-0.1.0a5-1-cp310-abi3-macosx_11_0_arm64.whl[mfa]'
kaldi-rust-mfa-runtime -- mfa version
```

The last command downloads and verifies the native bindings on first use, caches them for later runs, and prints `3.4.4`. The wheel supplies the Kaldi command-line tools. For other platforms, use a host-compatible build in a working MFA 3.4.4 environment with Kalpy and Pynini. [Runtime and offline installation](docs/mfa.md#runtime)

### 2. Prepare a recording and transcript

Keep the environment active. The following commands download the Mini LibriSpeech development archive (126 MB), extract one 2.04-second recording, and write its transcript. Run the remaining steps from `mfa-demo/`. [Mini LibriSpeech on OpenSLR](https://www.openslr.org/31/)

```sh
mkdir -p mfa-demo/corpus/1272
cd mfa-demo
clip=1272-135031-0012
curl -fL -o dev-clean-2.tar.gz https://www.openslr.org/resources/31/dev-clean-2.tar.gz
tar -xOf dev-clean-2.tar.gz "LibriSpeech/dev-clean-2/1272/135031/$clip.flac" > "corpus/1272/$clip.flac"
printf '%s\n' 'where is my brother now' > "corpus/1272/$clip.lab"
```

For your own recordings, put each speaker in a subdirectory of `corpus/`. Pair each WAV or FLAC file with a plain-text transcript of what was said, for example `corpus/alex/greeting.wav` and `corpus/alex/greeting.lab`.

### 3. Get the acoustic model and dictionary

Download MFA's English (US) ARPA v3.0.0 acoustic model. Leave the ZIP intact. The dictionary below covers all five words and includes alternative pronunciations for “is” and “where”. Each entry uses a tab between the word and its space-separated ARPAbet phones. [Acoustic model release](https://github.com/MontrealCorpusTools/mfa-models/releases/tag/acoustic-english_us_arpa-v3.0.0)

```sh
curl -fL -o english_us_arpa.zip \
  https://github.com/MontrealCorpusTools/mfa-models/releases/download/acoustic-english_us_arpa-v3.0.0/english_us_arpa.zip

printf '%b\n' \
  'brother\tB R AH1 DH ER0' \
  'is\tIH0 Z' 'is\tIH1 Z' \
  'my\tM AY1' \
  'now\tN AW1' \
  'where\tHH W EH1 R' 'where\tW EH1 R' > english.dict
```

For a different transcript, supply pronunciations for its words using the acoustic model's phone set. For another language, use a dictionary and acoustic model for that language.

### 4. Run alignment and read the TextGrid

Pass the corpus directory, pronunciation dictionary, acoustic model ZIP, and output directory in that order. The Rust corpus command uses GMM scoring by default.

```sh
kaldi-rust-mfa-corpus-align corpus english.dict english_us_arpa.zip grids --num_jobs 1 --single_speaker
```

Open the exported `.TextGrid` alongside the recording in Praat to inspect the `words` and `phones` tiers, or print the word intervals in seconds with the installed Python environment.

```sh
python - <<'PYTHON'
from pathlib import Path
from praatio import textgrid

path = Path("grids/1272/1272-135031-0012.TextGrid")
grid = textgrid.openTextgrid(str(path), includeEmptyIntervals=False)
print(path)
for start, end, word in grid.getTier("words").entries:
    print(f"{start:.2f}  {end:.2f}  {word}")
PYTHON
```

The script prints the TextGrid path followed by the start time, end time, and word for each interval.

```text
grids/1272/1272-135031-0012.TextGrid
0.52  0.86  where
0.86  1.01  is
1.01  1.12  my
1.12  1.42  brother
1.42  1.89  now
```

For multiple speakers, keep the per-speaker directories and omit `--single_speaker`. To align with the project's basic chain TDNN, add `--chain-model /path/to/final.raw` and supply the MFA archive with the transition model, tree and phone IDs used to train that network. The MFA guide also covers model export and the single-recording command. [MFA guide](docs/mfa.md)

## Install the standalone Kaldi tools

From a checkout on Apple Silicon macOS, install the prebuilt wheel in a fresh Python environment.

```sh
uv venv --python 3.12
uv pip install ./dist/kaldi_rust-0.1.0a5-1-cp310-abi3-macosx_11_0_arm64.whl
uv run --no-sync compute-mfcc-feats --help
```

For command-line use only, a matching prebuilt wheel can also be installed into uv's isolated tool environment. The following command uses Apple Silicon macOS.

```sh
uv tool install --python 3.12 ./dist/kaldi_rust-0.1.0a5-1-cp310-abi3-macosx_11_0_arm64.whl
kaldi-rust-train-chain --help
```

To rebuild from source, install a Rust toolchain and run `uv build --wheel`. The wheel contains the Rust extension and Kaldi-style executable entry points. A matching prebuilt wheel installs with uv or pip without a compiler, a Kaldi installation or Conda. The development builds exercised here use Apple Silicon and CPython. Publishing tested wheels on PyPI for multiple operating systems remains a release milestone.

## Train a chain TDNN on CPU or GPU

On **Apple Silicon macOS**, the [GPU-enabled wheel](dist/kaldi_rust-0.1.0a5-1-cp310-abi3-macosx_11_0_arm64.whl) includes native Metal training through wgpu. From the repository root, install it in a Python environment and check that the trainer lists `--gpu-backend`.

```sh
uv venv --python 3.12 .venv
source .venv/bin/activate
uv pip install ./dist/kaldi_rust-0.1.0a5-1-cp310-abi3-macosx_11_0_arm64.whl
kaldi-rust-train-chain --help
```

To train with PyTorch MPS in the same environment, install the wheel's optional `torch` extra.

```sh
uv pip install './dist/kaldi_rust-0.1.0a5-1-cp310-abi3-macosx_11_0_arm64.whl[torch]'
```

Build **1** in the filename identifies the GPU-enabled wheel. If you already have the earlier `0.1.0a5` wheel installed, add `--reinstall-package kaldi-rust` to the install command. Linux and Windows users need a build for their platform. PyTorch CUDA also requires a CUDA-enabled PyTorch installation. [PyTorch installation selector](https://pytorch.org/get-started/locally/)

Given a prepared mini LibriSpeech `s5` directory, choose one of these commands. Each writes its trained Kaldi model to `final.raw` in the experiment directory.

| Training device | Command |
| --- | --- |
| CPU (default) | `kaldi-rust-train-chain /path/to/s5 exp/chain-cpu` |
| Native Rust with wgpu (Metal or Vulkan) | `kaldi-rust-train-chain /path/to/s5 exp/chain-wgpu --gpu-backend wgpu` |
| NVIDIA GPU with PyTorch CUDA | `kaldi-rust-train-chain /path/to/s5 exp/chain-cuda --gpu-backend torch --torch-device cuda` |
| Apple GPU with PyTorch MPS | `kaldi-rust-train-chain /path/to/s5 exp/chain-mps --gpu-backend torch --torch-device mps` |

The basic TDNN trainer sends forward and backward matrix multiplications to the selected GPU. The LF-MMI graph calculation runs on CPU. Check the training log or the `device` field in `result.json` to see which device ran. An explicit backend requires a usable GPU. Add `--use-gpu=optional` to allow a CPU fallback when the device is unavailable. Both backends were exercised on an Apple M4 Pro. [GPU training results](egs/mini_librispeech/chain/README.md#selecting-a-device)

The shell recipe accepts the same training options. For an existing mini LibriSpeech `s5` experiment with features and monophone alignments, run it from the checkout.

```sh
. .venv/bin/activate
./egs/mini_librispeech/chain/run.sh /path/to/s5 exp/chain_tdnn
```

From a pinned upstream source checkout and a download cache, the full driver prepares the data and alignments with the Rust wheel and then trains the network.

```sh
./egs/mini_librispeech/run.sh /path/to/kaldi-source /path/to/corpus /path/to/new-experiment
```

The default recipe trained on 500 real utterances over two epochs. The frame-averaged LF-MMI increased from −1.402817 to −0.588534 after reloading the Kaldi-readable raw network. The [chain guide](egs/mini_librispeech/chain/README.md) covers settings, supported example formats and a short eight-recording run. The [benchmark](docs/mini-librispeech.md) distinguishes this basic architecture from upstream stage 9.

## Supported workflows

The wheel has run the original mini-LibriSpeech recipe through monophone, delta-triphone, LDA+MLLT and speaker-adaptive GMM training on CPU. Monophone, triphone and LDA+MLLT alignments each cover all 1,519 training utterances. The Rust graph tools compile a pronunciation lexicon and ARPA trigram into a word-search HCLG for the wheel's trained models. The acceptance runner guards the Kaldi command names so an installed C++ executable cannot silently supply a missing Rust command. See the [CPU results and reproduction commands](docs/mini-librispeech.md).

| Function | Implemented surface |
| --- | --- |
| Feature extraction and storage | MFCCs, compressed and uncompressed binary feature archives, SCP offsets, per-speaker CMVN, normalization and delta features. |
| Language models and graphs | ARPA backoff grammars, constant ARPA compilation, lexicon disambiguation, transcript-to-HMM training graph compilation, HCLG word-search graph construction and FST stochasticity checks. |
| Chain TDNN training | LF-MMI numerator and denominator forward–backward, phone n-gram estimation, denominator and normalization FSTs, frame and minibatch training, and text/binary raw networks for the single-input affine/ReLU/affine topology. |
| Acoustic model training | Monophone initialization, phonetic clustering and decision trees, Gaussian mixture splitting, transition and acoustic re-estimation, context-dependent alignment conversion, spliced features, LDA, MLLT and fMLLR. |
| Alignment and recognition | Transcript-constrained Viterbi alignment, word and phone CTM intervals, GMM word recognition using the graph’s pronunciation lexicon and language model, word lattices, language-model rescoring and word-error scoring. |

The [command inventory](docs/kaldi-commands.md) tracks individual Kaldi programs, and the [recipe catalog](docs/recipes.md) lists tested upstream workflows. The original YesNo driver also trained and decoded with the wheel on 8 kHz audio. The catalog includes the exact split, scoring and invoked commands. [YesNo and other upstream drivers](docs/recipes.md)

Online recognition, general nnet3 networks, full upstream chain recipes and many other Kaldi commands still need implementation and testing. The native CPU reference and wheel results are reported separately in the [benchmark](docs/mini-librispeech.md).

With a prepared static lexicon and grammar, the Python API builds the word-search graph in memory. Its inputs and output use Kaldi and OpenFst binary formats.

```python
from pathlib import Path
from kaldi_rust import build_hclg

lang = Path("data/lang_test_tgsmall")
model = Path("exp/tri1")
graph = build_hclg(
    (lang / "L_disambig.fst").read_bytes(),
    (lang / "G.fst").read_bytes(),
    (model / "tree").read_bytes(),
    (model / "final.mdl").read_bytes(),
    list(map(int, (lang / "phones/disambig.int").read_text().split())),
)
Path("HCLG.fst").write_bytes(graph)
```

With a fixed English triphone GMM, the Rust-built graph matched the 486,109,477-byte C++ graph byte for byte. Starting from the audio, both recognizers independently produced identical word sequences and word and phone timestamps for all 8,423 LibriSpeech recordings tested. Of these, the 2,864 dev-other recordings were held aside until the wheel and graphs were fixed. [Waveform comparison and full counts](docs/mini-librispeech.md#compare-both-recognizers-from-raw-audio)

## Compatibility milestones

The initial upstream reference is [Kaldi at e02e35f](https://github.com/kaldi-asr/kaldi/tree/e02e35f0254bb033fab73d1df99fc34123e31d56). Compatibility is measured at the file, command, and workflow levels. For each command, compare accepted inputs and options, output artifacts, exit status, and numerical results against that reference.

| Area | Evidence needed |
| --- | --- |
| I/O and features | Exchange binary and text objects, keyed archives, SCP offsets, and compressed features in both directions with upstream. Compare MFCC, filterbank, CMVN, and delta outputs on fixed audio. |
| Classical training and decoding | Run a small reproducible recipe from audio and transcripts through monophone and context-dependent GMM-HMM training, speaker adaptation, graph construction, decoding, and forced alignment. Exchange acoustic models, trees, alignments, graphs, and lattices with upstream at intermediate stages. |
| Remaining toolkit | Inventory the executables and options in the pinned tree. Cover remaining model families, including additional nnet3 architectures and full upstream chain training, online and batch decoding, language modeling, speaker workflows, and CPU/GPU behavior. Record unsupported commands and numerical tolerances. |
| Python and distribution | Test wheels in clean supported environments without system Kaldi, Conda, or a compiler. Exercise MFA's actual Kalpy calls and selected ESPnet recipes. Test joint installation and representative workflows for pinned versions of both applications. |

ESPnet2 makes Kaldi optional. Joint installation and execution with ESPnet remain a separate integration target. [ESPnet installation](https://github.com/espnet/espnet/blob/master/doc/installation.md)

## Related implementations

A November 2026 search of public GitHub repositories, crates.io, and PyPI identified several projects with narrower scopes than full Kaldi compatibility.

- [utter](https://github.com/pyscape/utter) implements streaming recognition with Vosk/Kaldi models in Rust and ships Python bindings.
- [kaldi-fbank](https://github.com/ryaningli/kaldi-fbank) implements Kaldi-compatible filterbank features in Rust. [rustfst](https://github.com/garvys-org/rustfst) implements weighted finite-state transducer operations in Rust.
- [kaldi-hmm-gmm](https://github.com/csukuangfj/kaldi-hmm-gmm) exposes C++ HMM-GMM training and decoding to Python and provides a potential reference for future comparisons.

## Speech recognition experiments

The second project goal is to use the port to train and evaluate ASR on utterances that switch between Korean and English, returning word and phone intervals. Evaluate transcript recognition, phone and word boundaries on known transcripts, and the full pipeline on recognized transcripts separately. Use human-annotated boundaries for alignment accuracy and upstream Kaldi output for implementation parity.

## License

Original kaldi-rust code is licensed under Apache 2.0. Kaldi, OpenFst and other third-party contributions retain their applicable licenses and notices. The wheel includes the project license and third-party notices. [Apache 2.0 license](LICENSE) · [Distribution and attributions](docs/licensing.md)

