Skip to content

fix(gemma4): restore E-series Conformer audio parity with the reference pipeline - #796

Merged
inureyes merged 2 commits into
mainfrom
fix/issue-782-gemma4-audio-features
Jul 13, 2026
Merged

inureyes merged 2 commits into
mainfrom
fix/issue-782-gemma4-audio-features

Conversation

@inureyes

Copy link
Copy Markdown
Member

Summary

Fixes the garbled audio perception on the Gemma 4 E-series (E2B/E4B) Conformer path: a 16 kHz PCM16 clip that the 12B Unified path transcribed correctly came out as nonsense phonemes on E2B/E4B. A numerical reference-diff harness against the canonical Gemma4AudioFeatureExtractor (transformers 5.8.0, identical to upstream mlx-vlm main) and the upstream mlx-vlm gemma4 audio tower localized two independent root causes, both fixed here. This is the completion of the incomplete #436 fix.

Numerical premise check

Method: extract log-mel features for one fixed 16 kHz mono PCM16 speech clip (98832 samples, 6.18 s) with the reference extractor in Python and with mlxcel's extractor on the same bytes, then compare per-frame per-mel-bin; afterwards feed the bit-identical mel input through mlxcel's Conformer tower (env-gated stage dumper) and upstream mlx-vlm's tower and compare per stage.

Root cause 1, mel front-end (src/audio/feature_extractor.rs). mlxcel was ported from the previous generation of the extractor and diverged on four ops: fft_overdrive defaulted to true (fft_length 1024) where the reference defaults to false (512); log floor was the hard clamp ln(max(mel, 1e-3)) instead of the additive ln(mel + 1e-3); the unfold window was frame_length instead of frame_length + 1, emitting one extra frame whenever total_len is a multiple of the hop (1248 vs 1247 frames on the issue's 12.5 s clip); and the frame mask was computed at the window START (frame 0 wrongly invalid, tail frames straddling right-padding wrongly valid) instead of the window END, without zeroing invalid rows. Before the fix the features diverged from the reference by RMS 0.818, max abs 6.89, mean offset +0.65 (about ln 2, from the fft_overdrive doubling), on features whose own RMS is 3.14. After the fix: max abs 4.8e-7, RMS 7e-8 (f32 rounding), identical shapes and masks on both test clips including the 199680-sample edge case. Confirmation that the reference generation is what the checkpoints expect: the installed mlx-vlm 0.4.4, whose extractor still has the OLD semantics (fft_overdrive true, no left-pad, clamp floor), reproduces the exact same "cannot hear the audio" failure end to end on gemma-4-e4b-it-4bit, while upstream mlx-vlm main (new semantics) transcribes the same clip word-exact.

Root cause 2, missing ClippableLinear clamps (src/audio/encoder.rs). The checkpoints ship finite per-layer input_min/max and output_min/max bounds for every audio ClippableLinear (for example lconv1d.linear_end input clamps to about +-5.8 while block activations reach far larger tails) and the reference clamps input and output at inference; the bounds are part of the trained function. mlxcel's AudioLinear skipped them as "training artifacts". With bit-exact mel input, the stage diff against the upstream tower read: in_mel and sscp_out (no ClippableLinear) rel RMS 0.000, then block 0 = 0.079, growing monotonically to block 11 = 0.952 and tower_out = 0.965 (fully decorrelated). After loading and applying the bounds, every stage matches within 8.2e-4 relative RMS (dtype noise) and embed_audio_out within 8.6e-4. The vision tower already applied these bounds; the audio port had dropped them.

What changed

  • src/audio/feature_extractor.rs: fft_overdrive default false; additive mel floor; frame_length + 1 unfold; end-indexed frame mask; zero invalid feature rows; optional per_bin_mean/per_bin_stddev normalization; serde-deserializable config plus from_processor_config honoring a checkpoint-shipped feature_extractor block (the published checkpoints ship none, so reference defaults apply).
  • src/audio/encoder.rs: AudioLinear loads and applies the checkpoint's input/output clamp bounds when present; env-gated MLXCEL_AUDIO_PROBE_DIR stage dumper for future parity diffing.
  • src/vision/gemma4_vl.rs, src/loading/vlm_gemma.rs, src/commands/generate_vlm.rs, src/server/model_worker.rs: the model carries the extractor config from processor_config.json to the CLI and server call sites.
  • src/audio/encoder_tests.rs (new) and extended feature_extractor tests: golden log-mel vector baked from the reference extractor for a fixed synthetic waveform (no network, no Python dependency), reference-default invariants (fft_length 512), frame count, end-indexed tail mask with row zeroing, processor_config.json parsing, and AudioLinear clamp semantics.

Validation (real checkpoints, -t 0)

  • gemma-4-e4b-it-4bit, 16 kHz English clip: word-exact transcription ("The quick brown fox jumps over the lazy dog. The bridge construction was completed in August of 2011."), previously "okran faqchambavadalaijidag ..." nonsense.
  • gemma-4-e4b-it-4bit, Korean clip of the issue's FLEURS ground-truth sentence (say/Yuna TTS at 16 kHz; the FLEURS datasets-server API was persistently 503): near-exact, comparable to upstream mlx-vlm and well inside the issue's ~5.5% CER expectation.
  • gemma-4-e2b-it-4bit and -8bit: transcribe both clips correctly. One prompt/clip combination on the 4-bit E2B ends at EOS before emitting text at -t 0; it perceives the same audio correctly with a slightly different prompt, so it is a knife-edge sampling artifact, not the feature-path defect.
  • 24 kHz source clip on E4B: resample path (fix: Gemma 4 audio understanding (CLI --audio) produces no output (missing 16kHz resample + audio token placed outside the user turn) #436) still word-exact.
  • gemma-4-12b-it-4bit Unified path: unchanged (English clip perceived correctly; the Korean TTS clip produces the same channel-marker loop on the released 0.3.3 binary, pre-existing and unrelated).
  • cargo test --release --lib audio:: 71 passed, loading:: 215 passed, gemma 307 passed; cargo clippy --lib --tests --features metal,accelerate -- -D warnings clean; cargo fmt --all -- --check clean.

Follow-ups (out of scope, from the issue's secondary observations)

Closes #782

The Gemma 4 E-series (E2B/E4B) Conformer audio path produced garbled perception on 16 kHz PCM16 input while the 12B Unified waveform path transcribed the same clip correctly (issue #782, an incomplete-fix follow-up to #436). A reference-diff harness against the canonical Gemma4AudioFeatureExtractor and the upstream mlx-vlm gemma4 audio tower localized two independent root causes, both fixed here.

Root cause 1, mel front-end divergence. src/audio/feature_extractor.rs was ported from the previous generation of the reference extractor and diverged from what the published checkpoints expect on four points: fft_overdrive defaulted to true (fft_length 1024) where the reference defaults to false (512), the log floor was a hard clamp ln(max(mel, 1e-3)) instead of the additive ln(mel + 1e-3), the unfold window was frame_length instead of frame_length + 1 (one extra frame whenever total_len is a multiple of the hop, e.g. 1248 vs 1247 frames for the issue's 12.5 s clip), and the frame validity mask was computed at the window START (wrongly invalidating frame 0, which begins inside the semicausal left-pad, and wrongly validating tail frames straddling the right padding) instead of the window END, without zeroing invalid rows. Measured against the reference on a real 6.18 s speech clip, the produced log-mel features were off by RMS 0.818 (max abs 6.89, mean offset +0.65, approximately ln 2 from the fft_overdrive doubling) on features whose own RMS is 3.14. After the fix the features match the reference bit-exactly within f32 rounding (max abs 4.8e-7) on both test clips, including the frame-count edge case. The old defaults also match the installed mlx-vlm 0.4.4 extractor, which reproduces the same garbled perception end to end, confirming the checkpoint expects the new-generation features.

Root cause 2, missing ClippableLinear clamps. The audio checkpoints ship finite per-layer input_min/max and output_min/max bounds for every ClippableLinear (for example lconv1d.linear_end input clamps to about +-5.8 while block activations reach far larger tails), and the reference applies them at inference; they are part of the trained function. src/audio/encoder.rs AudioLinear skipped them as training artifacts. With bit-exact mel input, the per-block error versus the reference tower compounded from 7.9% relative RMS after block 0 to 95% after block 11. AudioLinear now loads and applies the bounds when present; every stage then matches the reference within 8.2e-4 relative RMS (dtype noise). The vision tower already applied these bounds; the audio port had dropped them.

Also: the extractor config is now read from the checkpoint's processor_config.json feature_extractor block when present (falling back to reference defaults, which is the effective config for the published checkpoints, and honoring per_bin_mean/per_bin_stddev), the Gemma4VLModel carries that config to the CLI and server call sites, and an env-gated MLXCEL_AUDIO_PROBE_DIR stage dumper is added to the audio tower for future parity diffing.

Validation on real checkpoints at -t 0: gemma-4-e4b-it-4bit transcribes a 16 kHz English clip word-exact and a Korean clip near-exact (previously nonsense phonemes), gemma-4-e2b-it-4bit and -8bit likewise, a 24 kHz source clip still resamples and transcribes word-exact (issue #436 path), and gemma-4-12b-it-4bit Unified output is unchanged. Regression tests cover the reference defaults (fft_length 512), a golden log-mel vector produced by the reference extractor, the frame count and end-indexed tail mask with row zeroing, processor_config.json parsing, and the AudioLinear clamp semantics.

Refs #782
@inureyes inureyes added type:bug Bug fixes, error corrections, or issue resolutions priority:high High priority status:review Under review labels Jul 13, 2026
…oint config

Now that the extractor honors a feature_extractor block from processor_config.json, its scalar fields are semi-trusted input read at load. A malformed or hostile block could set hop_length_ms to 0 (divide-by-zero in extract, which on the server aborts the whole worker), an enormous feature_size (unbounded mel filterbank and per-frame buffer allocation), or an enormous frame_length_ms (a runaway fft_length doubling loop). Guard each scalar in AudioFeatureExtractor::new: out-of-range sampling_rate, frame/hop length, and feature_size fall back to the reference defaults, and the derived frame/hop lengths are re-derived from the defaults if they land at zero or past a sane cap. This mirrors the per-bin-vector length validation the extractor already does. The published checkpoints ship no such block, so the default path is unchanged.
@inureyes inureyes added status:done Completed and removed status:review Under review labels Jul 13, 2026
@inureyes
inureyes merged commit 14b26fe into main Jul 13, 2026
4 checks passed
@inureyes
inureyes deleted the fix/issue-782-gemma4-audio-features branch July 13, 2026 13:58
@inureyes inureyes self-assigned this Aug 31, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…ce pipeline (lablup#796)

## Summary

Fixes the garbled audio perception on the Gemma 4 E-series (E2B/E4B) Conformer path: a 16 kHz PCM16 clip that the 12B Unified path transcribed correctly came out as nonsense phonemes on E2B/E4B. A numerical reference-diff harness against the canonical `Gemma4AudioFeatureExtractor` (transformers 5.8.0, identical to upstream mlx-vlm main) and the upstream mlx-vlm gemma4 audio tower localized two independent root causes, both fixed here. This is the completion of the incomplete lablup#436 fix.

## Numerical premise check

Method: extract log-mel features for one fixed 16 kHz mono PCM16 speech clip (98832 samples, 6.18 s) with the reference extractor in Python and with mlxcel's extractor on the same bytes, then compare per-frame per-mel-bin; afterwards feed the bit-identical mel input through mlxcel's Conformer tower (env-gated stage dumper) and upstream mlx-vlm's tower and compare per stage.

Root cause 1, mel front-end (src/audio/feature_extractor.rs). mlxcel was ported from the previous generation of the extractor and diverged on four ops: `fft_overdrive` defaulted to `true` (fft_length 1024) where the reference defaults to `false` (512); log floor was the hard clamp `ln(max(mel, 1e-3))` instead of the additive `ln(mel + 1e-3)`; the unfold window was `frame_length` instead of `frame_length + 1`, emitting one extra frame whenever total_len is a multiple of the hop (1248 vs 1247 frames on the issue's 12.5 s clip); and the frame mask was computed at the window START (frame 0 wrongly invalid, tail frames straddling right-padding wrongly valid) instead of the window END, without zeroing invalid rows. Before the fix the features diverged from the reference by RMS 0.818, max abs 6.89, mean offset +0.65 (about ln 2, from the fft_overdrive doubling), on features whose own RMS is 3.14. After the fix: max abs 4.8e-7, RMS 7e-8 (f32 rounding), identical shapes and masks on both test clips including the 199680-sample edge case. Confirmation that the reference generation is what the checkpoints expect: the installed mlx-vlm 0.4.4, whose extractor still has the OLD semantics (fft_overdrive true, no left-pad, clamp floor), reproduces the exact same "cannot hear the audio" failure end to end on `gemma-4-e4b-it-4bit`, while upstream mlx-vlm main (new semantics) transcribes the same clip word-exact.

Root cause 2, missing ClippableLinear clamps (src/audio/encoder.rs). The checkpoints ship finite per-layer `input_min/max` and `output_min/max` bounds for every audio ClippableLinear (for example `lconv1d.linear_end` input clamps to about +-5.8 while block activations reach far larger tails) and the reference clamps input and output at inference; the bounds are part of the trained function. mlxcel's `AudioLinear` skipped them as "training artifacts". With bit-exact mel input, the stage diff against the upstream tower read: `in_mel` and `sscp_out` (no ClippableLinear) rel RMS 0.000, then block 0 = 0.079, growing monotonically to block 11 = 0.952 and `tower_out` = 0.965 (fully decorrelated). After loading and applying the bounds, every stage matches within 8.2e-4 relative RMS (dtype noise) and `embed_audio_out` within 8.6e-4. The vision tower already applied these bounds; the audio port had dropped them.

## What changed

- `src/audio/feature_extractor.rs`: `fft_overdrive` default false; additive mel floor; `frame_length + 1` unfold; end-indexed frame mask; zero invalid feature rows; optional `per_bin_mean`/`per_bin_stddev` normalization; serde-deserializable config plus `from_processor_config` honoring a checkpoint-shipped `feature_extractor` block (the published checkpoints ship none, so reference defaults apply).
- `src/audio/encoder.rs`: `AudioLinear` loads and applies the checkpoint's input/output clamp bounds when present; env-gated `MLXCEL_AUDIO_PROBE_DIR` stage dumper for future parity diffing.
- `src/vision/gemma4_vl.rs`, `src/loading/vlm_gemma.rs`, `src/commands/generate_vlm.rs`, `src/server/model_worker.rs`: the model carries the extractor config from `processor_config.json` to the CLI and server call sites.
- `src/audio/encoder_tests.rs` (new) and extended `feature_extractor` tests: golden log-mel vector baked from the reference extractor for a fixed synthetic waveform (no network, no Python dependency), reference-default invariants (fft_length 512), frame count, end-indexed tail mask with row zeroing, `processor_config.json` parsing, and `AudioLinear` clamp semantics.

## Validation (real checkpoints, -t 0)

- `gemma-4-e4b-it-4bit`, 16 kHz English clip: word-exact transcription ("The quick brown fox jumps over the lazy dog. The bridge construction was completed in August of 2011."), previously "okran faqchambavadalaijidag ..." nonsense.
- `gemma-4-e4b-it-4bit`, Korean clip of the issue's FLEURS ground-truth sentence (say/Yuna TTS at 16 kHz; the FLEURS datasets-server API was persistently 503): near-exact, comparable to upstream mlx-vlm and well inside the issue's ~5.5% CER expectation.
- `gemma-4-e2b-it-4bit` and `-8bit`: transcribe both clips correctly. One prompt/clip combination on the 4-bit E2B ends at EOS before emitting text at -t 0; it perceives the same audio correctly with a slightly different prompt, so it is a knife-edge sampling artifact, not the feature-path defect.
- 24 kHz source clip on E4B: resample path (lablup#436) still word-exact.
- `gemma-4-12b-it-4bit` Unified path: unchanged (English clip perceived correctly; the Korean TTS clip produces the same channel-marker loop on the released 0.3.3 binary, pre-existing and unrelated).
- `cargo test --release --lib audio::` 71 passed, `loading::` 215 passed, `gemma` 307 passed; `cargo clippy --lib --tests --features metal,accelerate -- -D warnings` clean; `cargo fmt --all -- --check` clean.

## Follow-ups (out of scope, from the issue's secondary observations)

- The raw `<|channel|>thought` marker and thinking stream still leak into CLI output on the E-series generate path (related in spirit to lablup#350/lablup#352).
- `--audio` still rejects IEEE Float WAV (the format datasets-server serves) with an unclear "WAV scan error: failed to fill whole buffer"; wider float-subformat support or a clearer error needs a WAV chunk-parser rework.
- The 12B Unified path emits a channel-marker loop on one synthetic Korean TTS clip (pre-existing on 0.3.3, reproducible).

Closes lablup#782
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority:high High priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Gemma4 E2B/E4B audio transcription is garbled on 16 kHz PCM16 input while the 12B Unified path transcribes the same clip correctly

1 participant