Skip to content

feat(xla): add Gemma3n audio execution - #922

Merged
inureyes merged 1 commit into
mainfrom
feature/issue-878-gemma3n-xla-audio
Oct 17, 2026
Merged

inureyes merged 1 commit into
mainfrom
feature/issue-878-gemma3n-xla-audio

Conversation

@inureyes

@inureyes inureyes commented Jul 24, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Add the split resident IREE Gemma3n audio encoder (sscp, conformer, merge_ple), projection, prepared-prefill, dense_ple, CLI, and continuous-batch server path across CPU, CUDA, and ROCm/HIP targets.
  • Validate the pinned audio weight schema, cache identity, request ownership, cancellation, and slot reuse without a silent MLX fallback.
  • Fix dense_ple_input_head in src/lib/mlxcel-xla/src/emitter/gemma3n_math.rs so audio placeholder tokens (token_id >= vocab_size_per_layer_input, e.g., 262273 >= 262144) map to row 0 of embed_tokens_per_layer via per_layer_embedding_lookup (scaled by embed_tokens_per_layer_scale) instead of zeroing the gathered row after lookup, matching MLX Gemma3nModel::get_per_layer_inputs and Hugging Face Gemma3nTextModel.
  • Implement LanguageModel::prepare_sequence_state on Gemma3nVLModel (src/vision/gemma3n_vl.rs) and preserve pre-rendered chat-template audio/image placeholders in prepare_gemma3n_audio_embeddings (src/server/model_worker.rs) when ORDERED_MEDIA_PREFIX is absent so mlxcel generate --audio works on both Eager MLX and OpenXLA.
  • Match the pinned MLX sequential BF16 affine dequantization contract, explicit BF16 mel boundary before the first SSCP convolution, BF16 SSCP operands with explicit F32 StableHLO convolution results followed by BF16 output rounding, cumulative-normalization association order, and explicit lane/XOR RMS reduction schedule.

Root Cause of Previous dense_ple Divergence

In xla_gemma3n_audio_reference_check, the previous dense_ple discrepancy (max_abs = 5.90625, rms = 0.826056) was caused by dense_ple_input_head in src/lib/mlxcel-xla/src/emitter/gemma3n_math.rs zeroing per_layer_token rows whenever token_id >= vocab_size_per_layer_input (262273 >= 262144). Both Hugging Face Gemma3nTextModel.get_per_layer_inputs and MLX Gemma3nModel::get_per_layer_inputs instead clamp out-of-range token IDs (token_id < 0 || token_id >= vocab_size_per_layer_input) to index 0 and gather row 0 of embed_tokens_per_layer scaled by embed_tokens_per_layer_scale. Removing the redundant post-gather zeroing in dense_ple_input_head drops the dense_ple diff on ROCm (gfx1151) to max_abs = 0.1328125, rms = 8.972e-3 and yields 100% token-exact greedy generation against Eager MLX.

Validation

  • End-to-end greedy token exactness (mlx-community/gemma-3n-E4B-it-4bit + 103-1240-0000.wav, 16 greedy tokens):
    • Eager MLX GPU (ROCm): [24233, 236743, 236770, 236761, 12216, 236761, 35783, 28452, 563, 6486, 143843, 236761, 108, 39828, 236761, 35783] ("Chapter 1. Mrs. Rachel Lind is Surprised.\n\nMrs. Rachel")
    • Eager MLX CPU (MLXCEL_DEVICE=cpu): identical 16 tokens
    • OpenXLA xla_gemma3n_audio_check (hip): identical 16 tokens (OK: Gemma3n XLA audio generated exact expected transcript)
    • OpenXLA CLI (MLXCEL_BACKEND=xla MLXCEL_XLA_DEVICE=hip mlxcel generate): identical 16 tokens
  • cargo test -p mlxcel-xla gemma3n -- --test-threads=1 — 60 passed
  • GEMMA3N_MODEL_DIR=... cargo test -p mlxcel-xla gemma3n -- --ignored --test-threads=1 — passed
  • cargo test --lib --features xla-diagnostics-rocm gemma3n -- --include-ignored --test-threads=1 — 52 passed
  • cargo test --test xla_gemma3n_prefill --features xla-diagnostics-rocm -- --include-ignored --test-threads=1 — passed
  • cargo fmt --all -- --check — passed
  • cargo clippy --workspace --all-targets -- -D warnings — passed
  • cargo clippy --all-targets --features xla-diagnostics-rocm -- -D warnings — passed

Closes #878

Parent epic: #566

@inureyes inureyes added status:blocked Blocked by dependencies or other issues type:enhancement New features, capabilities, or significant additions priority:low Low priority area:models Model architectures, weights, loading, metadata area:inference Generation, sampling, decoding (incl. speculative, DRY) labels Jul 24, 2026
@inureyes
inureyes force-pushed the feature/issue-878-gemma3n-xla-audio branch from 74a7d39 to 876bcc3 Compare July 27, 2026 00:28
@inureyes

Copy link
Copy Markdown
Member Author

Rebased onto main@7fe1412d and force-pushed as 876bcc3c.

Rebase integration:

  • resolved the serde dependency spelling conflict in favor of current main
  • combined feat(xla): version auxiliary dtype contracts #934 numeric-contract test imports with this branch’s typed auxiliary weight storage
  • adapted the newer Qwen2-VL loader to AuxiliaryWeightStorage::Bytes
  • kept both Gemma3n audio artifacts explicitly new_legacy_unqualified

Post-rebase validation:

  • cargo fmt --all -- --check
  • git diff --check
  • cargo test -p mlxcel-xla emitter::gemma3n_audio_emit::tests::: 5 passed, 5 environment-dependent ignored
  • cargo check -p mlxcel-xla --features diagnostics: passed with existing warnings
  • cargo check -p mlxcel-xla --features diagnostics --tests: reaches only the existing mainline gemma3n_qmv test-only Builder cfg/import defect; the branch-specific Qwen auxiliary-storage mismatch was fixed

The unchanged MLX-to-IREE audio threshold blocker remains, and CUDA is unavailable on the current host. No new numeric pass is claimed. This PR remains draft/blocked and #878 remains blocked by #932.

@inureyes
inureyes force-pushed the feature/issue-878-gemma3n-xla-audio branch from 876bcc3 to 2b6d949 Compare July 27, 2026 01:41
@inureyes

inureyes commented Jul 27, 2026 •

Copy link
Copy Markdown
Member Author

Foundation refresh complete at head 2b6d949:

  • rebased the full draft cleanly onto main@15a37117 (feat(xla): add explicit CUDA prefix scan contract #943)
  • replaced the family-local one-block cumulative-scan implementation with the shared mlx_cuda_prefix_sum_2d helper
  • added a production-wrapper structural regression pinning the same 17-add / 3-concatenate CUDA hierarchy
  • focused Gemma3n audio tests pass (6 runnable, 5 environment-dependent ignored), the shared schedule compiles through local-task CPU IREE, and diagnostics test compilation passes

The draft remains fail-closed and status:blocked. This refresh does not change the recorded first unresolved boundary: sscp_conv_1_convolution still requires a representable cuDNN/IREE engine or reduction-plan contract.

@inureyes
inureyes force-pushed the feature/issue-878-gemma3n-xla-audio branch from 2b6d949 to 0a5aa90 Compare July 27, 2026 04:01
@inureyes

Copy link
Copy Markdown
Member Author

Rebased onto current main (ec6fbb6d foundation; new head 0a5aa90d) and revalidated the Gemma3n audio branch.

Validation:

  • cargo check -p mlxcel-xla --features diagnostics --lib — passed
  • cargo test -p mlxcel-xla gemma3n_audio --lib — 17 passed, 6 ignored (environment-gated real IREE/checkpoint probes)
  • cargo fmt --all --check — passed
  • git diff --check — passed

The PR intentionally remains draft/fail-closed. The existing production-oracle blocker is unchanged: the first SSCP convolution still has 6 BF16-ULP mismatches (max_abs = 0.25), so the original #878 intermediate/token/lifecycle gates are not satisfied. No tolerance was relaxed, and this branch is not merge-qualified yet.

Refs #878
Refs #932

@inureyes

Copy link
Copy Markdown
Member Author

Current-head CUDA actual at 0a5aa90d: the first SSCP convolution now passes

Run on the GB10 qualification host (driver 580.159.03, CUDA 13.0, IREE 3.12.0rc20260721,
Rust 1.93.1, MLX pin b7c3dd6d27f4, MLX_CUDA_ARCHITECTURES=121, release profile).
Working tree clean at 0a5aa90d. Tolerances unchanged, no override.

Fast pre-gate

cargo test --locked -p mlxcel-xla gemma3n_audio --lib: 17 passed, 6 ignored.

Small SSCP convolution characterization probe

./target/release/examples/xla_gemma3n_sscp_conv_oracle exits 0 and reports PASS:

channel=0 mlx=0.000000000e0 iree=0.000000000e0 bf16_ulp=0     schedule_outcomes=[0.0, 1.0]
channel=1 mlx=1.000000000e0 iree=1.000000000e0 bf16_ulp=0     schedule_outcomes=[0.0, 1.0]
channel=2 mlx=0.000000000e0 iree=0.000000000e0 bf16_ulp=0     schedule_outcomes=[0.0, 1.0]
channel=3 mlx=1.000000000e0 iree=0.000000000e0 bf16_ulp=16256 schedule_outcomes=[0.0, 1.0]
PASS (backend reduction schedules differ within the enumerated F32 accumulation envelope)

Channel 3 is worth recording explicitly: the probe enumerates the achievable F32 accumulation
orders and finds that both 0.0 and 1.0 are legitimate outcomes for the same sum. MLX
lands on one and IREE on the other. That is an exact-tie cancellation whose result is decided
by the reduction tree, so no precision policy can reconcile it, which supports the existing
characterization of this as a backend reduction/engine-identity difference rather than a
correctable semantic mismatch.

Full audio intermediate actual, MLXCEL_XLA_DEVICE=cuda

The recorded blocker for this PR was 6 BF16 ULP outliers with max_abs=0.25 on the first
SSCP convolution. At this head the first convolution no longer produces any BF16 ULP outlier,
and the first divergence has moved downstream:

first divergent stage=sscp_conv_0_norm_cumulative_sum
max_abs=1.562500000e-2  rms=2.432233746e-3  max_index=373
max_bf16_ulp=0  non_bf16_values=1024  over_one_bf16_ulp=0  captured_bf16_outliers=0

max_abs is about 16x smaller than the recorded blocker, and max_bf16_ulp,
over_one_bf16_ulp and captured_bf16_outliers are all zero at the failing stage. Mel
features, valid mask, frame lengths and bucket all pass ahead of it.

The gate still fails, now at the cumulative-sum normalization rather than the convolution, so
the PR stays draft and the capability stays fail-closed.

The reference policy was checked and is not responsible

I filed on #932 that MLX defaults MLX_ENABLE_TF32=1 and that
src/lib/mlxcel-xla/README.md declares that mode is not valid F32 reference evidence. It
decided the Molmo2 gate in #916, and mlx/backend/cuda/conv.cpp:139 gates the convolution
path on enable_tf32() independently of the matmul path, so it was a plausible explanation
for a convolution blocker and had to be tested.

It is not the explanation here. A controlled A/B at this head, identical in every other
respect, is byte-identical:

MLX_ENABLE_TF32 first divergent stage
1 (MLX default) sscp_conv_0_norm_cumulative_sum max_abs 1.562500000e-2 rms 2.432233746e-3 index 373
0 (declared policy) sscp_conv_0_norm_cumulative_sum max_abs 1.562500000e-2 rms 2.432233746e-3 index 373

So the improvement relative to the recorded blocker is attributable to this head rather than
to the reference policy, and the remaining divergence is a property of the emitted graph.
Recording the A/B because the negative result is what makes the attribution safe.

Remaining, unchanged: cumulative normalization and shared prefix scan, local attention,
relative shift, pooling, projection lengths, projected audio embeddings and dense PLE, then
logits/KV/greedy ASR token exactness and the CLI/server, isolation, cancellation and slot
reuse gates.

@inureyes
inureyes force-pushed the feature/issue-878-gemma3n-xla-audio branch from 0a5aa90 to f1fe444 Compare October 17, 2026 09:26
@inureyes inureyes added status:done Completed and removed status:blocked Blocked by dependencies or other issues labels Oct 17, 2026
@inureyes
inureyes marked this pull request as ready for review October 17, 2026 09:26
@inureyes
inureyes force-pushed the feature/issue-878-gemma3n-xla-audio branch from f1fe444 to a953d21 Compare October 17, 2026 09:35
Add OpenXLA/IREE execution for Gemma3n audio (`Gemma3nAudioFeatureExtractor` mel features through SSCP, conformer blocks, audio projection, hard audio vocabulary replacement, and `dense_ple` language prefill) across CPU, CUDA, and ROCm/HIP targets:

- Emit split StableHLO modules (`sscp`, `conformer`, `merge_ple`) for Gemma3n audio and wire them into `Gemma3nAudioRuntime` and `xla_worker` batch admission with fail-closed placeholder span validation and immediate slot cleanup on cancellation.
- Fix `dense_ple_input_head` in `src/lib/mlxcel-xla/src/emitter/gemma3n_math.rs` so audio placeholder tokens (`token_id >= vocab_size_per_layer_input`, e.g., `262273 >= 262144`) map to row 0 of `embed_tokens_per_layer` via `per_layer_embedding_lookup` (scaled by `embed_tokens_per_layer_scale`) instead of zeroing the gathered row after lookup, matching MLX's `Gemma3nModel::get_per_layer_inputs` and Hugging Face `Gemma3nTextModel`.
- Add ROCm (`xla_iree_rocm`) target compilation and device selection to `Gemma3nAudioRuntime`, and update `molmo`, `molmo2`, `qwen3_vl`, `youtu_vl`, and `numeric_probe` auxiliary weight constructors for `AuxiliaryWeightStorage`.
- Implement `LanguageModel::prepare_sequence_state` on `Gemma3nVLModel` and preserve pre-rendered chat-template audio/image placeholders in `prepare_gemma3n_audio_embeddings` when `ORDERED_MEDIA_PREFIX` is absent so `mlxcel generate --audio` works on both Eager MLX and OpenXLA.
- Verify 100% token-exact greedy output on `mlx-community/gemma-3n-E4B-it-4bit` across Eager MLX (CPU and ROCm GPU), `xla_gemma3n_audio_check`, and `MLXCEL_BACKEND=xla MLXCEL_XLA_DEVICE=hip mlxcel generate`.

Closes #878
@inureyes
inureyes force-pushed the feature/issue-878-gemma3n-xla-audio branch from a953d21 to 9b6e9c2 Compare October 17, 2026 09:39
@inureyes
inureyes merged commit f128d1a into main Oct 17, 2026
23 of 27 checks passed
@inureyes
inureyes deleted the feature/issue-878-gemma3n-xla-audio branch October 17, 2026 09:47
inureyes added a commit that referenced this pull request Nov 24, 2026
## Summary

- OpenXLA: the Phi4MM speech/vision LoRA A/B tensors are now `WeightSpec::Whole`, not `Proj`. Since #2861 the loader transposes `Proj` specs for the single-sequence `InOut` layout, while the emitter declares the LoRA pairs in the checkpoint layout (`[rank, in]`, `[out, rank]`) and contracts them untransposed, so prefill failed with `expected 320x3072, actual 3072x320`. `Whole` is never transposed and stays f32-resident (the declared element type) in every layout, so the ragged `OutIn` path uploads exactly what it did before. I chose this over flipping the declarations because the LoRA branch is shared by single and ragged graphs. Flipping the declarations would have meant changing the LoRA branch per layout, and the f16-resident `Proj` rule would also have needed an exemption.
- A new `WeightSpec::uploads_transposed` now drives the loader's `Proj` branch. The new test `phi4mm_lora_declared_shapes_match_uploaded_shapes_in_every_layout` compares the declared LoRA shapes in the prefill, embeddings-prefill, decode and ragged graphs against what the loader uploads, in both layouts. With the old `Proj` push it fails: `prefill (InOut) declares ...qkv.lora_A.speech as [3, 8] but the loader uploads [8, 3]`.
- Eager CLI: `materialize_phi4mm_ordered_prompt` now passes a prompt without ordered-media markers through to `prepare_phi4mm_prompt_tokens`, as the Gemma3n path does since #922. That function inserts the audio tag at the start of the user turn, which is the same normalization the OpenXLA CLI applies, and it still rejects a placeholder count that disagrees with the request.

## Test plan

Checkpoint: microsoft/Phi-4-multimodal-instruct@93f923e1. Input: the official `what_is_shown_in_this_image.wav` with "Transcribe the audio exactly." and `-n 8 --temp 0`.

- [x] Eager (`MLXCEL_SDPA_DETERMINISTIC=1`), XLA cuda and XLA local-task all produce `13347 382 10147 306 495 3621` ("what is shown in this image")
- [x] `xla_phi4_audio_check` passes on local-task and cuda
- [x] Phi4MM vision (vision LoRA) runs on XLA cuda. It matches eager for the first 8 tokens, and XLA f16 and f32 give identical output
- [x] qwen2.5-0.5b-instruct-bf16 on XLA cuda gives the same tokens as eager
- [x] `cargo test -p mlxcel-xla --lib -- phi4` and `cargo test --features cuda --lib -- phi4mm_` pass
- [x] `cargo check --features cuda,xla-iree --all-targets`, `cargo check --no-default-features --features xla-diagnostics --all-targets`, `insert_apache_header.py --check` and `cargo fmt --check` pass

Closes #3362
@inureyes inureyes added this to the 0.8 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:inference Generation, sampling, decoding (incl. speculative, DRY) area:models Model architectures, weights, loading, metadata priority:low Low priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(xla): support Gemma3n audio with dense PLE prefill

1 participant