Skip to content

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

Closed

Description

@hoonjae-newmean

Summary

On mlxcel 0.4.0, transcribing a 16 kHz mono PCM16 clip with a Gemma4 E-series checkpoint (gemma-4-e2b-it-4bit / gemma-4-e4b-it-4bit) produces garbled output: the model "hears" a stream of nonsense phonemes and either declares the input unintelligible or reports that no audio was provided. The same clip with the same command on gemma-4-12B-it-4bit (the Unified, encoder-free waveform path) produces a near-correct transcription. The defect is isolated to the E-series Conformer audio feature path. It does not crash (#428) and does not emit 0 tokens (#436), so this is either a regression after #436 or a case the #436 validation clip did not cover.

Background

Gemma4 exposes two distinct audio front-ends in this codebase:

  • E-series (E2B/E4B): a mel spectrogram plus Conformer encoder. The DSP front-end lives in src/audio/feature_extractor.rs (AudioFeatureExtractor, USM-style log-mel), the encoder in src/audio/encoder.rs (SSCP followed by 12 ConformerBlocks and an output projection), and the loader logs "Loaded Gemma4 audio encoder (12 Conformer layers)" from src/loading/vlm_gemma.rs.
  • 12B Unified: an encoder-free waveform path (no mel, no Conformer), noted in src/server/model_worker.rs and src/vision/gemma4_unified.rs.

The reporter observes correct output only on the Unified path, which points at the E-series mel or Conformer stage rather than at token placement or the language model.

The CLI audio flow is in compute_gemma4_audio_embeddings in src/commands/generate_vlm.rs. It computes the placeholder count from duration via audio::compute_audio_num_tokens (ceil(duration_ms / 40), matching the observed 312 soft tokens for 12.5 s), then resamples, extracts the mel spectrogram, and calls get_input_embeddings_with_audio.

Reproduction

The reporter provided a self-contained script that fetches one public Korean speech sample (FLEURS ko_kr, test split, row 0) from the HuggingFace datasets-server API, converts it to 16 kHz mono PCM16 with ffmpeg, and runs both checkpoints. See the Original Suggestion below for the full script and verbatim output.

Ground truth (FLEURS): 다리 밑 수직 간격은 15미터이며 공사는 2011년 8월에 마무리되었으며 해당 다리의 통행금지는 2017년 3월까지이다

  • gemma-4-e4b-it-4bit: leaks a thinking stream whose quoted "perception" is a heavily distorted phonetic rendition ("tadi misukangke gibu ..."), then declares the input garbled. E2B behaves the same.
  • gemma-4-12B-it-4bit: 달래미의 초기 가격은 15m이며, 공사는 2011년 8월에 마무리되었으며, 해당 다리의 통행 금지는 2017년 3월까지입니다. (near-correct)

Both runs report the same clip (199680 samples at 16000 Hz, 12.5 s) and the same 312 soft tokens, so placement and count are correct; what reaches the model appears to be garbled features.

Proposed Solution

Root-cause the E-series audio feature path so E2B/E4B produce a roughly correct transcription on 16 kHz PCM16 input, matching the quality the same checkpoints achieve through other runtimes (the reporter cites roughly 5.5% CER on FLEURS Korean via mlx-vlm).

Implementation Notes

Static analysis (this environment cannot build or run Metal/MLX) supports the reporter's framing and narrows the candidates:

  • Resample gate is not the cause on this input. In src/commands/generate_vlm.rs the resample only runs when sample_rate != 16_000:

    let samples = if sample_rate != 16_000 {
        audio::whisper_mel::resample_to_16k(&samples, sample_rate)
    } else {
        samples
    };

    The clip is already 16 kHz PCM16, so resampling is skipped and root cause B of fix: Gemma 4 audio understanding (CLI --audio) produces no output (missing 16kHz resample + audio token placed outside the user turn) #436 does not apply. The mel and Conformer stages run on the raw 16 kHz waveform.

  • Mel front-end config. src/commands/generate_vlm.rs constructs the extractor with AudioFeatureExtractorConfig::default(). Confirm the default window, hop, fft/num_frequency_bins, mel filter count, min_frequency/max_frequency, and log/normalization match the E-series (USM) reference in src/audio/feature_extractor.rs. A window or hop mismatch would distort the spectrum without changing the frame count enough to break the duration-based placeholder alignment.

  • Conformer encoder. src/audio/encoder.rs (SSCP, 12x ConformerBlock, output projection, ConformerLightConv1d causal depthwise conv, AudioRMSNorm with no +1 offset). Verify weight-key mapping and per-block ordering against the mlx-vlm gemma4 audio.py port, and confirm the depthwise lconv1d channel layout matches the note in src/loading/vlm_gemma.rs about the channel-last depthwise conversion.

  • Feature-to-placeholder alignment. Confirm the masked-scatter in get_input_embeddings_with_audio maps encoder frames onto the 312 audio placeholders in the correct order and count, and that the invalid-frame mask passed as [1, T] is interpreted consistently (the CLI sets true = invalid).

Because the Unified encoder-free path on the same clip is correct, the language model, tokenizer, and audio-token placement are very likely fine; focus on the mel config and Conformer stages.

Acceptance Criteria

Secondary observations (track or split separately)


Original Suggestion

Title: bug(gemma4): E2B/E4B --audio perception is garbled on 16 kHz PCM16 input (0.4.0), while 12B Unified transcribes the same clip correctly (regression or incomplete fix of #436)

Summary

On mlxcel 0.4.0, mlxcel generate -m --audio <16 kHz mono PCM16 wav> -p "Transcribe this audio." -t 0 no longer crashes (#428) and no longer emits 0 tokens (#436), but the model receives garbled audio features: it "hears" a stream of nonsense phonemes and either declares the input unintelligible or concludes no audio was provided. The same clip with the same command on gemma-4-12B-it-4bit (Unified, encoder-free waveform path) produces a near-correct transcription. This isolates the defect to the E-series Conformer audio feature path.

#436 was closed with "e4b + a 3.6 s clip resampled to 16 kHz + audio token in the user turn: a full coherent transcription is produced". On 0.4.0 I cannot reproduce coherent behavior on real speech (Korean, 12.5 s, native 16 kHz), so this looks like either a regression after #436 or a case its validation clip did not cover.

Environment

  • mlxcel 0.4.0 (Homebrew, lablup/tap/mlxcel, macOS aarch64 release artifact)
  • macOS (Darwin 25.5.0), Apple Silicon M5 Pro, 64 GB
  • Checkpoints: mlx-community/gemma-4-e4b-it-4bit, mlx-community/gemma-4-e2b-it-4bit, mlx-community/gemma-4-12B-it-4bit (resolved from the HF hub cache)

Reproduction

Self-contained script. It fetches one public Korean speech sample (FLEURS ko_kr, test split, row 0) from the HuggingFace datasets-server API at runtime, no auth or datasets library needed. Requires curl, python3, ffmpeg.

#!/usr/bin/env bash
set -euo pipefail

WORK=$(mktemp -d)
API="https://datasets-server.huggingface.co/rows?dataset=google/fleurs&config=ko_kr&split=test&offset=0&length=1"

echo "== Fetching public Korean speech sample (FLEURS ko_kr test[0]) =="
for attempt in 1 2 3; do
  curl -s "$API" -o "$WORK/row.json"
  if python3 -c "import json,sys; json.load(open(sys.argv[1]))['rows']" "$WORK/row.json" 2>/dev/null; then
    break
  fi
  echo "datasets-server returned no rows (attempt $attempt), retrying..."
  [ "$attempt" = 3 ] && { echo "API response:"; cat "$WORK/row.json"; exit 1; }
  sleep 5
done
python3 - "$WORK/row.json" > "$WORK/info.txt" <<'EOF'
import json, sys
row = json.load(open(sys.argv[1]))["rows"][0]["row"]
print(row["audio"][0]["src"])
print(row["transcription"])
EOF
URL=$(head -1 "$WORK/info.txt")
REF=$(sed -n 2p "$WORK/info.txt")
curl -s "$URL" -o "$WORK/clip_float.wav"

# datasets-server serves IEEE Float WAV, which mlxcel's WAV reader rejects
# ("WAV scan error: failed to fill whole buffer"), so convert to 16 kHz PCM16.
ffmpeg -y -loglevel error -i "$WORK/clip_float.wav" -ar 16000 -ac 1 -c:a pcm_s16le "$WORK/clip.wav"

E4B="${E4B:-mlx-community/gemma-4-e4b-it-4bit}"
B12="${B12:-mlx-community/gemma-4-12B-it-4bit}"

echo
echo "== Ground truth =="
echo "$REF"
echo
echo "== gemma-4-e4b-it-4bit (Conformer audio tower) -> garbled =="
mlxcel generate -m "$E4B" --audio "$WORK/clip.wav" -p "Transcribe this audio." -n 150 -t 0
echo
echo "== gemma-4-12B-it-4bit (Unified, encoder-free) -> correct =="
mlxcel generate -m "$B12" --audio "$WORK/clip.wav" -p "Transcribe this audio." -n 150 -t 0

Observed output (verbatim, -t 0)

Ground truth (FLEURS transcription):

다리 밑 수직 간격은 15미터이며 공사는 2011년 8월에 마무리되었으며 해당 다리의 통행금지는 2017년 3월까지이다

gemma-4-e4b-it-4bit:

Loaded Gemma4 audio encoder (12 Conformer layers)
Model loaded in 1.026s (resident: 4.83 GB, peak: 4.86 GB).
Loaded audio: 199680 samples at 16000 Hz (12.5s)
Gemma4: expanded audio into 312 soft tokens (335 total tokens)
Generating...
Transcribe this audio.<|channel>thought
Here's a thinking process that leads to the suggested transcription:

1.  **Analyze the Request:** The user has provided an audio snippet (or rather, a text representation of an audio snippet, which is highly garbled/unintelligible in the provided text) and asked for a transcription.

2.  **Analyze the Input Text:** The input text is:
    " tadi misukangke gibu mitanya okangani ichan ya pada rubiyea eden tadi tukengke gibu ichan samakaji da"

    *Self-Correction/Initial Assessment:* The text is extremely garbled. It appears to be a phonetic attempt to capture speech, but it is highly distorted,

[Generated 150 tokens in 2.55s = 58.76 tok/s]

gemma-4-12B-it-4bit (same clip, same command):

Loaded Gemma4 Unified audio embedder (encoder-free waveform path)
Model loaded in 2.169s (resident: 10.24 GB, peak: 10.24 GB).
Loaded audio: 199680 samples at 16000 Hz (12.5s)
Gemma4: expanded audio into 312 soft tokens (332 total tokens)
Generating...
Transcribe this audio.달래미의 초기 가격은 15m이며, 공사는 2011년 8월에 마무리되었으며, 해당 다리의 통행 금지는 2017년 3월까지입니다.

[Generated 48 tokens in 3.65s = 13.16 tok/s]

The 12B output is a near-correct transcription of the ground truth. The E4B "perception" quoted inside its (leaked) thinking is a heavily time/spectrum-distorted rendition of the same Korean utterance. E2B behaves like E4B. With other prompts and samplings E4B sometimes instead concludes "There is no audio provided".

Expected

E4B should produce a roughly correct Korean transcription. The same mlx-community E-series checkpoints transcribe FLEURS Korean at roughly 5.5% CER through other runtimes (measured via mlx-vlm in June), so the checkpoints and the model family are capable; the garble appears specific to mlxcel's E-series audio feature path.

Analysis notes

  • The encoder loads ("Loaded Gemma4 audio encoder (12 Conformer layers)") and the placeholder count is correct (312 soft tokens for 12.5 s = ceil(duration_ms / 40)), so placement and count look right. What reaches the model appears to be garbled features.
  • The input is already 16 kHz mono PCM16, so root cause B of fix: Gemma 4 audio understanding (CLI --audio) produces no output (missing 16kHz resample + audio token placed outside the user turn) #436 (missing resample from a non-16k source) should not apply, unless the resampler now runs on already-16k input or the mel/window config diverges for E-series. Candidate areas: mel extraction config for the Conformer path, Conformer weight mapping, or masked_scatter alignment between encoder frames and placeholders.

Secondary observations (can file separately if preferred)

Happy to run instrumented builds or additional clips if useful.

Activity

  1. changed the title [-]bug(gemma4): E2B/E4B --audio perception is garbled on 16 kHz PCM16 input (0.4.0), while 12B Unified transcribes the same clip correctly (regression or incomplete fix of #436)[/-] [+]Gemma4 E2B/E4B audio transcription is garbled on 16 kHz PCM16 input while the 12B Unified path transcribes the same clip correctly[/+] on Jul 13, 2026
  2. added
    status:ready
    type:bug
    priority:high
    status:in-progress
    status:review
    status:done
    and removed
    status:ready
    status:in-progress
    status:review
    on Jul 13, 2026
  3. added a commit that references this issue on Jul 30, 2026
    14b26fe
  4. added a commit that references this issue on Oct 27, 2026
    85d0a14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority:highstatus:donetype:bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions