Repository navigation
Gemma 4: native audio input (port the gemma4_audio USM-Conformer encoder) - #392
fdagostino wants to merge 3 commits into
Conversation
42f8ff7 to
b055afc
Compare
|
Rebase with main for swift-format |
b055afc to
8c14b17
Compare
|
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. |
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>
8c14b17 to
6abe089
Compare
|
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. |
…coder-codes Decode corrupt H.264 and HEVC clips and check that none gives a transient code
…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>
Gemma 4: native audio (+ video) input for the
Gemma4VLMDraft — builds on #390 (
fix/gemma4-vlm-kv-shared-construct), which the E4B checkpoint needs to load.Wires native audio (and video) into the
Gemma4VLM class (model_type: "gemma4",e.g.
mlx-community/gemma-4-e4b-it-4bit), previously text + vision only. The audioencoder (
audio_tower, a USM-Conformer) is ported fromBlaizzy/mlx-vlmmodels/gemma4/audio.pyand cross-checked against three independent implementationsthat all agree: mlx-vlm (Python),
VincentGourbin/gemma-4-swift-mlx(Swift), and themerged llama.cpp PR #21421 (
tools/mtmd/models/gemma4a.cpp, C++).Changes
Libraries/MLXVLM/Models/Gemma4Audio.swift(new) — theaudio_tower:SSCP subsample projection (2×
Conv2d3×3 stride-2 → flatten(F·C) →Linear), macaronConformerFeedForward(0.5 residual), chunked-localAudioAttention(Transformer-XLrelative shift, base-2
qScale/kScale,per_dim_scalesoftplus, tanh softcap 50,float32 math), depthwise-causal
LightConv1d, ×12ConformerBlock,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.rfftis re-exported byMLX(no new package dependency).
Libraries/MLXVLM/Models/Gemma4.swift:Gemma4Configurationdecodesaudio_config,video_token_id,boa/eoa,audio_soft_tokens_per_image,audio_ms_per_token.Gemma4buildsaudio_tower/embed_audiowhenaudio_configis present; runs thetower in
getAudioFeatures(mask polarity:ProcessedAudio.maskistrue==valid,inverted to the tower's
true==padding); scatters audio soft-tokens ataudio_token_id;scatters video frames through the same vision tower at
video_token_id; handlesinput.audio/input.videoinprepare;sanitizekeeps audio weights + normalisesconv layout (shape-guarded, no-ops on pre-converted mlx-community weights).
Gemma4Processorextracts mel frominput.audios, expands each audio placeholder toboa + 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; themessage generator emits
{type: audio}.Gemma4ClippableLinearrelaxedprivate→ internal for reuse.Tests (
Tests/MLXLMTests/Gemma4AudioTests.swift): config decode; exact checkpointweight-key parity; strict-loader round-trip; forward-pass subsampling/shape/finiteness/
padding-zeroing; mel filterbank validity; extractor shape/frame-count/determinism;
audioTokenCountformula; and an end-to-end consistency test proving the processor'sper-clip token count equals the tower's valid subsampled-frame count.
Data flow
waveform→Gemma4AudioFeatureExtractor→ mel[1,T,128]→ SSCP →[1,T/4,1024]→ 12Conformer blocks →
output_proj[1,T/4,1536]→embed_audio(RMSNorm-noscale →Linear1536→2560) → masked-scatter at
audio_token_id 258881.Verification
swift buildclean. All tests pass under Xcode (swift testCLI can't load MLX'sdefault.metallib):Verification of the two open questions
chat_template.jinjarenders{type: audio}content as<|audio|>(=audio_token_id 258881), andtokenizer_config.jsondefinesaudio/boa/eoatokens. So the message generator's{type: audio}→<|audio|>→ processor expansion chain is correct against the realcheckpoint files. (
processor_config.jsonalso confirms the extractor params:16 kHz / 128 mel / fft 512 / hop 160.)
audio.py(small config, seeded weights, deterministicinput), exported weights+I/O, loaded them into the Swift
Gemma4AudioModel, and theoutput matches to < 1e-3 (MLX-vs-MLX). Gold-standard validation of the attention
transposes, relative-shift, einsum→matmul rewrite, and convs.
audio_feature_extractor.py(numpy) on a deterministicwaveform; the Swift extractor matches to ~1e-2 in log-mel — the residual is
float32 Metal FFT vs numpy's float64 CPU FFT (amplified by
logat near-silentbins), not an algorithm difference. Asserted in a committed self-contained test.
Follow-ups
processor_config.jsonhaschunk_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.