Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ C/C++ speech-to-text inference library. Runs diverse STT model families via [GGU
| Canary-Qwen 2.5B | `canary-qwen-2.5b` | - | [docs/models/canary-qwen-2.5b.md](docs/models/canary-qwen-2.5b.md) |
| Cohere Transcribe | `cohere-transcribe-03-2026`, `cohere-transcribe-arabic-07-2026` | - | [docs/models/cohere.md](docs/models/cohere.md) |
| Fun-ASR-Nano | `fun-asr-mlt-nano-2512`, `fun-asr-nano-2512` | - | [docs/models/fun-asr-nano.md](docs/models/fun-asr-nano.md) |
| GigaAM | `gigaam-multilingual-v2-e2e-rnnt`, `gigaam-v3-ctc`, `gigaam-v3-e2e-ctc`, `gigaam-v3-e2e-rnnt`, `gigaam-v3-rnnt`, `gigaam-v4-e2e-rnnt` | token timestamps | [docs/models/gigaam.md](docs/models/gigaam.md) |
| GigaAM | `gigaam-multilingual-v2-e2e-rnnt`, `gigaam-v3-ctc`, `gigaam-v3-e2e-ctc`, `gigaam-v3-e2e-rnnt`, `gigaam-v3-rnnt`, `gigaam-v4-e2e-rnnt` | token timestamps; streaming (v4) | [docs/models/gigaam.md](docs/models/gigaam.md) |
| Granite Speech 4 / 4.1 | `granite-4.0-1b-speech`, `granite-speech-4.1-2b`, `granite-speech-4.1-2b-nar`, `granite-speech-4.1-2b-plus` | diarize, translate, word timestamps | [docs/models/granite-speech.md](docs/models/granite-speech.md) |
| Granite Speech 5.0 TurboCTC | `granite-speech-5.0-470m-turboctc`, `granite-speech-5.0-470m-turboctc-nc` | - | [docs/models/granite-speech-5.0-turboctc.md](docs/models/granite-speech-5.0-turboctc.md) |
| MedASR | `medasr` | token timestamps | [docs/models/medasr.md](docs/models/medasr.md) |
Expand Down
15 changes: 14 additions & 1 deletion docs/models/gigaam-v4-e2e-rnnt.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<!-- catalog:intro -->
Upstream: [`ai-sage/GigaAM-v4`](https://huggingface.co/ai-sage/GigaAM-v4) at [`180301a`](https://huggingface.co/ai-sage/GigaAM-v4/commit/180301a).

Transcribes Russian and English speech, with capital letters and punctuation. On the FLEURS Russian test it makes the fewest errors of the models in transcribe.cpp. Recordings of any length work. It does not transcribe live audio or translate.
Transcribes Russian and English speech, with capital letters and punctuation. On the FLEURS Russian test it makes the fewest errors of the models in transcribe.cpp. Recordings of any length work, and the streaming API transcribes live audio. It does not translate.
<!-- /catalog -->

Other GigaAM models are on the [GigaAM page](gigaam.md).
Expand Down Expand Up @@ -115,6 +115,18 @@ To run the benchmark yourself:
uv run scripts/bench/run.py --profile --models gigaam-v4-e2e-rnnt
```

## Streaming

The GGUF carries the checkpoint's streaming config, so the model also runs
as a native stream: feed 16 kHz mono float32 PCM with
`transcribe_stream_feed`, read partial text between calls, and call
`transcribe_stream_finalize` at the end of the audio. The runtime uses the
smallest advertised future context (160 ms) and a 32-frame left context; the
attention, convolution and RNN-T states are carried between chunks. The
caches stay the same size for any stream length; only the transcript grows. GigaAM-v3 checkpoints have no
streaming config and stay offline. See
[the family doc](gigaam.md#streaming) for the API-level details.

## For developers

This port is checked against the original PyTorch model, layer by layer,
Expand All @@ -125,6 +137,7 @@ details.
| Field | Value |
| --- | --- |
| Reference | `modeling_gigaam.py` from `ai-sage/GigaAM-v4` @ `180301a`, built in F32 on CPU by `scripts/lib/gigaam_v4_hf.py` |
| Streaming parity | `GigaAMStreaming` from the same module; `transcribe_gigaam_stream_real_smoke` checks the streamed transcript on `samples/jfk.wav` exactly at 160, 320 and 640 ms |
| Dump script | `scripts/dump_reference_gigaam_v4_hf.py` |
| Manifest | `tests/golden/gigaam/gigaam-v4-e2e-rnnt.manifest.json` |
| Tolerances | `tests/tolerances/gigaam-v4.json` |
Expand Down
39 changes: 34 additions & 5 deletions docs/models/gigaam.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,31 @@ Downloads, WER, speed and the reproduction commands are on the
[family doc](../porting/families/gigaam.md#gigaam-v4-e2e-rnnt) has the
validation results.

### Streaming

A v4 GGUF that carries the checkpoint's `cfg.streaming` block supports
native streaming through `transcribe_stream_begin`,
`transcribe_stream_feed` and `transcribe_stream_finalize` (16 kHz mono
float32 PCM). The converter writes that block; GGUFs converted before it
existed, and every v3 variant, stay offline.

The encoder follows the reference's stateful stream: audio is processed in
chunks of the checkpoint's future context (160, 320 or 640 ms; the runtime
uses the smallest preset by default), each frame attends to the last 32 frames of the
left context, and the attention, convolution and RNN-T decoder states are
carried across chunks. Text grows as chunks are decoded. With the default policy
(`TRANSCRIBE_STREAM_COMMIT_AUTO`), `committed_text` grows only with the
stable prefix, the part that has stopped changing between feeds. Set
`TRANSCRIBE_STREAM_COMMIT_ON_FINALIZE` to hold the whole transcript back
until finalize.

The model caches hold the left context plus one chunk, so they stay the
same size for any stream length. The transcript is the only state that
grows. Audio shorter than one chunk is emitted by `finalize`.

The streamed transcript matches the reference `GigaAMStreaming` at all
three presets on the sample audio used for the port's validation.

## GigaAM Multilingual-v2 E2E RNN-T

`gigaam-multilingual-v2-e2e-rnnt` is the `e2e` head of
Expand Down Expand Up @@ -198,11 +223,15 @@ All GigaAM-v3 variants support:
- **Token-level timestamps** at the encoder frame rate (40 ms
granularity).

What's not supported (consistent across the family): translation, real-time
streaming, VAD, speaker diarization, languages other than Russian.
Long-form input is windowed internally rather than through upstream's
`transcribe_longform` PyAnnote-VAD chunking. See the family doc for the full
runtime contract.
What v3 does not support: translation, VAD, speaker diarization, languages
other than Russian, and streaming. v4 adds English and streaming;
translation, VAD and diarization are still out of scope. Long-form input is
windowed internally rather than through upstream's `transcribe_longform`
PyAnnote-VAD chunking. See the family doc for the full runtime contract.

A `gigaam-v4-e2e-rnnt` GGUF converted with the checkpoint's streaming
config runs the reference's stateful encoder and decodes each chunk as it
arrives. See [Streaming](#streaming) below.

`gigaam-multilingual-large-ctc` has the same capabilities and gaps, except
that it transcribes the five languages listed in
Expand Down
105 changes: 104 additions & 1 deletion scripts/convert-gigaam-v4.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,102 @@ def refuse(key, value, why):
raise ValueError("cfg.language_conditioning is unexpected for GigaAM-v4")


# Mirrors kMaxStreamChunkFrames / kMaxStreamLeftFrames in
# src/arch/gigaam/weights.cpp: a config the loader would refuse must not
# convert.
MAX_CHUNK_FRAMES = 256
MAX_LEFT_FRAMES = 256


def streaming_contexts(cfg: dict, enc_cfg: dict, pre_cfg: dict) -> tuple[int, list[int], list[int]]:
"""Validate cfg.streaming.contexts against the encoder's chunk geometry.

Returns (frame_ms, future_context_ms, left_context), or (0, [], []) when
the checkpoint carries no streaming config. The streaming graph attends
with a fixed band: query frame q sees keys in [q - left_context, q + chunk).
The Zapformer config spells the same band twice, as chunk_size and
window_size, so refuse a config where the two disagree instead of porting
one and silently ignoring the other.
"""
streaming = cfg.get("streaming")
if streaming is None:
streaming = {}
if not isinstance(streaming, dict):
raise ValueError("cfg.streaming must be a mapping")
contexts = streaming.get("contexts")
if contexts is None:
return 0, [], []
if not isinstance(contexts, list) or not all(isinstance(c, dict) for c in contexts):
raise ValueError("cfg.streaming.contexts must be a list of {future_context_ms, left_context}")

try:
sample_rate = int(pre_cfg["sample_rate"])
hop_length = int(pre_cfg["hop_length"])
except (KeyError, TypeError, ValueError) as e:
raise ValueError(f"cfg.preprocessor sample_rate/hop_length is missing or not an integer: {e}") from e
if sample_rate <= 0:
raise ValueError(f"cfg.preprocessor.sample_rate is {sample_rate}; it must be positive")
# Subsampling is fixed at 4 by the Zapformer frontend; the converter writes
# that value as stt.gigaam.encoder.subsampling_factor.
frame_ms = hop_length * 4 * 1000 // sample_rate
if frame_ms <= 0:
raise ValueError(f"preprocessor gives a non-positive frame_ms ({frame_ms})")

windows = enc_cfg.get("window_size", (-1, -1))
if not isinstance(windows, (list, tuple)):
raise ValueError(f"cfg.encoder.window_size is {windows!r}; expected a list of pairs")
if windows and not isinstance(windows[0], (list, tuple)):
windows = [windows]
if not all(isinstance(w, (list, tuple)) and len(w) == 2 for w in windows):
raise ValueError(f"cfg.encoder.window_size is {windows!r}; expected a list of [left, right] pairs")
streaming_windows = [list(w) for w in windows if list(w) != [-1, -1]]
if len(streaming_windows) != len(contexts):
raise ValueError(
f"cfg.streaming.contexts has {len(contexts)} entries but cfg.encoder.window_size "
f"describes {len(streaming_windows)} streaming bands")
chunk_size_raw = enc_cfg.get("chunk_size", -1)
if chunk_size_raw is None:
raise ValueError("cfg.encoder.chunk_size is null; expected an int or a list of ints")
chunk_sizes = parse_int_list(chunk_size_raw)

futures: list[int] = []
lefts: list[int] = []
for i, context in enumerate(contexts):
try:
future = int(context["future_context_ms"])
left = int(context["left_context"])
except KeyError as e:
raise ValueError(f"cfg.streaming.contexts[{i}] has no {e.args[0]}") from e
except (TypeError, ValueError) as e:
raise ValueError(f"cfg.streaming.contexts[{i}] is not a pair of integers: {e}") from e
if future <= 0 or future % frame_ms:
raise ValueError(
f"cfg.streaming.contexts[{i}].future_context_ms is {future}; it must be a positive "
f"multiple of the {frame_ms} ms encoder frame")
if left < 0:
raise ValueError(f"cfg.streaming.contexts[{i}].left_context is {left}; it must be >= 0")
window = streaming_windows[i]
if window != [left, 0]:
raise ValueError(
f"cfg.streaming.contexts[{i}] says left_context={left}, but cfg.encoder.window_size "
f"is {window}; the graph implements [left, 0] only")
if future // frame_ms > MAX_CHUNK_FRAMES:
raise ValueError(
f"cfg.streaming.contexts[{i}] is {future // frame_ms} frames at {frame_ms} ms; "
f"the loader accepts at most {MAX_CHUNK_FRAMES}")
if left > MAX_LEFT_FRAMES:
raise ValueError(
f"cfg.streaming.contexts[{i}].left_context is {left} frames; "
f"the loader accepts at most {MAX_LEFT_FRAMES}")
futures.append(future)
lefts.append(left)
if chunk_sizes != [-1] + [f // frame_ms for f in futures]:
raise ValueError(
f"cfg.encoder.chunk_size is {chunk_sizes}, but the streaming contexts imply "
f"{[f // frame_ms for f in futures]}")
return frame_ms, futures, lefts


def convert(model_dir: Path, out_path: Path, head: str, repo_id: str) -> None:
cfg_path = model_dir / "config.json"
st_path = model_dir / "model.safetensors"
Expand All @@ -185,6 +281,7 @@ def convert(model_dir: Path, out_path: Path, head: str, repo_id: str) -> None:
lang_cfg = cfg.get("language_conditioning")
if lang_cfg and head != "e2e":
raise ValueError("only the Multilingual-v2 e2e head is supported")
stream_frame_ms, stream_futures, stream_lefts = streaming_contexts(cfg, enc_cfg, pre_cfg)

tok_path = model_dir / dec_cfg["model_path"]
tok = extract_sp_tokenizer(tok_path)
Expand Down Expand Up @@ -292,7 +389,7 @@ def get_f32(key: str) -> np.ndarray:
writer.add_string("stt.variant", variant)
writer.add_bool("stt.capability.translate", False)
writer.add_bool("stt.capability.lang_detect", False)
writer.add_bool("stt.capability.streaming", False)
writer.add_bool("stt.capability.streaming", bool(stream_futures))
writer.add_string("stt.gigaam.head_kind", "rnnt")

# Tokenizer
Expand Down Expand Up @@ -335,6 +432,12 @@ def get_f32(key: str) -> np.ndarray:
writer.add_float32("stt.gigaam.encoder.out_norm.scale", out_norm_scale)
writer.add_float32("stt.gigaam.encoder.out_norm.eps", out_norm_eps)
writer.add_float32("stt.gigaam.encoder.rope_base", 10000.0)
if stream_futures:
# The streaming graph reads these; the capability flag above is set
# from their presence.
writer.add_uint32("stt.gigaam.streaming.frame_ms", stream_frame_ms)
writer.add_array("stt.gigaam.streaming.future_context_ms", stream_futures)
writer.add_array("stt.gigaam.streaming.left_context", stream_lefts)

# RNN-T predictor + joint
writer.add_uint32("stt.gigaam.predictor.hidden", pred_hidden)
Expand Down
126 changes: 126 additions & 0 deletions scripts/test_gigaam_v4.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,5 +220,131 @@ def test_a_key_zapformer_encoder_does_not_take_is_refused(self):
self.check({"lang_film": True})


class StreamingContextsTest(unittest.TestCase):
def cfg(self, contexts=None, **enc):
cfg = copy.deepcopy(_V4_CFG)
cfg["encoder"].update(enc)
if contexts is not None:
cfg["streaming"] = {"contexts": contexts}
cfg["preprocessor"] = {"sample_rate": 16000, "hop_length": 160}
return cfg

@staticmethod
def contexts():
return [
{"future_context_ms": 160, "left_context": 32},
{"future_context_ms": 320, "left_context": 32},
{"future_context_ms": 640, "left_context": 32},
]

def parse(self, cfg):
return convert_v4.streaming_contexts(cfg, cfg["encoder"], cfg["preprocessor"])

def test_the_v4_streaming_contexts_are_accepted(self):
cfg = self.cfg(self.contexts())
self.assertEqual(self.parse(cfg), (40, [160, 320, 640], [32, 32, 32]))

def test_a_checkpoint_without_streaming_config_is_offline(self):
self.assertEqual(self.parse(self.cfg(None)), (0, [], []))

def test_a_future_context_that_is_not_a_frame_multiple_is_refused(self):
contexts = self.contexts()
contexts[0]["future_context_ms"] = 150
with self.assertRaisesRegex(ValueError, r"multiple of the 40 ms"):
self.parse(self.cfg(contexts))

def test_a_negative_left_context_is_refused(self):
contexts = self.contexts()
contexts[0]["left_context"] = -1
with self.assertRaisesRegex(ValueError, r"left_context is -1"):
self.parse(self.cfg(contexts))

def test_a_window_that_disagrees_with_left_context_is_refused(self):
cfg = self.cfg(self.contexts(), window_size=[[-1, -1], [16, 0], [32, 0], [32, 0]])
with self.assertRaisesRegex(ValueError, r"window_size is \[16, 0\]"):
self.parse(cfg)

def test_a_chunk_size_that_disagrees_with_the_contexts_is_refused(self):
cfg = self.cfg(self.contexts(), chunk_size=[-1, 4, 8, 32])
with self.assertRaisesRegex(ValueError, r"chunk_size is \[-1, 4, 8, 32\]"):
self.parse(cfg)

def test_a_malformed_streaming_block_is_refused_with_a_value_error(self):
# None (and a missing key) means "no streaming config"; a list or a
# scalar is a malformed block.
self.assertEqual(self.parse(self.cfg(None)), (0, [], []))
for bad in ([], "x", 3):
cfg = self.cfg(None)
cfg["streaming"] = bad
with self.assertRaisesRegex(ValueError, r"cfg\.streaming must be a mapping"):
self.parse(cfg)
cfg = self.cfg(None)
cfg["streaming"] = {"contexts": {"future_context_ms": 160}}
with self.assertRaisesRegex(ValueError, r"must be a list of"):
self.parse(cfg)

def test_a_context_without_left_context_is_refused(self):
contexts = self.contexts()
del contexts[0]["left_context"]
with self.assertRaisesRegex(ValueError, r"has no left_context"):
self.parse(self.cfg(contexts))

def test_a_non_integer_context_is_refused(self):
contexts = self.contexts()
contexts[0]["future_context_ms"] = [160]
with self.assertRaisesRegex(ValueError, r"not a pair of integers"):
self.parse(self.cfg(contexts))

def test_a_zero_sample_rate_is_refused(self):
cfg = self.cfg(self.contexts())
cfg["preprocessor"]["sample_rate"] = 0
with self.assertRaisesRegex(ValueError, r"sample_rate is 0"):
self.parse(cfg)

def test_a_chunk_size_without_a_positive_entry_is_refused(self):
with self.assertRaisesRegex(ValueError, r"chunk_size is \[-1\]"):
self.parse(self.cfg(self.contexts(), chunk_size=[-1]))

def test_a_falsy_non_list_contexts_is_refused(self):
for bad in (0, {}, "", False):
cfg = self.cfg(None)
cfg["streaming"] = {"contexts": bad}
with self.assertRaisesRegex(ValueError, r"must be a list of"):
self.parse(cfg)

def test_a_null_chunk_size_is_refused(self):
with self.assertRaisesRegex(ValueError, r"chunk_size is null"):
self.parse(self.cfg(self.contexts(), chunk_size=None))

def test_a_window_entry_that_is_not_a_pair_is_refused(self):
cfg = self.cfg(self.contexts(), window_size=[[-1, -1], 32, [32, 0], [32, 0]])
with self.assertRaisesRegex(ValueError, r"expected a list of \[left, right\] pairs"):
self.parse(cfg)

def test_a_missing_hop_length_is_refused(self):
cfg = self.cfg(self.contexts())
del cfg["preprocessor"]["hop_length"]
with self.assertRaisesRegex(ValueError, r"hop_length is missing or not an integer"):
self.parse(cfg)

def test_a_chunk_beyond_the_loader_bound_is_refused(self):
contexts = self.contexts()
contexts[0]["future_context_ms"] = 20000 # 500 frames at 40 ms
with self.assertRaisesRegex(ValueError, r"the loader accepts at most 256"):
self.parse(self.cfg(contexts))

def test_a_left_context_beyond_the_loader_bound_is_refused(self):
contexts = self.contexts()
contexts[0]["left_context"] = 512
cfg = self.cfg(contexts, window_size=[[-1, -1], [512, 0], [32, 0], [32, 0]])
with self.assertRaisesRegex(ValueError, r"left_context is 512 frames"):
self.parse(cfg)

def test_a_context_count_that_disagrees_with_the_windows_is_refused(self):
cfg = self.cfg(self.contexts()[:-1])
with self.assertRaisesRegex(ValueError, r"2 entries but .* describes 3"):
self.parse(cfg)


if __name__ == "__main__":
unittest.main()
1 change: 1 addition & 0 deletions src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ add_library(transcribe
arch/gigaam/encoder.cpp
arch/gigaam/decoder.cpp
arch/gigaam/mel.cpp
arch/gigaam/stream.cpp
arch/granite/model.cpp
arch/granite/diarize.cpp
arch/granite/capabilities.cpp
Expand Down
Loading