Skip to content

Gemma 4: native audio input (port the gemma4_audio USM-Conformer encoder) - #392

Open
fdagostino wants to merge 3 commits into
ml-explore:mainfrom
fdagostino:feat/gemma4-audio-encoder
Open

fdagostino wants to merge 3 commits into
ml-explore:mainfrom
fdagostino:feat/gemma4-audio-encoder

Conversation

@fdagostino

Copy link
Copy Markdown
Contributor

Gemma 4: native audio (+ video) input for the Gemma4 VLM

Draft — builds on #390 (fix/gemma4-vlm-kv-shared-construct), which the E4B checkpoint needs to load.

Wires native audio (and video) into the Gemma4 VLM class (model_type: "gemma4",
e.g. mlx-community/gemma-4-e4b-it-4bit), previously text + vision only. The audio
encoder (audio_tower, a USM-Conformer) is ported from Blaizzy/mlx-vlm
models/gemma4/audio.py and cross-checked against three independent implementations
that all agree: mlx-vlm (Python), VincentGourbin/gemma-4-swift-mlx (Swift), and the
merged llama.cpp PR #21421 (tools/mtmd/models/gemma4a.cpp, C++).

Changes

Libraries/MLXVLM/Models/Gemma4Audio.swift (new) — the audio_tower:
SSCP subsample projection (2× Conv2d 3×3 stride-2 → flatten(F·C) → Linear), macaron
ConformerFeedForward (0.5 residual), chunked-local AudioAttention (Transformer-XL
relative shift, base-2 qScale/kScale, per_dim_scale softplus, tanh softcap 50,
float32 math), depthwise-causal LightConv1d, ×12 ConformerBlock, output_proj.

Libraries/MLXVLM/Models/Gemma4AudioFeatures.swift (new) — Gemma4AudioFeatureExtractor:
faithful MLX port of HF Gemma4AudioFeatureExtractor (raw 16 kHz waveform → log-mel
[1,T,128] + validity mask). Periodic Hann, HTK mel (128 bins, 0–8 kHz), rfft (n=512),
magnitude spectrum, log(mel + 1e-3), semicausal pad. rfft is re-exported by MLX
(no new package dependency).

Libraries/MLXVLM/Models/Gemma4.swift:

  • Gemma4Configuration decodes audio_config, video_token_id, boa/eoa,
    audio_soft_tokens_per_image, audio_ms_per_token.
  • Gemma4 builds audio_tower/embed_audio when audio_config is present; runs the
    tower in getAudioFeatures (mask polarity: ProcessedAudio.mask is true==valid,
    inverted to the tower's true==padding); scatters audio soft-tokens at audio_token_id;
    scatters video frames through the same vision tower at video_token_id; handles
    input.audio/input.video in prepare; sanitize keeps audio weights + normalises
    conv layout (shape-guarded, no-ops on pre-converted mlx-community weights).
  • Gemma4Processor extracts mel from input.audios, expands each audio placeholder to
    boa + audio_soft_token×N + eoa (N derived from valid mel frames via the SSCP formula,
    so it exactly matches the tower's scatter count), and produces ProcessedAudio; the
    message generator emits {type: audio}.
  • Gemma4ClippableLinear relaxed private → internal for reuse.

Tests (Tests/MLXLMTests/Gemma4AudioTests.swift): config decode; exact checkpoint
weight-key parity; strict-loader round-trip; forward-pass subsampling/shape/finiteness/
padding-zeroing; mel filterbank validity; extractor shape/frame-count/determinism;
audioTokenCount formula; and an end-to-end consistency test proving the processor's
per-clip token count equals the tower's valid subsampled-frame count.

Data flow

waveform → Gemma4AudioFeatureExtractor → mel [1,T,128] → SSCP → [1,T/4,1024] → 12
Conformer blocks → output_proj [1,T/4,1536] → embed_audio (RMSNorm-noscale → Linear
1536→2560) → masked-scatter at audio_token_id 258881.

Verification

swift build clean. All tests pass under Xcode (swift test CLI can't load MLX's
default.metallib):

xcodebuild test -scheme mlx-swift-lm-Package -destination 'platform=macOS,arch=arm64' \
  -only-testing:MLXLMTests/Gemma4AudioTests -skipPackagePluginValidation -skipMacroValidation

Verification of the two open questions

  • Chat template — confirmed. The checkpoint's chat_template.jinja renders
    {type: audio} content as <|audio|> (= audio_token_id 258881), and
    tokenizer_config.json defines audio/boa/eoa tokens. So the message generator's
    {type: audio} → <|audio|> → processor expansion chain is correct against the real
    checkpoint files. (processor_config.json also confirms the extractor params:
    16 kHz / 128 mel / fft 512 / hop 160.)
  • Numerical parity — confirmed both ways.
    • Encoder: ran mlx-vlm's real audio.py (small config, seeded weights, deterministic
      input), exported weights+I/O, loaded them into the Swift Gemma4AudioModel, and the
      output matches to < 1e-3 (MLX-vs-MLX). Gold-standard validation of the attention
      transposes, relative-shift, einsum→matmul rewrite, and convs.
    • Mel: ran the reference audio_feature_extractor.py (numpy) on a deterministic
      waveform; the Swift extractor matches to ~1e-2 in log-mel — the residual is
      float32 Metal FFT vs numpy's float64 CPU FFT (amplified by log at near-silent
      bins), not an algorithm difference. Asserted in a committed self-contained test.

Follow-ups

  • Long-audio chunking: processor_config.json has chunk_duration 8.0 / overlap 1.0;
    this extractor does a single window up to 30 s. Fine for short clips; chunking of longer
    audio into overlapping 8 s segments is not implemented.

@davidkoski

Copy link
Copy Markdown
Member

Rebase with main for swift-format

@fdagostino

Copy link
Copy Markdown
Contributor Author

Rebased on main and ran swift-format. Two notes: (1) the conflict resolution keeps #405's aspect-preserving image path untouched and only adds the audio scatter after it; (2) this branch previously carried a video-wiring commit that overlapped with #391 — dropped it here, so this PR is now audio-only (USM-Conformer encoder port + log-mel extractor + numerical parity test). 268 tests pass locally with the CI invocation.

fdagostino and others added 3 commits September 13, 2026 22:10
The `Gemma4` VLM class (`model_type: "gemma4"`, e.g. gemma-4-e4b-it) was
text + vision only: `Gemma4Configuration` ignored `audio_config`, no audio
encoder existed anywhere in the repo, `sanitize` dropped every `audio_tower.*`
/ `embed_audio.*` weight, and `prepare` never consumed `input.audio`. This
adds native audio input.

New `Gemma4Audio.swift` ports the `audio_tower` (USM-Conformer) from the
Python reference (Blaizzy/mlx-vlm `models/gemma4/audio.py`), cross-checked
against VincentGourbin/gemma-4-swift-mlx:

- `Gemma4AudioConfiguration` (decodes `audio_config`).
- SSCP subsample projection: 2× `Conv2d` 3x3 stride-2 (symmetric pad) ->
  flatten(freq*channels) -> `Linear` to hidden. 4x time subsampling.
- Macaron `ConformerFeedForward` (0.5 residual); chunked-local `AudioAttention`
  (Transformer-XL relative-position shift, base-2 q/k scales, `per_dim_scale`
  softplus, tanh logit softcap, float32 math); depthwise-causal `LightConv1d`
  (GLU + `Conv1d(groups=hidden)`); `ConformerBlock` x12; `output_proj` head.

`Gemma4.swift`:
- `Gemma4Configuration` decodes `audio_config`, `video_token_id`,
  `boa`/`eoa_token_id`, `audio_soft_tokens_per_image`, `audio_ms_per_token`.
- `Gemma4` builds `audio_tower`/`embed_audio` when `audio_config` is present,
  runs the tower in `getAudioFeatures`, scatters audio soft-token embeddings at
  `audio_token_id` in `getInputEmbeddings`, handles `input.audio` in `prepare`,
  and `sanitize` now keeps audio weights (when an audio tower was built) and
  normalises conv weight layout (Conv2d 0,2,3,1; depthwise Conv1d swapaxes),
  both shape-guarded so pre-converted mlx-community weights no-op.
- `Gemma4ClippableLinear` relaxed private -> internal for reuse by the tower.

Tests (`Gemma4AudioTests.swift`): config decode, exact checkpoint weight-key
parity (incl. ClippableLinear `.linear.` nesting, `relative_k_proj`,
`per_dim_scale`, depthwise `[C,K,1]`), strict-loader round-trip, and forward
shape / 4x subsampling / finiteness / padding-zeroing. All 7 pass under
`xcodebuild test` (swift test CLI can't load MLX's default.metallib).

The raw-waveform -> mel feature extraction and boa+audio*N+eoa token
expansion in `Gemma4Processor`, plus video wiring and numerical parity vs
exported Python activations, are follow-ups; the tower already accepts
pre-extracted mel via `LMInput.ProcessedAudio`.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Completes the raw-waveform -> model path for audio. Previously the audio tower
accepted only pre-extracted mel; this adds the extraction and the processor
glue so `input.audios` works end to end (given a chat template that emits an
audio placeholder).

New `Gemma4AudioFeatures.swift` - `Gemma4AudioFeatureExtractor`: a faithful MLX
port of HuggingFace `Gemma4AudioFeatureExtractor` (raw 16 kHz mono -> log-mel
`[1, T, 128]` + validity mask). Periodic Hann window, HTK mel filterbank (128
bins, 0-8 kHz), `rfft(n=512)`, magnitude (not power) spectrum, `log(mel + 1e-3)`,
semicausal left-pad. `rfft` is re-exported by `MLX`, so no new package
dependency. Cross-checked against llama.cpp PR #21421 `mtmd-audio.cpp` (same
window / mel scale / 31.25 Hz bin spacing).

`Gemma4.swift`:
- `Gemma4Processor` extracts mel per clip, expands each audio placeholder into
  `boa + audio_soft_token*N + eoa`, and produces `ProcessedAudio`. N is derived
  from the clip's valid mel-frame count via the SSCP subsample formula
  `ceil(ceil(V/2)/2)`, so the prompt's audio-token count exactly equals the
  encoder frames the tower scatters (asserted end-to-end in tests).
- `Gemma4MessageGenerator` emits `{type: audio}`; `Gemma4ProcessorConfiguration`
  decodes audio/boa/eoa ids, `audio_seq_length`, `audio_sampling_rate`.
- `getAudioFeatures` inverts mask polarity (`ProcessedAudio.mask` is
  `true == valid`; the tower expects `true == padding`).

Tests: mel filterbank validity, extractor shape/frame-count/determinism,
`audioTokenCount` formula, and an end-to-end check that the extractor's token
count matches the tower's valid subsampled frames. All 12 audio tests pass under
`xcodebuild test`.

Note: automatic audio-token insertion depends on the E4B chat template emitting
an audio placeholder, which is unverified without the real tokenizer.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Adds a self-contained test that runs the mel extractor on a deterministic
waveform and checks it against values produced by the Python reference
(mlx-vlm `audio_feature_extractor.py`, numpy). Log-mel agrees to ~1e-2 — the
residual is float32 Metal FFT vs numpy's float64 CPU FFT, amplified by log at
near-silent bins, not an algorithm difference; the deterministic empty-filter
cell (log(mel_floor)) is checked exactly.

Verified separately (not committed — needs a Python-exported weight fixture):
the encoder output matches mlx-vlm's real audio.py to < 1e-3 on shared weights
and input (MLX-vs-MLX), validating the attention transposes, Transformer-XL
relative shift, einsum->matmul rewrite, and convs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@aleroot

aleroot commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

Following the merge of #684, much of the encoder work here can now reuse the shared implementation: MLXLMCommon contains Gemma4AudioModel and its configuration, and the EmbeddingGemma 2 path includes log-mel preprocessing.
Native audio input for Gemma4 generation is still missing, so this PR remains useful. @fdagostino could we narrow it to the Gemma4 configuration, processor/template handling, audio projection/scatter, and integration tests, reusing the shared encoder and generalizing the existing preprocessing?
One difference worth preserving is padding-mask support: the shared encoder currently consumes unpadded frames, whereas this implementation handles padded inputs. It would also be useful to load the audio component on demand through #580’s infrastructure.

div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…coder-codes

Decode corrupt H.264 and HEVC clips and check that none gives a transient code
div0-space added a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Dec 2, 2026
…20cb09) into unified LibraxisAI core

- Integrates MLXWhisper Swift 6 library, POST /v1/audio/transcriptions (--whisper-model), ml-explore#854 compiled SwiGLU, ml-explore#436 PromptTrie/LRUPromptCache, ml-explore#643 bounded Prompt-Lookup Decoding, and ml-explore#392/ml-explore#400 Gemma 4 audio/video
- Reconciles Package.swift (both MLXGuidedGeneration and MLXWhisper linked into MLXLMServer), ServerConfiguration (--batch-v2/--max-concurrency/--kv-cache-mb/--served-model-name + --whisper-model), and MLXServerRunner (CBv2 + Whisper + Embeddings in one mlx-server process)

Authored-By: gemini <agents@vetcoders.io>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants