Skip to content

fix: restore Phi4MM audio on the XLA and eager CLI paths - #3380

Merged
inureyes merged 3 commits into
mainfrom
fix/issue-3362-phi4mm-audio
Nov 24, 2026
Merged

inureyes merged 3 commits into
mainfrom
fix/issue-3362-phi4mm-audio

Conversation

@inureyes

Copy link
Copy Markdown
Member

Summary

  • OpenXLA: the Phi4MM speech/vision LoRA A/B tensors are now WeightSpec::Whole, not Proj. Since perf(xla): load single-sequence graphs with transposed weights (#2859) #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 feat(xla): add Gemma3n audio execution #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.

  • 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")
  • xla_phi4_audio_check passes on local-task and cuda
  • Phi4MM vision (vision LoRA) runs on XLA cuda. It matches eager for the first 8 tokens, and XLA f16 and f32 give identical output
  • qwen2.5-0.5b-instruct-bf16 on XLA cuda gives the same tokens as eager
  • cargo test -p mlxcel-xla --lib -- phi4 and cargo test --features cuda --lib -- phi4mm_ pass
  • 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

OpenXLA: since #2861 the loader transposes every `Proj` spec for the single-sequence `InOut` layout, but the Phi4MM speech/vision LoRA A/B tensors were pushed as `Proj` while the emitter declares them in the checkpoint layout (`[rank, in]`, `[out, rank]`) and contracts them with the untransposed helpers. Prefill failed with `expected 320x3072, actual 3072x320`. The pairs are now `Whole` specs, which the loader never transposes in any layout and keeps f32-resident (the declared element type), so the ragged `OutIn` path is unchanged. A `WeightSpec::uploads_transposed` helper now drives the loader's `Proj` branch, and a new test checks the declared LoRA shapes of the prefill, embeddings-prefill, decode and ragged graphs against what the loader uploads in both layouts (it fails with the old `Proj` push).

Eager: since #874 `materialize_phi4mm_ordered_prompt` refused a prompt without ordered-media markers, which is what the CLI renders through the Phi4MM template. Mirroring the Gemma3n fallback from #922, such a prompt now passes through to `prepare_phi4mm_prompt_tokens`, which inserts the audio tag at the start of the user turn (as the OpenXLA CLI does) and still rejects a placeholder count that disagrees with the request.

Verified on microsoft/Phi-4-multimodal-instruct@93f923e1 with the official WAV: eager, XLA cuda and XLA local-task all produce `13347 382 10147 306 495 3621`.

Closes #3362
@inureyes inureyes added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:high High priority area:inference Generation, sampling, decoding (incl. speculative, DRY) area:architecture Architecture and code structure changes labels Nov 24, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Restore Phi4MM audio on OpenXLA (LoRA A/B no longer transposed under InOut) and on the eager CLI (markerless prompt falls back to the Phi4MM normalizer), per #3362.

Findings Addressed

No CRITICAL or HIGH findings, so no commits were added.

Remaining Items

  • The Rows arm in iree.rs still matches projection_layout directly instead of calling WeightSpec::uploads_transposed, so the helper's doc ("drives the loader") covers only the Proj arm. Behaviour is identical today; routing Rows through the helper would remove the drift risk. (LOW)
  • On the server, a Phi4MM audio request whose chat template drops every ordered marker used to fail closed; it now gets tags inserted at the first <|user|>. Every server audio route (chat, responses, anthropic, transcriptions) builds a chat request with markers, and clip and image counts are still enforced by prepare_phi4mm_prompt_tokens, so only tag placement in a multi-turn prompt could differ. Acceptable as is. (LOW)

Checks

  • Memory and upload cost: Phi4MM has fused qkv and gate_up, so supports_f16_resident() is false and LoRA tensors were already uploaded as f32 under Proj. OutIn uploads the same bytes and dims as before (whole_graph_shape only reshapes mixer.conv1d). InOut now skips one transpose per LoRA tensor.
  • Cache key and artifact contract: the emitter output is unchanged (only a comment changed) and there is no on-disk weight cache, so no key bump is needed.
  • uploads_transposed returns InOut for every Proj, which is the old condition. Dense, Gemma3n (Projection maps to Proj) and other families are unchanged.
  • Eager fallback: a markerless prompt still has to match the attached media. Audio tags must be exactly 1..N in order, image and audio slot counts must equal the inputs, reserved literals are rejected, and expand_phi4mm_placeholders checks cardinality again. Prompts with markers take the unchanged parse path with its cardinality check, and user text containing the marker prefix is still rejected by validate_no_reserved_media_sentinels.

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass: cargo test -p mlxcel-xla --lib --profile test-fast -- phi4 (11 passed), and the cuda lib phi4mm_ filter with --test-threads=1 under the GPU lock (16 passed). The new shape test pins declared and uploaded shapes in all four graph kinds and both layouts.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 24, 2026
@inureyes
inureyes marked this pull request as ready for review November 24, 2026 03:07
inureyes added a commit that referenced this pull request Nov 24, 2026
`scripts/inkling2_mlx_community_remap.py` landed in #3381 with a `python3` shebang but Git mode 100644, so `test_script_executable_modes` in the python tooling tests job fails on main and on every open PR (seen on #3380). This sets the executable bit; no content change.
@inureyes
inureyes merged commit d81e7a1 into main Nov 24, 2026
33 checks passed
@inureyes
inureyes deleted the fix/issue-3362-phi4mm-audio branch November 24, 2026 05:18
inureyes added a commit that referenced this pull request Nov 24, 2026
## Summary

The OpenXLA CLI now prepares a request's images (or Phi4MM media) before it compiles its one context shape. It sizes the shape and admission from `PreparedPrefill::sequence_len`, the expanded prompt the family preprocessor actually produced. The serve worker already routes on that same length. The per-family worst-case floor is no longer added on top, so Qwen2-VL stops compiling 32768 for a 64-token image, and Gemma3, Molmo v1 and Phi4MM no longer get a 256 shape they cannot fit.

- `multimodal::xla_image_prefill` holds the one rule: `PreparedImagePrefill`, `prepare_image_prefill` (DeepStack first) and `xla_request_positions`. The CLI, `XlaBackendSession::generate_images_greedy` and the server preprocess stage all use it.
- `backend::xla::create_prepared_xla_session` builds the request-sized session and takes over the preprocessor that prepared the images, so vision weights load once.
- `xla_image_context_floor` now only picks the server's startup buckets and guards an unsized session. Family vision limits still fail closed, and the Qwen3-VL 512-patch IREE vision bound is documented in the module docs and in `docs/environment-variables.md`.

## Verification (GB10, XLA cuda, `tests/fixtures/test_image.png`, `-n 16 --temp 0`, eager with `MLXCEL_SDPA_DETERMINISTIC=1`)

| Model | Old shape | New shape (prompt) | Tokens vs eager |
|---|---|---|---|
| qwen2-vl-2b-instruct-4bit | 32768 (OOM) | 256 (89) | 11/11 match |
| qwen2.5-vl-3b-instruct-4bit | 32768 (OOM), pinned 256 refused | 256 (89), pinned 256 admitted | 16/16 match |
| qwen3-vl-2b-instruct-4bit | 256 | 256 (78) | 16/16 match |
| gemma-3-4b-it-4bit | 256, refused | 512 (272) | 15/16, known token-16 divergence |
| molmo-7b-d-0924-4bit | 256, refused | 512 (325) | 16/16 match |
| youtu-vl-4b-instruct | 256 | 256 (74) | admitted; output broken by #3364 |
| phi-4-multimodal-instruct | 256, refused | 1024 (552) | 16/16 match with #3380's fix applied locally; on main prefill fails with the #3362 LoRA transpose |
| llava-interleave-qwen-0.5b-bf16 | 1024 | 1024 (742) | 16/16 match |

Each XLA run matched the same binary pinned at `MLXCEL_XLA_CONTEXT_CAPACITY=1024`. `llava-1.5-7b-4bit` cannot load its XLA image preprocessor on main (`text_config.hidden_size` missing), and that is unrelated to sizing.

After review: the Qwen2-VL/Qwen2.5-VL 256-patch vision cap (`QWEN2_VL_PATCH_BUCKETS`) is documented next to the Qwen3-VL 512 and Youtu-VL 256 caps and pinned by a refusal test; CLI `preparation_time` excludes the one-time vision weight load and compile, as before; the unpinned Phi4MM producer is bounded by `min(window, context ladder top)`; a two-image test pins multi-image sizing.

- [x] Per-family expansion and sizing unit tests (`multimodal::xla_image_prefill::tests`, including the large-image refusals for Qwen2-VL, Qwen3-VL and Youtu-VL and a two-image case), server `xla_preprocess` tests, CLI sizing tests (18 pass)
- [x] `cargo check --features cuda,xla-iree --all-targets`, `cargo check --no-default-features --features xla-diagnostics --all-targets`, `cargo clippy --features cuda,xla-iree --lib --bins -D warnings`, `scripts/insert_apache_header.py --check`

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

Labels

area:architecture Architecture and code structure changes area:inference Generation, sampling, decoding (incl. speculative, DRY) 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: restore Phi4MM audio on the XLA and eager CLI paths

1 participant