Repository navigation
gigaam: add GigaAM-v4 (Zapformer encoder + RNN-T) - #285
Conversation
The Zapformer port had no way to be checked against its reference inside the repo's own gates. The family's gigaam package pin has no Zapformer, so v4 gets its reference from the modeling_gigaam.py the HF repo ships, in a separate env, leaving the v3 reference untouched. - scripts/lib/gigaam_v4_hf.py pins ai-sage/GigaAM-v4 at 180301a1 and builds GigaAMDualASR from the snapshot without trust_remote_code; the converter and the new reference dumper read the pin - golden manifest (ru, odd T_enc; fleurs-en) and tolerances at 1.5x the observed drift; C++ dumps enc.stage.<s>.out for each Zapformer stack - real-model public-ABI smoke, single and batched - intake, porting log, family doc section - reference WER runner (scripts/wer/run_reference_gigaam_v4_hf.py) - long-form windows start on a multiple of the largest downsampling factor, so the half-rate stack pairs the same frames as whole-clip inference; the loader rejects stage geometry the graph cannot run; Zapformer batches skip the unused packed-batch mel pass - clang-format the Zapformer sources Co-Authored-By: Claude Opus 5.5 <[email protected]>
d55dda4 to
b12d7d5
Compare
|
Thanks for submitting, ill start reviewing soon! |
|
@cjpais Could you approve the pending |
vlsi
left a comment
There was a problem hiding this comment.
I ported GigaAM-v4 independently before I saw this PR, so I won't open a competing one. The inline comments come from reviewing this branch against modeling_gigaam.py and my port; where my port has numbers or code you could use, they are in the comment.
Three things block the merge for me. The encoder output differs from the reference by the RoPE table rounding, and the tolerances are widened to absorb it (F1). The new golden manifest makes scripts/lib/test_gigaam_hf.py fail, so the python-bindings CI job goes red once it runs (F2). The window alignment fix has no test that reaches a windowed clip (F3).
F1 and F16 are one change: the reference loads the RoPE tables from the checkpoint, so the graph, the tolerance file, and the comment in load_model need to follow that. F8 resolves F2 and most of F13: record the v4 source in gigaam_hf.VARIANTS instead of a second pin module. F5, F6, F7, and F12 share one cause: the converter and the loader accept Zapformer configurations beyond the one the graph was validated on, so refusing everything but GigaAM-v4's geometry resolves them together. The rest are small.
WER for the remaining quants and for LibriSpeech. These come from my build (F16-rounded RoPE, scripts/wer/run.py --backend metal, batch size 1), not from this PR's GGUFs, so treat them as an indication of how the quants behave rather than as this PR's numbers. The gigaam package's transcribe refuses clips over 25 s (1 in FLEURS ru, 9 in LibriSpeech test-clean), so every row compares the remaining utterances:
| FLEURS ru (774) | LibriSpeech test-clean (2611) | |
|---|---|---|
reference (gigaam package, F32, CPU) |
4.36 | 2.02 |
| F32 | 4.35 | 2.02 |
| F16 | 4.35 | 2.02 |
| Q8_0 | 4.39 | 2.03 |
| Q6_K | 4.40 | 2.03 |
| Q5_K_M | 4.39 | 2.06 |
| Q4_K_M | 4.57 | 2.09 |
F32 transcripts equal the reference's on 770 of 774 FLEURS ru and 2592 of 2611 LibriSpeech utterances. Q4_K_M is the only preset that moves FLEURS ru by more than 0.05 pp.
Not inline
F18 minor docs/models/gigaam.md:11-14, outside the diff: docs/models/gigaam.md gets no GigaAM-v4 section, where the unpublished Multilingual variant has one
Problem: A user who opens the model page for GigaAM (the page the README links) learns about the converted-but-unpublished Multilingual variant and how to convert and run it, and finds nothing about gigaam-v4-e2e-rnnt, which is the variant this change makes runnable. The family doc is a porting page for contributors, not the page a user reads.
Proposed solution: Add a ## GigaAM-v4 E2E RNN-T section to docs/models/gigaam.md in the shape of the Multilingual one: what the variant is (ru+en, cased and punctuated, Zapformer encoder), that no GGUF is published, the convert/quantize/run commands, and a link to the family doc section for validation results; mention it in the intro beside the fifth variant.
F21 minor The description names the internal EncoderKind enum but not the GGUF key that selects the encoder, stt.gigaam.encoder.type (conformer default, zapformer), nor the new load errors.
Problem: The GGUF key is the format contract converters and other GGUF readers depend on and the string a reader searches for; EncoderKind is a C++ type nobody outside src/arch/gigaam sees. The new TRANSCRIBE_ERR_GGUF outcomes and their log text are what an on-call reader holding the log line would search for.
Proposed solution: In the Summary, name the key: the encoder is selected by the GGUF string stt.gigaam.encoder.type (zapformer for v4; absent or conformer for v3 and Multilingual GGUFs). Add the outcomes: an unknown value fails the load with TRANSCRIBE_ERR_GGUF and gigaam: unsupported stt.gigaam.encoder.type=<value>, and malformed stage geometry fails with TRANSCRIBE_ERR_GGUF and gigaam: stage <s> has unsupported geometry (...).
F34 nit The description states several facts twice: the TLDR line repeats the Summary, and the "## Scope" file list repeats the Summary bullets; keep the "Not included" paragraph and drop the rest.
Problem: The TLDR also has grammar errors ("it is contains", "I haved added the support from it") that make the first line the hardest to read.
Proposed solution: Delete the TLDR line and the file list under "## Scope"; keep the "Not included" paragraph under a **Scope.** lead-in, with the follow-up issue number for each gap where one exists. Drop the clang-format bullet. The validation evidence that CONTRIBUTING.md "PR package" requires in the description stays.
Reviewed at b12d7d5f.
| // Standard interleaved RoPE (GGML_ROPE_TYPE_NORMAL = 0) on [qdim, H, T_s, B]. | ||
| q = ggml_reshape_4d(ctx, q, qdim, H, T_s, B); | ||
| k = ggml_reshape_4d(ctx, k, qdim, H, T_s, B); | ||
| q = ggml_rope_ext(ctx, q, positions, nullptr, qdim, GGML_ROPE_TYPE_NORMAL, 0, rope_base, 1.0f, 0.0f, 1.0f, 32.0f, | ||
| 1.0f); | ||
| k = ggml_rope_ext(ctx, k, positions, nullptr, qdim, GGML_ROPE_TYPE_NORMAL, 0, rope_base, 1.0f, 0.0f, 1.0f, 32.0f, | ||
| 1.0f); |
There was a problem hiding this comment.
F1 major The Zapformer graph computes RoPE angles in F32 with ggml_rope_ext, but the reference applies the checkpoint's F16-rounded cos/sin tables, and this mismatch accounts for nearly all of the encoder drift that tests/tolerances/gigaam-v4.json then absorbs.
Problem: load_model fills the rope_bank cos/sin parameters from the checkpoint, which stores them in F16; they differ from an exact F32 table by up to 2.4e-4. Running the reference on samples/ru.wav once with the checkpoint tables and once with exact F32 tables moves enc.out by 5.68e-4 max and 5.82e-5 mean, against this PR's C++-vs-reference 5.70e-4 and 5.82e-5. In my port of the same model, replacing ggml_rope_ext with host-built tables rounded through F16 removes that drift (CPU, F32, one thread, samples/ru.wav; my reference is the gigaam package at e9bbf2e7, which reads the same F16 tables):
| RoPE in the C++ graph | enc.out max_abs |
mean_abs |
|---|---|---|
ggml_rope_ext, F32 angles (this PR) |
5.700e-04 | 5.820e-05 |
| host-built tables rounded through F16 | 9.939e-06 | 9.785e-07 |
With the tables, enc.out max_abs is 1.2e-05 on jfk and 1.3e-05 on fleurs-ru. The tolerance file sets enc.out and rnnt.encoded to 1.5e-03, 27x the v3 Conformer's 5.5e-05, and its drift sources name SDPA, feed-forward, and convolution noise, not the table rounding. A gate that wide also passes an encoder regression of the same size, such as a wrong mask on the padded frame or a mis-scaled residual.
Reproducer (reference side)
# uv run --project scripts/envs/gigaam-v4 python rope_exp.py <worktree> <GigaAM-v4 snapshot> samples/ru.wav
model, _ = load_model(snap) # scripts/lib/gigaam_v4_hf.py
enc = model.encoder
tbl = enc.encoder.rope_bank.tables["ed32_S10000_b10000"]
inv = 1.0 / 10000 ** (torch.arange(0, 32, 2, dtype=torch.float32) / 32)
fr = torch.outer(torch.arange(10000, dtype=torch.float32), inv)
f, fl = model.preprocessor(wav, ln)
e16, _ = enc(f, fl) # checkpoint (F16-rounded) tables
tbl.cos.data.copy_(fr.cos()[None, None]); tbl.sin.data.copy_(fr.sin()[None, None])
e32, _ = enc(f, fl) # exact tables, what ggml_rope_ext computes
print((e16 - e32).abs().max(), (e16 - e32).abs().mean())
# actual: 5.677e-04 5.815e-05 (PR's C++ vs reference on ru: 5.700e-04 5.820e-05)
# expected: the C++ graph matches the e16 path, leaving only float noiseProposed solution: rotate with the same cos/sin values as the reference, either host-built and rounded through F16 at load or written into the GGUF from the checkpoint, then re-derive every enc.* and rnnt.encoded entry with the same 1.5x recipe; in my port those entries come out around 2e-05. The rotation is on adjacent pairs, so it takes a few ops instead of one ggml_rope_ext. If you keep ggml_rope_ext, name the table rounding in the tolerance file as the dominant drift source, with its measured share of enc.out.
Host-built tables, from my port
Two F32 inputs per stack, cos and sin, shaped ne=[1, qdim/2, 1, T_s], filled after allocation:
for (int64_t i = 0; i < half; ++i) {
const float inv_freq = 1.0f / std::pow(theta, static_cast<float>(2 * i) / (2 * half));
for (int64_t t = 0; t < T; ++t) {
const float angle = static_cast<float>(t) * inv_freq;
cos_buf[t * half + i] = ggml_fp16_to_fp32(ggml_fp32_to_fp16(std::cos(angle)));
sin_buf[t * half + i] = ggml_fp16_to_fp32(ggml_fp32_to_fp16(std::sin(angle)));
}
}In the graph, with x viewed as [2, qdim/2, H, T]:
y0 = x0 * cos - x1 * sin; // even lanes
y1 = x0 * sin + x1 * cos; // odd lanesThere was a problem hiding this comment.
Fixed in e84a607. The graph no longer uses ggml_rope_ext: zap_rope rotates adjacent pairs by cos/sin tables that fill_zapformer_rope_tables builds at run time from the reference's F32 angles, rounded through F16. They equal the checkpoint's tables bit for bit up to position 824 (two later entries differ by one F16 ulp), and a window encodes at most 625 positions, so existing GGUFs keep working and nothing new goes into the file. q and k come out in planar lane order, which the attention dot product does not see.
enc.out is now 1.299e-05 max / 9.99e-07 mean on ru and 1.073e-05 / 1.08e-06 on fleurs-en (was 5.70e-04 / 5.82e-05), in line with your numbers. tests/tolerances/gigaam-v4.json is re-derived with the same 1.5x recipe (enc.out 1.5e-03 -> 2.0e-05, stages 5.6e-04 -> 6.8e-06..9.5e-06), and its drift-source list now names the table rounding. Thanks for the reproducer.
Cost: the rotation is a few ops instead of one ggml_rope_ext; Q8_0 encode on M5 Max Metal goes from 11.9 to 13.0 ms on jfk and 32.1 to 34.4 ms on ru-long (CPU about +5%). FLEURS F32 (Metal): ru 4.3501% (reference 4.3435%), en 4.9240% (reference 4.9171%, one more substitution), both within the +0.01pp gate; hypotheses equal the reference's on 767/775 ru and 640/647 en (766 and 639 before).
| "source_model": { | ||
| "hf_repo": "ai-sage/GigaAM-v4", | ||
| "hf_revision": "180301a192bb45bc2b2ca122e0d4aab24ffe7a96" | ||
| }, | ||
| "reference": { | ||
| "kind": "author_repo_gigaam", | ||
| "source": "https://huggingface.co/ai-sage/GigaAM-v4/blob/180301a192bb45bc2b2ca122e0d4aab24ffe7a96/modeling_gigaam.py", | ||
| "revision": "180301a192bb45bc2b2ca122e0d4aab24ffe7a96", | ||
| "entrypoint": "scripts/dump_reference_gigaam_v4_hf.py", | ||
| "env": "gigaam-v4", | ||
| "variant_key": "v4_e2e_rnnt", | ||
| "dump_args": ["--variant", "v4_e2e_rnnt"] | ||
| }, |
There was a problem hiding this comment.
F2 major Adding the v4 golden manifest makes scripts/lib/test_gigaam_hf.py fail, which CI runs as the step "GigaAM variant sources and loader": the test expects every gigaam manifest to name a variant of lib.gigaam_hf.VARIANTS, and the v4 pin lives in lib.gigaam_v4_hf
Problem: The python-bindings workflow runs this file on any PR touching src/, scripts/lib/ or tests/**, so this PR's CI goes red once the workflows are approved. The PR filtered the same glob in scripts/test_convert_gigaam.py but missed this second consumer, and the porting log and PR body report only test_convert_gigaam.py.
uv run scripts/lib/test_gigaam_hf.py
# at b12d7d5f: FAILED (failures=1) in SourceTableTest.test_every_golden_manifest_names_the_pinned_source_of_its_variant
# at af4ea6d4: Ran 23 tests ... OK
# expected: OKProposed solution: F8 removes the cause: with the v4 source recorded in gigaam_hf.VARIANTS, this check covers the v4 manifest as it is (test_only_multilingual_large_ctc_is_built_from_its_snapshot then needs the new key too). If F8 is deferred, make SourceTableTest skip manifests whose reference.entrypoint is not the author dumper, as test_convert_gigaam.py does, which leaves the v4 pin checked only by GigaamV4PinTest.
There was a problem hiding this comment.
Fixed in e84a607, without routing v4 through gigaam_hf.VARIANTS: there from_snapshot=True means "build with the gigaam_hf snapshot loader", which builds the Conformer model, not GigaAMDualASR (see the reply on F8). SourceTableTest now checks only manifests whose entrypoint is the author dumper and asserts the others are the v4 dumper; the v4 manifest is checked by the new scripts/test_gigaam_v4.py, which is also a step in the python-bindings workflow. uv run scripts/lib/test_gigaam_hf.py passes.
| const int ws_ctx = std::max(0, a - k_window_ctx_frames); | ||
| const int ws = ws_ctx - ws_ctx % ws_align; |
There was a problem hiding this comment.
F3 major The long-form window alignment fix has no test: no case runs a Zapformer clip whose window starts on an odd encoder frame.
Problem: the alignment fixes a real defect; my port has the same defect and lacks this fix. The evidence for it here is one manual run (22 word edits on 12 composite clips before the change). Both smoke cases and both golden-manifest cases are shorter than one 25 s window, so they never reach the windowed loop, and dropping the ws_align rounding, or computing it from the wrong stage, leaves every test green.
Proposed solution: add a v4 case longer than one window whose unrounded window start (a - k_window_ctx_frames) is odd, to the smoke test or as a golden-manifest case, with the PyTorch transcript of the same windows as a literal, and show it failing on d0d1efb.
There was a problem hiding this comment.
Added in e84a607: transcribe_gigaam_v4_e2e_smoke now has samples/dots.wav (35.3 s, T_enc 883, two windows; the second would start on odd frame 391 and starts on 390). The expected text is the PyTorch reference run on the same windows. With the rounding removed the test fails on CPU and on Metal:
FAIL [cpu] dots.wav: edit_distance=2 > 0
FAIL [gpu] dots.wav: edit_distance=2 > 0
("future. You" for "future you"). It is exact on F32, F16 and Q8_0; the K-quants drop a comma there, so the test reads general.file_type and skips that check for them.
| ggml_tensor * valid_s = (ds == 1) ? eb.zap_valid_mask_in : nullptr; | ||
| ggml_tensor * attn_mask_s = (ds == 1) ? eb.zap_attn_mask_in : nullptr; | ||
| const int64_t T_valid_s = (ds == 1) ? T_orig : T_s; |
There was a problem hiding this comment.
F5 minor The loader accepts a stage downsampling factor between 1 and the largest one, but the graph masks the padded tail only in stages with factor 1, so such a stage attends to and averages over padded frame groups that the reference masks
Problem: weights.cpp accepts any factor that divides the largest (the PR body says the loader rejects geometry the graph cannot run), so a GGUF with factors such as 1,2,4,2 (the ZapformerEncoder default) loads and gives encoder output that differs from the reference whenever T_enc % 4 is 1. GigaAM-v4's 1,2,1 is not affected.
Proposed solution: Decide each stage's mask from that stage's own factor: when padding exists, build the stage's valid mask from valid[::ds] (and the matching additive attention mask) with T_valid_s the count of valid group starts, so that it equals the stage-1 mask only when ds == 1 and nothing when no group start is padded. Alternatively, have the loader refuse any factor other than 1 and the largest, so that the check matches what the graph implements.
There was a problem hiding this comment.
Took the second option in e84a607: the loader accepts only 1 or the largest factor (gigaam: stage <s> downsampling <d> is not supported (each stage must use 1 or the largest factor, <max>)), and the converter refuses the same config before reading tensors. Intermediate-rate masks can come with a checkpoint that needs them.
| causal_frontend = bool(enc_cfg.get("causal_frontend", True)) | ||
| activation = str(enc_cfg.get("activation", "SiLU")).lower() | ||
| if activation != "silu": | ||
| raise ValueError(f"unsupported Zapformer activation {activation!r} (only SiLU implemented)") |
There was a problem hiding this comment.
F6 minor convert-gigaam-v4.py converts encoder configs that the offline Zapformer graph does not implement without an error, and assumes defaults that differ from the reference's.
Problem: the graph implements full-context SiLU Zapformer without language conditioning, and the converter accepts a local directory. It checks only activation, and only where the config names it: a config without causal_frontend (reference default False, converter writes True) or without activation (reference default swish, converter assumes SiLU) converts silently. So does a language-conditioned checkpoint (cfg.language_conditioning, with encoder.language_film and language_fusion tensors, as in GigaAM-Multilingual-v2), a limited-context one (dual_mode false with causal true and chunk_size > 0, or window_size or chunk_window other than -1), or one whose embed_dim differs from encoder_dim[0]. Each gives a GGUF that loads and transcribes with no signal that it does not match the checkpoint.
Proposed solution: decide support from what the reference reads: for every encoder config key ZapformerEncoder's constructor takes, compare the effective value (the config value, or the reference default when absent) with the value the graph implements, and refuse with the key and the value on any difference, before reading any tensor; refuse an enabled cfg.language_conditioning the same way. My port refuses the language-conditioned and limited-context cases this way. F7 catches the modules such configs add as tensors.
There was a problem hiding this comment.
Fixed in e84a607. check_supported_config runs before any tensor is read and compares every ZapformerEncoder argument's effective value (the config's, or the constructor default when absent) with what the graph implements. It refuses: activation other than SiLU (so a config without activation is refused, default swish), causal_frontend other than true (default false), causal single-mode encoders, embed_dim other than the first encoder_dim, a downsampling factor other than 1 or the largest, mixed query head dims, cfg.language_conditioning, and keys ZapformerEncoder does not take. window_size / chunk_window alone are not refused, since _allowed ignores them when the offline chunk is <= 0, which is what dual mode gives. Each refusal has a test in scripts/test_gigaam_v4.py. The F32 GGUF from the pinned checkpoint is byte-identical (6cd32ae7…cd745).
| if stage_dims[-1] != d_model: | ||
| raise ValueError(f"expected final stage dim {stage_dims[-1]} == {d_model}") | ||
|
|
||
| # RNN-T head hparams | ||
| pred_cfg = head_cfg["decoder"] | ||
| joint_cfg = head_cfg["joint"] | ||
| pred_hidden = int(pred_cfg["pred_hidden"]) | ||
| pred_n_layers = int(pred_cfg["pred_rnn_layers"]) | ||
| pred_vocab = int(pred_cfg["num_classes"]) | ||
| joint_hidden = int(joint_cfg["joint_hidden"]) | ||
| joint_n_classes = int(joint_cfg["num_classes"]) | ||
| if len(tok["tokens"]) != pred_vocab or tok["blank_id"] != pred_vocab - 1: | ||
| raise ValueError( | ||
| f"tokenizer size {len(tok['tokens'])} / blank {tok['blank_id']} != pred_vocab {pred_vocab}" | ||
| ) |
There was a problem hiding this comment.
F29 nit Converter errors render as false equalities: expected final stage dim 1024 == 768
Problem: The rendered messages assert an equality that is false and do not name the config key to look at.
Proposed solution: Name the config key and the values, as prose. Rendered for encoder_dim 768,1024,1024 and for a 1025-token e2e tokenizer against num_classes 1026:
cfg.encoder.encoder_dim is 768,1024,1024, but the converter needs the last stage dim (1024) to equal the first (768, d_model); this encoder layout is not supported
e2e_tokenizer.model gives 1025 tokens (blank id 1024), but cfg.heads.e2e.decoder.num_classes is 1026; the tokenizer and the RNN-T head must agree
There was a problem hiding this comment.
Fixed in e84a607: both messages name the config key and the values. The encoder_dim check moved into check_supported_config.
| C++ dumps `enc.stage.<s>.out` for each stack, before frames are | ||
| unstacked, so the shapes are `[T_pad / ds, ds * D]` on both sides. |
There was a problem hiding this comment.
F30 nit The change calls a ZapformerStack a "stage" in names and dumps but a "stack" in prose, with no sentence that equates them
Problem: Upstream modeling_gigaam.py names the unit ZapformerStack (held in encoder.encoders) and uses "stage" only for the subsampling convs. The C++ types (ZapformerStageHParams, zap_stages), the GGUF keys (stt.gigaam.encoder.stage_*), and the dumps (enc.stage.<s>.out) say stage, while the family doc, porting log, and tolerance comment say "three stacks", "the middle stack", "for each stack". A reader who greps for one word finds half the material.
Proposed solution: Keep the GGUF names and define the term once where the family doc first uses it, for example "stage s is encoder.encoders[s], a ZapformerStack", then use "stage" in the rest of the doc, the porting log, and the tolerance comment.
There was a problem hiding this comment.
Done in e84a607: the family doc defines stage s as encoder.encoders[s], a ZapformerStack, where it first uses the term, and the doc, the porting log and the tolerance comment now say "stage".
| if (auto st = read_required_u32_kv(gguf, "stt.gigaam.encoder.n_layers", kFamilyTag, hp.enc_n_layers); | ||
| st != TRANSCRIBE_OK) { | ||
| return st; | ||
| } | ||
| if (auto st = read_required_u32_kv(gguf, "stt.gigaam.encoder.d_model", kFamilyTag, hp.enc_d_model); | ||
| st != TRANSCRIBE_OK) { | ||
| return st; | ||
| } | ||
| if (auto st = read_required_u32_kv(gguf, "stt.gigaam.encoder.feat_in", kFamilyTag, hp.enc_feat_in); | ||
| st != TRANSCRIBE_OK) { | ||
| return st; | ||
| } | ||
| if (auto st = read_required_u32_kv(gguf, "stt.gigaam.encoder.subsampling_factor", kFamilyTag, | ||
| hp.enc_subsampling_factor); | ||
| st != TRANSCRIBE_OK) { | ||
| return st; | ||
| } |
There was a problem hiding this comment.
F31 nit The Zapformer branch of read_gigaam_hparams repeats four reads the Conformer branch already has; hoist them above the branch
Problem: Reading the four shared keys once before the branch removes 17 lines and leaves the Conformer reads unindented, so the diff of the Conformer path shrinks to the lines that differ.
Proposed solution: Read the four shared keys once before the branch; keep only Conformer-specific keys (n_heads, d_ff, conv_kernel, subs_kernel_size, pos_emb_max_len, the two strings) inside the Conformer branch.
There was a problem hiding this comment.
Done in e84a607: n_layers, d_model, subsampling_factor and feat_in are read once before the branch.
| int max_ds = 1; | ||
| for (const auto & shp : hp.zap_stages) { | ||
| if (shp.downsampling > max_ds) { | ||
| max_ds = shp.downsampling; | ||
| } | ||
| } |
There was a problem hiding this comment.
F32 nit The largest Zapformer downsampling factor is computed in three places; store it in GigaamHParams where the loader validates it
Problem: The padding and the long-form window alignment are right only while the three loops agree; one field set by the loader after its divisibility check removes two of them.
Proposed solution: Add int32_t zap_max_downsampling = 1; to GigaamHParams, set it in read_gigaam_hparams after the divisibility check, and read it in build_zapformer_encoder_graph and run() (where Conformer keeps 1).
There was a problem hiding this comment.
Done in e84a607: GigaamHParams::zap_max_downsampling, set by the loader after the factor check and read by the graph and the window plan (1 for Conformer).
| KvResult read_float32_array_kv(const gguf_context * ctx, const char * key, std::vector<float> & out) { | ||
| const int64_t key_id = gguf_find_key(ctx, key); | ||
| if (key_id < 0) { | ||
| return KvResult::Absent; | ||
| } | ||
| if (gguf_get_kv_type(ctx, key_id) != GGUF_TYPE_ARRAY) { | ||
| return KvResult::BadType; | ||
| } | ||
| if (gguf_get_arr_type(ctx, key_id) != GGUF_TYPE_FLOAT32) { | ||
| return KvResult::BadType; | ||
| } | ||
| const size_t n = gguf_get_arr_n(ctx, key_id); | ||
| const void * data = gguf_get_arr_data(ctx, key_id); | ||
| if (data == nullptr && n > 0) { | ||
| return KvResult::BadType; | ||
| } | ||
| std::vector<float> tmp(n); | ||
| if (n > 0) { | ||
| std::memcpy(tmp.data(), data, n * sizeof(float)); | ||
| } | ||
| out = std::move(tmp); | ||
| return KvResult::Ok; | ||
| } |
There was a problem hiding this comment.
F33 nit read_float32_array_kv is a copy of read_int32_array_kv that differs only in the GGUF type tag and the element type
Proposed solution: Implement both through one file-local template parameterized by the element type and the gguf_type (for example template <typename T> KvResult read_scalar_array_kv(const gguf_context *, const char *, gguf_type, std::vector<T> &)), keeping the two public declarations in transcribe-meta.h as thin wrappers.
There was a problem hiding this comment.
Done in e84a607: both are thin wrappers around a file-local read_scalar_array_kv<T>.
Direct CONV_2D for the strided and 1x1 frontend convs (conv1 stays on im2col for precision), direct depthwise for the ConvNeXt conv, flash attention with an F16 key mask for odd lengths, no copies of the q/k/v and gate views, and the conv module in the channel-innermost layout (direct depthwise conv, time mean via pool_2d). M1 Metal Q8_0 encode: jfk 113 -> 75 ms, ru-long 406 -> 258 ms. validate.py all gigaam-v4-e2e-rnnt: 9/9 on both cases, drift equal or lower; FLEURS ru/en WER unchanged (F32 4.34% / 4.91%).
Start the speculative span at 8 frames after a token and double it over blank runs up to 32. Same tokens, about 25% less joint work. FLEURS ru: transcripts identical on v3-e2e-rnnt and v3-rnnt (775/775).
The calling thread sleeps in the backend synchronize for the whole GPU encode; macOS clocks its core down and the host RNN-T decode right after it runs 4-8x slower. Spin a helper thread during the GPU compute. M1 Metal: decode 30 -> 4 ms on jfk. TRANSCRIBE_GIGAAM_NO_KEEP_WARM=1 turns it off.
|
Thanks all for the comments and desire to get this in appreciate the work and review, I'm on vacation a few days but this will come in! |
|
I built and tested this PR locally at
This covers the native CPU engine only; I did not test CUDA, Vulkan, or the Handy app. |
|
Thanks for the Zapformer port. I use Hex locally for Russian dictation, still on GigaAM v3, and this is what Hex needs before it can offer v4. |
…tests) The reference rotates RoPE by the checkpoint's F16 cos/sin tables, and ggml_rope_ext's F32 tables were nearly all of the encoder drift (enc.out 5.7e-4 on ru). The graph now rotates adjacent pairs by tables built at run time and rounded through F16, which equal the checkpoint's up to position 824; enc.out drift is 1.3e-5, and the tolerances are re-derived with the same 1.5x recipe. Encode is ~8% slower on Metal for it. Rounding a long-form window start down could encode 626 frames; plan_windows now reserves the alignment. The smoke test gets samples/ dots.wav, whose second window would start on an odd frame, with the PyTorch transcript of the same windows, and runs again on a GPU backend. The converter and the loader refuse configs the graph does not implement (non-SiLU, non-causal frontend, limited context, intermediate downsampling, mixed qdim, language conditioning, unknown keys, unconverted tensors); a fixture loader smoke covers the loader's refusals. test_gigaam_hf.py no longer fails on the v4 manifest, and scripts/test_gigaam_v4.py tests the pin, the converter and the dumper refusals. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@vlsi thanks for the thorough review, and for the numbers from your port. All inline findings are answered in their threads; the fixes are in e84a607, on top of the maintainer's three graph commits. The three blockers:
F5, F6, F7 and F12 are handled as you suggested, by refusing everything but what the graph implements (converter and loader). F10 is a fixture loader smoke with eight mutants. The findings that are not inline:
FLEURS F32 after the change: ru 4.35% / en 4.92%, both within +0.01pp of the reference. |
Replace the element-wise RoPE (per q and k: a de-interleave copy, four muls, an add, a sub and a concat) with one batched mul_mat over q and k together: fill_zapformer_rope_tables builds, from the same F16-rounded cos/sin, a block-diagonal 2x2 rotation per lane pair and frame ([qdim, qdim, T_pad], shared by every layer), and q/k are strided views of the product. src1 is kept in F32 so Metal's matrix kernel does not round q and k to half. Q8_0 encode, min of 3 interleaved rounds (M1): Metal jfk 82.9 -> 75.9 ms, ru-long 284.6 -> 258.6 ms; CPU jfk 350.6 -> 347.7 ms, ru-long 1161.9 -> 1147.2 ms. enc.out drift (CPU, 1 thread) is 1.05e-5 on ru and 1.10e-5 on fleurs-en, within the tolerances; FLEURS F32 (Metal, batch 8) still matches the reference's error counts (ru 4.3435%, en 4.9171%).
Each Zapformer stage computes x + proj_out(r0 * proj(x) + ...) with r0 ~= -1 and proj_out * proj ~= I in stages 0 and 2 (||I - P'P|| 0.003 at F32), so the stage replaces its residual. Under Q4_K the product is 0.10 off identity and about 10% of the residual leaks through. Route enc.stages.<s>.proj.weight / proj_out.weight through linear_attn_out like the attention output projection: Q8_0 in Q4_K_M and Q5_K_M; F16, Q8_0 and Q6_K files are byte-identical. Only gigaam-v4 has these tensor names. FLEURS en Q4_K_M (Metal, batch 8): 5.68% -> 5.23% (F32 4.92%); FLEURS ru: 4.52% -> 4.46%. Q4_K_M grows 140.9 -> 143.7 MB.
|
this will be pulled in today, thanks again for all the support folks, i will also try to cut a small release with it asap |
Shorter sentences and lists in the family doc section, final WER for every quant (FLEURS ru/en, LibriSpeech test-clean), the stage-projection quantization note, and the serial-batching decision. The porting log drops superseded entries and keeps one fact per bullet.
An asr-publication-v2 target can be marked opt_in: it is required only for records that list its machine in speed_opt_in. Adds an m1 target (cpu, metal) on that basis, so a record can publish Apple M1 numbers in place of a missing base M4 run. No existing record opts in; publication check results for every other record are unchanged.
Catalog record, model page, HF card spec and family page entry. Accuracy: LibriSpeech test-clean for every quant, FLEURS ru/en at Q8_0 (asr-publication-v2, L40S). Speed: Apple M4 Max, Ryzen 7 PRO 4750U, and Apple M1 standing in for the base M4, which was not available.
Plain-language summary and WER note, a short 'What it does' list, which file to download, and how to read the speed tables. Validation and conversion details move to a 'For developers' section.
Drop what the library docs already say (offline use, audio conversion) and the repeated feature list; no semicolons in the prose.
TLDR: GigaAM v4 released, it is contains new encoder, I haved added the support from it and validated
Summary
GigaAM-v4 (ai-sage/GigaAM-v4, released 2026-11-26) replaces the v3 Conformer with a Zapformer encoder: a 2D conv frontend and three stages (
ZapformerStack) of 4/11/4 layers at 768/1024/768 dims, where the middle stage runs at half the frame rate on stacked pairs of frames. The RNN-T head (320-wide LSTM predictor and joint, 1024 SentencePiece pieces + blank) and the mel frontend are the same as in v3. The model is trained on Russian and English and outputs cased, punctuated text.The encoder is selected by the GGUF string
stt.gigaam.encoder.type:zapformerfor v4; absent orconformerfor v3 and Multilingual GGUFs, which take the same code path as before. An unknown value fails the load withTRANSCRIBE_ERR_GGUFandgigaam: unsupported stt.gigaam.encoder.type=<value> (expected conformer or zapformer); stage geometry the graph does not implement fails withTRANSCRIBE_ERR_GGUFand agigaam: stage <s> ...message naming the values. An odd frame count is padded to the largest downsampling factor, and the padded frame is masked in the full-rate stages.The Zapformer port is by @70sh1 (first commit, cherry-picked from https://github.com/70sh1/transcribe.cpp/tree/gigaam-v4 without conflicts). The second commit adds what the repo's gates need to check it, and a few fixes; the three commits after it are the maintainer's graph-speed changes, and the last one addresses the review:
gigaampackage pin has no Zapformer, so the reference is themodeling_gigaam.pythat ai-sage/GigaAM-v4 ships, pinned at 180301a1 inscripts/lib/gigaam_v4_hf.pyand built locally (notrust_remote_code) in its own envscripts/envs/gigaam-v4. The v3 env and reference do not change.scripts/dump_reference_gigaam_v4_hf.pyandscripts/wer/run_reference_gigaam_v4_hf.py(reference WER baseline), golden manifest (ru, which has an odd encoder length, andfleurs-en) andtests/tolerances/gigaam-v4.json(1.5x the worst observed drift, rounded up to two significant digits; no 1e-6 floor, unlikegigaam.json).enc.stage.<s>.outfor each stage, since the Conformer per-block dumps don't map onto Zapformer.ggml_rope_ext's F32 ones; that was nearly all of the encoder drift, and the tolerances are 75x tighter for it.samples/dots.wav.qdim, even conv kernel,feat_inother than the mel count (loader,TRANSCRIBE_ERR_GGUF).transcribe_gigaam_smoke(fixture, default build) tests the loader's refusals.transcribe_gigaam_v4_e2e_smoke(real model,TRANSCRIBE_GIGAAM_V4_GGUF): transcripts onru,fleurs-enand the windoweddots, the same clips throughtranscribe_run_batch, on CPU and on a GPU backend when present.scripts/test_gigaam_v4.py(python-bindings workflow) tests the pin and the converter and dumper refusals.docs/porting/families/gigaam.md, and a user section indocs/models/gigaam.md.Part of #279 (coordination with @70sh1: #279 (comment)).
Scope. Not included: the
rawhead (convert-gigaam-v4.py --head rawwrites it, but it has no golden manifest and is not validated), thectcbranch, streaming, and packed batching for Zapformer (run_batchtakes the per-utterance loop). No GGUF upload, no catalog entry.AI Assistance
Generated with Claude Opus 5.5
Reviewed: ChatGPT Astra 5.2, Qwen 4
Validation
macOS, Apple Silicon. Numerical validation is CPU F32, one thread.
Conversion. Source
ai-sage/GigaAM-v4@180301a192bb45bc2b2ca122e0d4aab24ffe7a96.6cd32ae7ded4ec470075ac7acb79c248b64818f118c6913a96c4a81ae11cd7452316a5ed089c77567ad0efcb2a334d8af5ab043188f877d47d77b39464ecb39edebd6179b9948beba5c60c0944285e577f732610dd50dee1233884e4b46e3e292a026b8f602b657009440404c58babff079ca459d947f2af9b481e6e0cb2a38b6e624fe398f73eabb810aca10b1fb7189154ba013510e7b55c0ec8ebba229879ab83cc9a62141e042f6b0e24441256f2029360fa0f272198e44f91909485965aF32 and Q8_0 are byte-identical to the ones published at https://huggingface.co/70sh1/gigaam-v4-e2e-rnnt-gguf.
Preflight. Gate A has two WARNs, both expected: the frontend is declared inside
config.json(nopreprocessor_config.json; recorded in the intake), and capabilities are skipped until a GGUF exists. Gate B passes.Gate A / Gate B stdout
Numerical validation.
uv run scripts/validate.py all --family gigaam --variant gigaam-v4-e2e-rnnt --report: overall PASS. All 7 reference tensors are within tolerance on both cases (the tool prints 9/9;dec.enc_outandenc.mel.inare C++-only dumps with no reference counterpart), and the transcripts are exact.validate.py report
Tests.
ctest --test-dir build: 100% tests passed out of 98 (real-model tests skip without their env vars), including the new fixture smoketranscribe_gigaam_smoke. WithTRANSCRIBE_GIGAAM_V4_GGUFandTRANSCRIBE_GIGAAM_GGUFset to the v4 GGUF,ctest --test-dir build -R gigaam --no-tests=errorpassestranscribe_gigaam_smoke,transcribe_gigaam_v4_e2e_smoke(CPU and Metal passes) andtranscribe_gigaam_workspace_release_smoke(3/3) for each of F32, F16 and Q8_0.scripts/lib/test_gigaam_hf.py,scripts/test_gigaam_v4.py,scripts/test_convert_gigaam.pyandscripts/lib/test_hf_source.pypass.scripts/ci/clang-format.sh --checkis clean.Transcripts. C++ compared with PyTorch on samples/ru.wav, fleurs-ru.wav, ru-short.wav, fleurs-en.wav and jfk.wav: they match for F32, F16, Q8_0, Q6_K and Q5_K_M on both CPU and Metal. Q4_K_M adds a comma on
fleurs-enand drops one onru-short. samples/dots.wav (35.3 s, windowed) equals the PyTorch reference run on the same windows for F32, F16 and Q8_0 on CPU and Metal (in the smoke test).Long-form window alignment was checked on 12 clips made of consecutive FLEURS ru/en utterances (34-98 s), each with at least one window starting on an odd frame: C++ F32 equals PyTorch run with the same windows on all 12. Before the change it was 22 word edits away from that. WER against the FLEURS text did not move measurably.
WER on FLEURS test. The reference row is the PyTorch module (F32, CPU, whole-clip decode,
scripts/wer/run_reference_gigaam_v4_hf.py). The C++ rows use Metal,scripts/wer/run.py --batch-size 8, timestamps none. This is not a publication-profile run.F32 is within the family's
C++ <= reference + 0.01ppgate: ru 4.3501% vs 4.3435%, en 4.9240% vs 4.9171% (one more substitution each). F32 hypotheses equal the reference's on 767/775 ru and 640/647 en utterances; the others are near ties (a comma, a plural ending, a transliterated name). The v3 number is within 0.03pp of the published catalog value (5.35%). Other quants, CUDA/Vulkan, and benchmarks were not run.