Metadata-Version: 2.4
Name: kaldi-rust
Version: 0.1.0a6
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: 3
Requires-Dist: click ; extra == 'mfa'
Requires-Dist: huggingface-hub ; extra == 'mfa'
Requires-Dist: kneed ; extra == 'mfa'
Requires-Dist: librosa ; extra == 'mfa'
Requires-Dist: matplotlib ; extra == 'mfa'
Requires-Dist: numpy ; extra == 'mfa'
Requires-Dist: pgvector ; extra == 'mfa'
Requires-Dist: praatio>=6.0.0 ; extra == 'mfa'
Requires-Dist: pyyaml ; extra == 'mfa'
Requires-Dist: requests ; extra == 'mfa'
Requires-Dist: rich ; extra == 'mfa'
Requires-Dist: rich-click ; extra == 'mfa'
Requires-Dist: scikit-learn ; extra == 'mfa'
Requires-Dist: seaborn ; extra == 'mfa'
Requires-Dist: soundfile ; extra == 'mfa'
Requires-Dist: sqlalchemy>=2.0 ; extra == 'mfa'
Requires-Dist: tqdm ; 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
Project-URL: Documentation, https://github.com/byseon/kaldi-rust/blob/main/README.md
Project-URL: Issues, https://github.com/byseon/kaldi-rust/issues
Project-URL: Repository, https://github.com/byseon/kaldi-rust
License-File: pybind11-LICENSE
License-File: MFA-native-notices.txt
License-File: kaldi-e02e35f0254bb033fab73d1df99fc34123e31d56-COPYING
License-File: openfst-1.8.4-COPYING
License-File: portaudio-LICENSE.txt

# kaldi-rust

[Try word alignment in Colab](https://colab.research.google.com/github/byseon/kaldi-rust/blob/main/egs/colab/word_alignment.ipynb) · [한국어 사용 안내](#한국어-사용-안내)

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, six-layer chain TDNN training on CPU, 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)
- [Align a recording with language tags](#align-a-recording-with-language-tags)
- [Align a JSONL batch](#batch-alignment)
- [Train and decode mini LibriSpeech on CPU](#train-and-decode-mini-librispeech-on-cpu)
- [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)
  - [Linux with NVIDIA CUDA](#linux-with-nvidia-cuda)
- [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

Listen to “Where is my brother now?”, see all five words on the waveform, and play just *brother*. The CPU notebook also exports the word and phone boundaries for Praat. [Open the alignment example in Colab](https://colab.research.google.com/github/byseon/kaldi-rust/blob/main/egs/colab/word_alignment.ipynb)

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 MFA-enabled kaldi-rust wheel targets **Apple Silicon, macOS 26 or later, and CPython 3.12**. Start in a terminal with uv installed. uv can fetch the requested Python version. [Install uv](https://docs.astral.sh/uv/getting-started/installation/)

```sh
uv venv --python 3.12 .venv
source .venv/bin/activate
uv pip install 'kaldi-rust[mfa]'
mfa version
```

`mfa version` prints `3.4.4`. The CPython 3.12 platform wheel includes upstream MFA and its bindings and routes `mfa align` to Rust. uv selects a single `kaldi-rust` wheel from PyPI and installs the Python dependencies from PyPI. [Runtime details](https://github.com/byseon/kaldi-rust/blob/main/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
mfa 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](https://github.com/byseon/kaldi-rust/blob/main/docs/mfa.md)

### Align a recording with language tags

Use the same MFA environment as above. The platform wheel provides the alignment commands and the upstream model manager.

Next, download one acoustic model and matching dictionary for each language in your recordings. For Korean, US English and French, run the following once. Subsequent alignments use the local MFA store.

```sh
for model in korean_mfa english_us_arpa french_mfa; do
  mfa model download acoustic "$model"
  mfa model download dictionary "$model"
done
```

Write the words in the order they are spoken. Each tag applies until the next one and can touch a word, as in `[en]meeting[ko]을`.

```sh
printf '%s\n' '[ko] 안녕 [en] hello [fr] bonjour' > transcript.txt
kaldi-rust-multilingual-align recording.wav transcript.txt result.TextGrid
```

Tags are case-sensitive. `[ko]`, `[en]` and `[fr]` select the three installed models above. A tag can also be an exact model ID such as `[english_mfa]`. Separate the words as they appear in the dictionary, including for scripts without spaces. If you supply a single `--model`, plain untagged text also works.

To override one language, append `--model en=/path/to/model.zip --dict en=/path/to/lexicon.dict`. Other tags still use the installed models. You can override just the dictionary. Lookup uses the explicit dictionary first, then a same-basename `.dict` beside the model, then the installed dictionary for that model.

For missing words, install the matching MFA G2P model once (for example, `mfa model download g2p korean_mfa`). The aligner automatically generates the top pronunciation for each distinct missing word per tag and reuses it throughout the batch in memory. Known words keep their dictionary pronunciations and weights. Use `--g2p ko=/path/to/model.zip` for a compatible custom model. [Worked Korean G2P example](https://github.com/byseon/kaldi-rust/blob/main/docs/mfa.md#generate-missing-korean-pronunciations)

The tagged aligner uses acoustic scale `0.1` for both languages and an English per-frame offset of `0.0`. If two vowels meet at a language switch, inspect the boundary in Praat. In the HiKE check, changing the pronunciation of *서사* left its boundary with *and* at 2.49 s. [HiKE pronunciation and boundary comparison](https://github.com/byseon/kaldi-rust/blob/main/docs/mfa.md#hike-pronunciation-and-boundary-comparison)

To set a pronunciation explicitly, save a per-word array as `words.json` and pass it in place of `transcript.txt`. The example uses Korean MFA symbols for the first word. The English word uses its dictionary entry.

```json
[
  {"lang":"ko","word":"안녕","pronunciations":["ɐ n ɲ ʌ ŋ"]},
  {"lang":"en","word":"hello"}
]
```

For Praat, open the recording and `result.TextGrid`, select both objects and choose **View & Edit**. The three tiers are `words`, `phones` and `language`. For machine-readable timestamps, name the output `result.json`. Each word has a language, start and end in seconds, half-open frame offsets and nested phone intervals. Pauses are listed under `silence`. This command exports alignment only. [Multilingual alignment and model compatibility](https://github.com/byseon/kaldi-rust/blob/main/docs/mfa.md#multilingual-alignment)

#### Batch alignment

Save the following as `recordings.jsonl`, with one JSON object per recording and a distinct output path on each line. Use UTF-8. Use `text` for inline tagged words or `transcript` for a tagged text or per-word JSON file. Paths in the manifest are relative to its directory.

```jsonl
{"audio":"clips/01.wav","text":"[ko] 안녕 [en] hello","output":"grids/01.TextGrid"}
{"audio":"clips/02.wav","transcript":"clips/02.txt","output":"timings/02.json"}
```

```sh
kaldi-rust-multilingual-align --batch recordings.jsonl
```

The command reads the transcripts first, loads each distinct acoustic model once, and scans each needed dictionary once for the batch vocabulary. It processes recordings sequentially and computes features only for the language tags in each recording. Models stay in memory until the batch finishes. Each completed output is written separately. If alignment fails on a recording, processing stops and the files already written remain available. Manifest and resource errors can be reported before any recording is processed. The same `--model` and `--dict` overrides apply to the whole batch.

## Train and decode mini LibriSpeech on CPU

The chain2 recipe trains a six-layer TDNN on `train-clean-5` with 40-dimensional MFCCs, online speaker i-vectors, LF-MMI and auxiliary cross-entropy. It decodes `dev-clean-2` with a Rust-built word graph. Reference transcripts are used to check coverage and to score the decoder output. The recipe reports one-best WER and two language-model scoring grids.

The Rust-trained model scored **17.56% WER** on the direct output, **17.55%** on the `tgsmall` grid and **12.59%** after `tglarge` rescoring across all 1,089 development recordings (20,138 reference words). [Results and settings](https://github.com/byseon/kaldi-rust/blob/main/docs/mini-librispeech.md#six-layer-cpu-training)

From the kaldi-rust checkout with its wheel installed, run the following with the pinned Kaldi source scripts, a download directory and a new work directory. [Prerequisites and restart instructions](https://github.com/byseon/kaldi-rust/blob/main/egs/mini_librispeech/chain2/README.md)

```sh
./egs/mini_librispeech/chain2/run.sh /path/to/kaldi-source /path/to/corpus /path/to/chain2-work
```

## Install the standalone Kaldi tools

Install the prebuilt wheel from PyPI on Apple Silicon (macOS 11+) or x86_64 Linux (glibc 2.28+). Both wheels support CPython 3.10 or newer. Run these commands in any directory. [PyPI package](https://pypi.org/project/kaldi-rust/)

```sh
uv venv --python 3.12 .venv
source .venv/bin/activate
uv pip install kaldi-rust
compute-mfcc-feats --help
```

To make the commands available across projects, use uv's isolated tool environment.

```sh
uv tool install --python 3.12 kaldi-rust
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 checked-in wheels target CPython 3.10 and newer.

## Train a chain TDNN on CPU or GPU

### Apple Silicon macOS

On **Apple Silicon macOS**, the [GPU-enabled wheel](https://pypi.org/project/kaldi-rust/#files) includes native Metal training through wgpu. Install it from PyPI 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 kaldi-rust
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 'kaldi-rust[torch]'
```

The original GPU training verification used build 1 of version 0.1.0a5.

### Linux with NVIDIA CUDA

Use the [Linux x86_64 wheel](https://pypi.org/project/kaldi-rust/#files) on a glibc-based distribution (glibc 2.28 or newer). The wheel contains the compiled Rust extension. PyTorch supplies the CUDA runtime for training. Start on the GPU machine with a working NVIDIA driver and a recent version of uv. Create an environment and let uv select PyTorch for the installed driver. [uv and PyTorch](https://docs.astral.sh/uv/guides/integration/pytorch/#automatic-backend-selection)

```sh
nvidia-smi
uv venv --python 3.12 .venv
source .venv/bin/activate
uv pip install --only-binary :all: --torch-backend=auto 'kaldi-rust[torch]'
python -c 'import torch; assert torch.cuda.is_available(), "PyTorch cannot see a CUDA GPU"; print(torch.cuda.get_device_name(0), torch.version.cuda)'
```

With features and monophone alignments in a prepared mini LibriSpeech `s5` directory, run a short training job.

```sh
kaldi-rust-train-chain /path/to/s5 exp/chain-cuda \
  --gpu-backend torch --torch-device cuda --limit 8 --epochs 2
```

The command requires a CUDA device and prints its name. A successful run writes `exp/chain-cuda/final.raw` and records the device in `exp/chain-cuda/result.json`. If the device check fails, confirm the driver can see the GPU and select a compatible CUDA build of PyTorch. [PyTorch installation selector](https://pytorch.org/get-started/locally/)

**Verified on Google Colab.** In a fresh CPython 3.13 environment on an NVIDIA Tesla T4, `uv pip install --torch-backend=auto 'kaldi-rust[torch]'` installed kaldi-rust `0.1.0a5` and PyTorch `2.15.0+cu132` (CUDA 13.2). The mini LibriSpeech command processed 17,350 frames across two epochs in 5.57 seconds. After reloading `final.raw`, the LF-MMI objective per frame improved from −1.239693 to −0.924909.

### Training commands

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. Native Metal and PyTorch MPS were exercised on an Apple M4 Pro. [GPU training results](https://github.com/byseon/kaldi-rust/blob/main/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](https://github.com/byseon/kaldi-rust/blob/main/egs/mini_librispeech/chain/README.md) covers settings, supported example formats and a short eight-recording run. The [benchmark](https://github.com/byseon/kaldi-rust/blob/main/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](https://github.com/byseon/kaldi-rust/blob/main/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 online natural-gradient training for the six-layer mini LibriSpeech TDNN with an auxiliary cross-entropy head. |
| 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](https://github.com/byseon/kaldi-rust/blob/main/docs/kaldi-commands.md) tracks individual Kaldi programs, and the [recipe catalog](https://github.com/byseon/kaldi-rust/blob/main/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](https://github.com/byseon/kaldi-rust/blob/main/docs/recipes.md)

The wheel provides 151 of the 519 inventoried Kaldi command names. Other nnet3 architectures, chain recipes and online recognition workflows still need implementation and testing. The native CPU reference and wheel results are reported separately in the [benchmark](https://github.com/byseon/kaldi-rust/blob/main/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](https://github.com/byseon/kaldi-rust/blob/main/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](https://github.com/byseon/kaldi-rust/blob/main/LICENSE) · [Distribution and attributions](https://github.com/byseon/kaldi-rust/blob/main/docs/licensing.md)

## 한국어 사용 안내

“Where is my brother now?”를 듣고 *brother*가 어디서 시작하는지 짐작해 보세요. Colab에서 실행하면 파형 위에 다섯 단어의 경계가 표시됩니다. 단어 하나를 골라 다시 듣거나 Praat용 TextGrid를 내려받을 수 있습니다. [Colab에서 단어 정렬 예제 열기](https://colab.research.google.com/github/byseon/kaldi-rust/blob/main/egs/colab/word_alignment.ipynb)

### MFA 설치

macOS 26 이상인 Apple Silicon Mac에서 MFA로 정렬하려면 CPython 3.12 가상환경을 만들고 MFA용 추가 의존성을 설치하세요.

```sh
uv venv --python 3.12 .venv-mfa
source .venv-mfa/bin/activate
uv pip install 'kaldi-rust[mfa]'
mfa version
```

`mfa version`은 `3.4.4`를 표시합니다. 음성과 전사를 준비한 뒤 `mfa align corpus english.dict english_us_arpa.zip grids`를 실행하면 Rust가 발음 그래프를 만들고 정렬하며, MFA가 단어와 음소의 시간 구간을 TextGrid에 기록합니다. [녹음·전사 준비부터 TextGrid 출력까지](#align-speech-with-montreal-forced-aligner)

### 녹음 한 개를 언어 태그로 정렬하기

위에서 만든 MFA 가상환경을 활성화하세요. 다음 명령은 예제에 쓰는 세 언어의 모델과 한국어 G2P를 설치합니다.

```sh
for model in korean_mfa english_us_arpa french_mfa; do
  mfa model download acoustic "$model"
  mfa model download dictionary "$model"
done
mfa model download g2p korean_mfa
```

녹음 내용을 UTF-8 텍스트로 적고, **언어가 바뀌는 곳에만** 태그를 붙입니다. 아래는 `recording.wav`에 “안녕 hello bonjour”가 들어 있는 경우입니다. 두 번째 명령에서 출력 확장자를 `.json`으로 바꾸면 같은 방식으로 정렬한 시간을 프로그램에서 읽을 수 있습니다.

```sh
printf '%s\n' '[ko] 안녕 [en] hello [fr] bonjour' > transcript.txt
kaldi-rust-multilingual-align recording.wav transcript.txt result.TextGrid
```

- **모델 선택**. `[ko]`는 `korean_mfa`, `[en]`은 `english_us_arpa`, `[fr]`은 `french_mfa`를 선택합니다. 태그는 대소문자를 구분하며 줄이 바뀌어도 다음 태그까지 유지됩니다. `[english_mfa]`처럼 설치된 모델 ID를 직접 써도 됩니다. 함께 쓰는 음향 모델은 이 디코더가 읽을 수 있는 GMM-HMM이어야 하고 프레임 시간축이 맞아야 합니다. [모델 호환 조건](https://github.com/byseon/kaldi-rust/blob/main/docs/mfa.md#multilingual-alignment)
- **단어 구분**. 일본어·중국어 등은 사전에서 찾을 단위로 띄어 씁니다. `[en]meeting[ko]을`처럼 한 어절의 접미사 앞에서도 모델을 바꿀 수 있습니다. 조사처럼 분리한 단위도 해당 언어의 사전에 있거나 발음을 직접 지정해야 합니다.
- **경로 지정**. 한 언어만 다른 모델로 처리하려면 명령 끝에 `--model en=/path/to/model.zip --dict en=/path/to/lexicon.dict`를 붙입니다. 사전만 바꿀 때는 `--dict`만 써도 됩니다. 명시한 사전, 모델 옆의 같은 이름인 `.dict`, MFA 저장소의 사전 순서로 찾습니다. `--model`을 하나만 명시하면 단일 언어 전사는 태그를 생략할 수 있습니다.
- **사전에 없는 단어**. 한국어는 `mfa model download g2p korean_mfa`로 G2P 모델을 한 번 설치합니다. 정렬기가 태그별 미등록 어절의 최상위 발음을 자동 생성합니다. 같은 태그에서 반복되는 어절은 배치 전체에서 한 번만 생성하며, 결과는 메모리에서 재사용합니다. 사전에 있는 단어는 기존 발음과 가중치를 사용합니다. 다른 호환 모델은 `--g2p ko=/path/to/model.zip`로 지정합니다. [한국어 G2P 실행 예시](https://github.com/byseon/kaldi-rust/blob/main/docs/mfa.md#generate-missing-korean-pronunciations)
- **언어 전환 경계**. 태그 정렬기는 두 언어에 음향 가중치 `0.1`을 쓰고 영어 프레임당 보정값은 `0.0`으로 둡니다. 서로 다른 언어의 모음이 이어질 때는 Praat에서 경계를 확인하세요. HiKE의 ‘서사 and’는 ‘서사’의 발음 후보를 바꿔도 경계가 2.49초였습니다. [HiKE 발음·경계 비교](https://github.com/byseon/kaldi-rust/blob/main/docs/mfa.md#hike-pronunciation-and-boundary-comparison)
- **단어별 발음 직접 지정**. 입력을 단어별 JSON 배열로 바꾸고 해당 단어에 모델의 음소 기호로 `pronunciations`를 지정합니다. 그 언어의 모든 단어에 발음을 넣었다면 해당 언어의 사전을 생략할 수 있습니다.

예를 들어 아래 전사를 `words.json`으로 저장한 뒤 `kaldi-rust-multilingual-align recording.wav words.json result.json`을 실행합니다. 이 예제의 녹음 내용은 “안녕 hello”입니다.

```json
[
  {"lang":"ko","word":"안녕","pronunciations":["ɐ n ɲ ʌ ŋ"]},
  {"lang":"en","word":"hello"}
]
```

**Praat에서 확인하려면** WAV와 TextGrid를 열고 두 객체를 함께 선택한 뒤 **View & Edit**를 누릅니다. `words`는 단어, `phones`는 음소, `language`는 각 단어에 적용한 언어입니다. 무음은 빈 구간으로 보입니다. JSON에서는 `words[].phones`에 음소별 시간이, `silence`에 무음 구간이 들어갑니다. `start`와 `end`는 녹음 시작부터의 초 단위 시간이고, 프레임 범위는 `start_frame` 이상 `end_frame` 미만입니다.

### 여러 녹음을 배치로 정렬하기

`recordings.jsonl`에 **한 줄당 녹음 하나**를 적습니다. 각 줄에는 `audio`와 고유한 `output` 경로가 필요합니다. 전사는 `text`에 바로 적거나 `transcript`로 외부 텍스트·JSON 파일을 지정합니다. 두 필드 중 하나만 사용합니다. 상대 경로의 기준은 JSONL 파일이 있는 디렉터리입니다.

```jsonl
{"audio":"clips/01.wav","text":"[ko] 안녕 [en] hello","output":"grids/01.TextGrid"}
{"audio":"clips/02.wav","transcript":"clips/02.txt","output":"timings/02.json"}
```

```sh
kaldi-rust-multilingual-align --batch recordings.jsonl
```

전체 전사에서 언어 태그와 필요한 단어를 먼저 모읍니다. 서로 다른 음향 모델은 각각 한 번만 열고, 각 사전도 배치에 필요한 단어를 찾기 위해 한 번만 읽습니다. 이후 녹음을 순서대로 처리하고 각 녹음에 등장하는 언어에 대해서만 음향 특징을 계산합니다. `--model`과 `--dict`는 배치 전체에 적용됩니다. 목록이나 모델 설정 오류는 정렬을 시작하기 전에 보고될 수 있습니다. 개별 녹음 정렬 중 오류가 나면 그 지점에서 멈추며 이미 저장한 결과는 남습니다.

### 독립 Kaldi 도구 설치와 CPU·GPU 학습

Apple Silicon Mac(macOS 11 이상)과 x86_64 Linux(glibc 2.28 이상)에서는 CPython 3.10 이상으로 아래 명령을 실행하면 됩니다. uv가 PyPI에서 환경에 맞는 wheel을 설치하므로 Rust 컴파일러나 소스 코드는 필요하지 않습니다. [PyPI 패키지](https://pypi.org/project/kaldi-rust/)

```sh
uv venv --python 3.12 .venv-kaldi
source .venv-kaldi/bin/activate
uv pip install kaldi-rust
compute-mfcc-feats --help
kaldi-rust-train-chain --help
```

Linux에서 NVIDIA GPU를 쓰려면 드라이버가 설치된 환경에서 다음 명령으로 PyTorch를 설치하고 GPU 이름을 확인하세요.

```sh
uv pip install --torch-backend=auto 'kaldi-rust[torch]'
python -c 'import torch; print(torch.cuda.get_device_name(0))'
```

Apple Silicon에서는 기본 설치로 Metal(wgpu)을 쓸 수 있습니다. PyTorch MPS를 쓰려면 같은 환경에서 `uv pip install 'kaldi-rust[torch]'`를 실행하세요.

특징과 모노폰 정렬을 준비한 mini LibriSpeech `s5` 디렉터리로 짧은 CUDA 학습을 실행합니다.

```sh
kaldi-rust-train-chain /path/to/s5 exp/chain-cuda \
  --gpu-backend torch --torch-device cuda --limit 8 --epochs 2
```

Google Colab의 NVIDIA Tesla T4에서 두 에포크 동안 총 17,350프레임을 처리하고 저장된 모델을 다시 불러왔습니다. [CUDA 검증 결과와 설치 조건](#linux-with-nvidia-cuda) · [CPU와 Metal 학습 명령](#training-commands)

