Skip to content

fix: Gemma 4 CLI audio resample to 16kHz and place <|audio|> in user turn - #438

Merged
inureyes merged 4 commits into
mainfrom
fix/issue-436-gemma4-audio-resample-placement
Jun 25, 2026
Merged

inureyes merged 4 commits into
mainfrom
fix/issue-436-gemma4-audio-resample-placement

Conversation

@inureyes

Copy link
Copy Markdown
Member

Summary

Gemma 4 audio understanding from the CLI (mlxcel generate --audio) ran the Conformer encoder but generated 0 tokens (immediate EOS) because of two independent pre-existing defects. Fixing both makes the model produce a coherent transcription. Root-caused and reproduced in #436 (this PR is unrelated to #434; the 0-token behavior is byte-identical before and after #434).

What changed

  • Fix B (resampling): the Gemma 4 Conformer audio paths now resample the waveform to 16 kHz via whisper_mel::resample_to_16k before mel extraction, because AudioFeatureExtractor::extract assumes 16 kHz (160-sample hop = 10 ms) while load_wav_file / load_wav_from_bytes return native-rate samples (the reference clips are 24 kHz). Without it the encoder emitted ~1.5x too many frames (64 vs 43 for a 1.7 s clip) and desynced from the duration-based placeholder count, garbling the embeddings. Fixed in CLI compute_gemma4_audio_embeddings and compute_gemma4_multimodal_embeddings (src/commands/generate_vlm.rs) and server prepare_gemma4_audio_embeddings (src/server/model_worker.rs). Duration (and thus num_audio_tokens) is rate-invariant, so the placeholder count stays correct and now matches the encoder output length.
  • Fix A (placement): a num_audios count is threaded through load_cli_prompt -> resolve_cli_prompt -> apply_vlm_chat_template (src/commands/generate.rs), which now emits {"type":"audio"} content parts into the user turn, gated on a new ChatTemplateProcessor::supports_audio_content() (src/server/chat_template.rs). The gemma-4 template renders these as <|audio|> in the user turn so expand_gemma4_audio_tokens finds and expands the placeholder in place, instead of the old "insert before the last token" fallback that landed the audio block inside the model turn and forced an immediate EOS. Routing only switches to the VLM template when the template actually handles audio content, so non-audio models keep the byte-identical text-only path (no regression).
  • Server placement deferred: the server renders chat messages text-only (build_chat_messages_with_thinking flattens to content.text()), so input_audio never becomes a user-turn <|audio|>. Fixing that requires reworking the prefix-cache-sensitive rendering path, so it is tracked as a focused follow-up in fix: Gemma 4 server audio (input_audio) places <|audio|> outside the user turn (0-token output) #437 with the evidence from fix: Gemma 4 audio understanding (CLI --audio) produces no output (missing 16kHz resample + audio token placed outside the user turn) #436. The server resampling half is fixed in this PR.
  • Tests: expand_gemma4_audio_tokens in-place and fallback expansion; apply_vlm_chat_template / resolve_cli_prompt audio rendering and routing (and the no-regression text path for non-audio templates); supports_audio_content detection; a 24 kHz -> 16 kHz resample length check.

Test plan

  • cargo check --bin mlxcel --features metal,accelerate (compiles)
  • cargo fmt --check and cargo clippy --bin mlxcel --features metal,accelerate (clean)
  • cargo test --bin mlxcel -- gemma4_audio vlm_chat_template resolve_cli_prompt (10 passed)
  • cargo test --lib -- resample_scales_length_from_24k supports_audio_content (passed)
  • Full cargo build --release --features metal,accelerate (run by the orchestrator)
  • Real-model E2E (orchestrator): mlxcel generate -m models/gemma-4-e2b-it-4bit --audio references/mlx-vlm/computer_use/audio/ask.wav -p "Transcribe this audio." -n 120 -t 0 produces a coherent transcription with no manual <|audio|> and no external resampling (the 24 kHz clip is resampled internally), and the encoder frame count equals the placeholder count; gemma-4-e2b text and image inputs remain coherent (no regression).

Closes #436

…turn

Gemma 4 audio understanding from the CLI (`mlxcel generate --audio`) ran the Conformer encoder but generated 0 tokens (immediate EOS) due to two independent pre-existing defects. Fixing both makes the model produce a coherent transcription.

Fix B (resampling): `audio::load_wav_file` returns samples at the file's native rate (the reference clips are 24 kHz), but `AudioFeatureExtractor::extract` assumes a 16 kHz waveform (160-sample hop = 10 ms). Passing native-rate samples inflated the encoder frame count (64 instead of 43 for a 1.7 s clip) and desynced it from the duration-based audio-token placeholder count, garbling the embeddings. The Gemma 4 Conformer paths now resample to 16 kHz via `whisper_mel::resample_to_16k` before mel extraction: CLI `compute_gemma4_audio_embeddings` and `compute_gemma4_multimodal_embeddings`, plus the server `prepare_gemma4_audio_embeddings`. Duration (and thus the placeholder count) is rate-invariant, so the count stays correct and now matches the encoder output length.

Fix A (placement): the CLI chat-template path only emitted image/video content parts and only took the VLM template path when num_images>0 || num_videos>0, so an audio-only request got a plain text user turn with no `<|audio|>` marker. `expand_gemma4_audio_tokens` then fell back to inserting the audio block before the last token, which lands inside the model turn and forces an immediate EOS. A `num_audios` count is now threaded through `load_cli_prompt` -> `resolve_cli_prompt` -> `apply_vlm_chat_template`, which emits `{"type":"audio"}` content parts gated on a new `ChatTemplateProcessor::supports_audio_content()`. The gemma-4 template renders these as `<|audio|>` in the user turn, so the expansion finds and expands the placeholder in place. Routing only switches to the VLM template when the template actually handles audio content, so every non-audio model keeps the byte-identical text-only path.

The server resampling defect is fixed here; the server placement defect (the prompt is rendered text-only, so `input_audio` never becomes a user-turn `<|audio|>`) requires reworking the prefix-cache-sensitive rendering path and is tracked as a focused follow-up.

Tests: in-place and fallback expansion for `expand_gemma4_audio_tokens`, `apply_vlm_chat_template` / `resolve_cli_prompt` audio rendering and routing, `supports_audio_content` detection, and a 24 kHz -> 16 kHz resample length check.

Closes #436
@inureyes inureyes added type:bug Bug fixes, error corrections, or issue resolutions priority:high High priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:cli Command-line interface / CLI flags status:review Under review labels Jun 25, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Make Gemma 4 CLI audio understanding (mlxcel generate --audio) produce output instead of 0 tokens, by resampling the waveform to 16 kHz before mel extraction (Fix B) and rendering <|audio|> into the user turn (Fix A); server resampling fixed, server placement deferred to #437.

Findings Addressed

None requiring a fix. The implementation is correct, complete, and integrated.

Verification

  • All stated requirements implemented (Fix A placement + Fix B resampling, CLI; server resampling)
  • No placeholder/mock code remaining
  • Integrated into project code flow (load_cli_prompt call site threads num_audios; E2E confirmed by orchestrator)
  • Project conventions followed (no references/ paths, GitHub URL used; no // Used by: needed for CLI-local helpers; no em dashes; no AI attribution; Closes #436)
  • Existing modules reused (whisper_mel::resample_to_16k, compute_audio_num_tokens, supports_*_content heuristic family)
  • No unintended structural changes
  • Tests pass (orchestrator-run: 10 + 2; logic hand-verified)

Detailed checks

  • Resampling: resample_to_16k is applied BEFORE AudioFeatureExtractor::extract in all three Conformer paths (compute_gemma4_audio_embeddings, compute_gemma4_multimodal_embeddings, server prepare_gemma4_audio_embeddings). The placeholder count (compute_audio_num_tokens) is computed from the native sample_rate before resample and is duration-based (rate-invariant), so it still equals the post-resample encoder frame count. A true 16 kHz input is a no-op via the if sample_rate != 16_000 guard. No Gemma 4 Conformer path was missed: the three are the only request-path AudioFeatureExtractor users. The Nemotron H Nano Omni path is a separate extractor that hard-errors on a rate mismatch (out of scope), and the gemma4_unified encoder-free path derives its placeholder count from the same process_audio chunking it feeds, so it is correctly left untouched.
  • Placement: num_audios threads load_cli_prompt -> resolve_cli_prompt -> apply_vlm_chat_template. The {"type":"audio"} part is emitted only when num_audios > 0 && supports_audio_content(), and routing only switches to the VLM template under the same gate, so non-audio and non-gemma models keep a byte-identical text-only (and image/video) prompt. Tests cover routing, rendering, omission-when-unsupported, and the no-regression text path. supports_audio_content() matches the template's type == 'audio' branch and mirrors supports_image_content / supports_video_content. expand_gemma4_audio_tokens expands the first <|audio|> marker in place and keeps the model-turn fallback only as a last resort; both new tests match the implementation.
  • Server deferral: fix: Gemma 4 server audio (input_audio) places <|audio|> outside the user turn (0-token output) #437 exists (OPEN) and tracks the server placement (Fix A) half; the server resampling (Fix B) half is fixed in this PR.

Remaining Items

  • None blocking. One non-blocking observation (LOW, informational, no change requested): the audio-routing in resolve_cli_prompt reaches apply_vlm_chat_template, which early-returns text-only if the template lacks image support. A hypothetical template that handles type == 'audio' but not type == 'image' would drop the audio marker. This does not affect Gemma 4 (its template handles image content, and image input is unregressed), so it is theoretical only.

Document that Gemma 4 Unified audio understanding is available from the CLI via --audio, with automatic resampling to 16 kHz, in docs/supported-models.md. Apply rustfmt brace-placement fix in generate_tests.rs (the assert! over the pipeline-stage iterator).
@inureyes

Copy link
Copy Markdown
Member Author

PR Finalization Complete

Summary

Tests: 8 tests added by the developer; all pass. No additional test was added (the server-path resample and compute_audio_num_tokens rate-invariance cases would test the same resample_to_16k function already covered, so they would add no coverage value). Verification:

  • cargo test --bin mlxcel -- vlm_chat_template_renders_audio_content_part_in_user_turn vlm_chat_template_omits_audio_when_template_lacks_audio_support resolve_cli_prompt_routes_audio_through_vlm_template resolve_cli_prompt_keeps_text_path_for_audio_on_plain_template passed (4/4)
  • cargo test --bin mlxcel -- gemma4_audio_expands_placeholder_in_place gemma4_audio_fallback_inserts_before_last_token passed (2/2)
  • cargo test --lib -- supports_audio_content_detects_audio_branch resample_scales_length_from_24k passed (2/2)

Documentation: Updated docs/supported-models.md Gemma 4 Unified entry to state that audio understanding is available from the CLI (--audio <path>) and that input audio is resampled to 16 kHz automatically. docs/audio-api.md was not touched (it covers the Whisper/Kokoro server endpoints, a separate feature).

Lint/Format: cargo clippy --bin mlxcel --features metal,accelerate -- -D warnings produced zero warnings. Applied rustfmt brace-placement fix in generate_tests.rs (the assert! over the pipeline-stage iterator; the three files with let chains could not be formatted by the installed rustfmt 1.8.0, which is a pre-existing limitation unrelated to this PR).

Commit: eaf156748

… path

The earlier note placed the audio-understanding sentence on the encoder-free Gemma 4 Unified bullet and credited a "Conformer encoder" that path does not use, and claimed server input_audio support that is not yet wired (tracked separately). Move the note to its own Gemma 4 VL bullet: the Conformer-tower checkpoints take CLI --audio and resample to 16 kHz before the encoder, and state that the server path is not yet wired through the chat prompt.
@inureyes inureyes added status:done Completed and removed status:review Under review labels Jun 25, 2026
The prior commit formatted generate_tests.rs with standalone rustfmt, which defaults to an older edition and lays out the multi-line assert! differently than `cargo fmt --all` under the project's edition 2024. CI runs `cargo fmt --all -- --check`, so reformat with cargo fmt to match.
@inureyes
inureyes merged commit d5cff84 into main Jun 25, 2026
4 checks passed
@inureyes
inureyes deleted the fix/issue-436-gemma4-audio-resample-placement branch June 25, 2026 13:59
inureyes added a commit that referenced this pull request Jun 25, 2026
The initial v0.3.3 cut (4d5f4fb) was never tagged, and 16 more commits
landed on main afterward. Fold those fixes into the v0.3.3 CHANGELOG and
debian/changelog entries and set the release date to 2026-06-25:

- N-gram loop detection (#433) and Nemotron-H Nano Omni audio input (#443)
- Prefill masks sized from the live window under --max-kv-size trim
  (#418, #420, #422, #431)
- Double-transpose crash on mlx-community conv checkpoints (#429)
- conv1d/conv2d and nemotron audio-encoder convs fallible at the FFI
  boundary (#434, #439)
- Gemma 4 audio placed in the user turn (#438, #440)
- mistral4 MLA backbone routing and 2D MoE token flattening (#423, #425)
- Bump actions/checkout from 6 to 7 (#395)
@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
…turn (lablup#438)

* fix: Gemma 4 CLI audio resample to 16kHz and place <|audio|> in user turn

Gemma 4 audio understanding from the CLI (`mlxcel generate --audio`) ran the Conformer encoder but generated 0 tokens (immediate EOS) due to two independent pre-existing defects. Fixing both makes the model produce a coherent transcription.

Fix B (resampling): `audio::load_wav_file` returns samples at the file's native rate (the reference clips are 24 kHz), but `AudioFeatureExtractor::extract` assumes a 16 kHz waveform (160-sample hop = 10 ms). Passing native-rate samples inflated the encoder frame count (64 instead of 43 for a 1.7 s clip) and desynced it from the duration-based audio-token placeholder count, garbling the embeddings. The Gemma 4 Conformer paths now resample to 16 kHz via `whisper_mel::resample_to_16k` before mel extraction: CLI `compute_gemma4_audio_embeddings` and `compute_gemma4_multimodal_embeddings`, plus the server `prepare_gemma4_audio_embeddings`. Duration (and thus the placeholder count) is rate-invariant, so the count stays correct and now matches the encoder output length.

Fix A (placement): the CLI chat-template path only emitted image/video content parts and only took the VLM template path when num_images>0 || num_videos>0, so an audio-only request got a plain text user turn with no `<|audio|>` marker. `expand_gemma4_audio_tokens` then fell back to inserting the audio block before the last token, which lands inside the model turn and forces an immediate EOS. A `num_audios` count is now threaded through `load_cli_prompt` -> `resolve_cli_prompt` -> `apply_vlm_chat_template`, which emits `{"type":"audio"}` content parts gated on a new `ChatTemplateProcessor::supports_audio_content()`. The gemma-4 template renders these as `<|audio|>` in the user turn, so the expansion finds and expands the placeholder in place. Routing only switches to the VLM template when the template actually handles audio content, so every non-audio model keeps the byte-identical text-only path.

The server resampling defect is fixed here; the server placement defect (the prompt is rendered text-only, so `input_audio` never becomes a user-turn `<|audio|>`) requires reworking the prefix-cache-sensitive rendering path and is tracked as a focused follow-up.

Tests: in-place and fallback expansion for `expand_gemma4_audio_tokens`, `apply_vlm_chat_template` / `resolve_cli_prompt` audio rendering and routing, `supports_audio_content` detection, and a 24 kHz -> 16 kHz resample length check.

Closes lablup#436

* chore: note Gemma 4 audio CLI support in docs and apply rustfmt

Document that Gemma 4 Unified audio understanding is available from the CLI via --audio, with automatic resampling to 16 kHz, in docs/supported-models.md. Apply rustfmt brace-placement fix in generate_tests.rs (the assert! over the pipeline-stage iterator).

* docs: attribute Gemma 4 audio CLI support to the Gemma 4 VL Conformer path

The earlier note placed the audio-understanding sentence on the encoder-free Gemma 4 Unified bullet and credited a "Conformer encoder" that path does not use, and claimed server input_audio support that is not yet wired (tracked separately). Move the note to its own Gemma 4 VL bullet: the Conformer-tower checkpoints take CLI --audio and resample to 16 kHz before the encoder, and state that the server path is not yet wired through the chat prompt.

* style: format assert with cargo fmt (edition 2024) to satisfy CI

The prior commit formatted generate_tests.rs with standalone rustfmt, which defaults to an older edition and lays out the multi-line assert! differently than `cargo fmt --all` under the project's edition 2024. CI runs `cargo fmt --all -- --check`, so reformat with cargo fmt to match.
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
The initial v0.3.3 cut (4d5f4fb) was never tagged, and 16 more commits
landed on main afterward. Fold those fixes into the v0.3.3 CHANGELOG and
debian/changelog entries and set the release date to 2026-06-25:

- N-gram loop detection (lablup#433) and Nemotron-H Nano Omni audio input (lablup#443)
- Prefill masks sized from the live window under --max-kv-size trim
  (lablup#418, lablup#420, lablup#422, lablup#431)
- Double-transpose crash on mlx-community conv checkpoints (lablup#429)
- conv1d/conv2d and nemotron audio-encoder convs fallible at the FFI
  boundary (lablup#434, lablup#439)
- Gemma 4 audio placed in the user turn (lablup#438, lablup#440)
- mistral4 MLA backbone routing and 2D MoE token flattening (lablup#423, lablup#425)
- Bump actions/checkout from 6 to 7 (lablup#395)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:cli Command-line interface / CLI flags area:core mlxcel-core: MLX FFI, primitives, KV cache, layers 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.

fix: Gemma 4 audio understanding (CLI --audio) produces no output (missing 16kHz resample + audio token placed outside the user turn)

1 participant