Skip to content

fix(xla): use the transformers Gemma 3 image mask on the OpenXLA path - #2789

Merged
inureyes merged 4 commits into
mainfrom
fix/issue-2781-xla-gemma3-image-mask
Oct 31, 2026
Merged

inureyes merged 4 commits into
mainfrom
fix/issue-2781-xla-gemma3-image-mask

Conversation

@inureyes

@inureyes inureyes commented Oct 31, 2026 •

Copy link
Copy Markdown
Member

Summary

  • The OpenXLA Gemma 3 host mask (prepare_gemma3_vlm_prefill) now matches vision::merge::attention_mask_for_image_runs cell for cell: causal, plus bidirectional inside each maximal image-token run, padding keys masked, query validity not applied.
  • The emitter applies its existing sliding-window band to the caller's embeddings-prefill bias on sliding layers for every windowed config. embeddings_prefill_uses_authoritative_mask still controls the f32::MIN value check and the VLM gate; its doc comment says the window still applies.
  • GEMMA3_VLM_MASK_MODE is now gemma3-vlm-causal-image-blocks-sliding-band-f32-min-v2, so bundles keyed on the old behavior are rejected. The prepared-prefill schema is unchanged.
  • New public mlxcel_xla::XlaPreparedPrefillLogits returns final-position embeddings-prefill logits from the ragged engine the server uses. No logits API existed outside the diagnostics feature, and the parity test needs one.
  • The xla_gemma3_reference_check expected mask and progress text now describe the new mask. docs/benchmarks.md and the module doc say the OpenXLA path uses the same mask, and the Gemma3IreeHostPreprocessor doc comment describes it.

Failing-first evidence (main 9f06fef plus the new tests)

  • exports_causal_image_block_mask: query 1 key 2: left 0.0, right f32::MIN (future key visible). image_blocks_start_at_position_zero_and_text_only_prompts_stay_causal also fails.
  • authoritative_embeddings_mask_keeps_the_sliding_window_band: left: None, right: Some(4096).
  • Root loading::vlm::gemma::xla_mask_tests (2 tests): [0, 7, 9, 9, 7, 9, 7]: query 1 key 2: OpenXLA 0, MLX f32::MIN.
  • local_task_gemma3_vlm_prefill_matches_mlx_mask: row 0 matches (7e-7), then rows 1 to 11 are off by 0.06 to 4.8.
  • Band isolation: with the host mask fixed and only the band change reverted, rows 0 to 3 match and rows 4 to 11 fail (row 4 off by 1.26), starting at the first row past the 4-token window.

Test results (fixed)

  • cargo fmt --all -- --check: clean.
  • mlxcel-xla lib, all 365 tests (--profile test-fast --features mlxcel-core/cuda): pass. Clippy --all-targets -D warnings: clean.
  • --features cuda,xla-backend lib, loading:: module: 383 passed.
  • Release cuda,xla-iree clippy (-p mlxcel-xla -p mlxcel --lib --test xla_prepared_prefill -D warnings): clean.
  • Release cargo check --features cuda,xla-reference-diagnostics -p mlxcel --lib --tests (covers the xla_gemma3_reference_check expected-mask change): clean.
  • xla_prepared_prefill --ignored with MLXCEL_XLA_DEVICE=cuda MLXCEL_XLA_PRECISION=f32: the new test passes, worst row error 2.6e-6 against the 1e-3 tolerance. CUDA defaults to f16 contractions, which leave a 3e-3 baseline gap at row 0, so the test takes the device from MLXCEL_XLA_DEVICE (default local-task).
  • The two existing tests in that target hardcode local-task. On this host, IREE fails to create that device (thread creation failed with 22), on main as well as on this branch, so they could not run here.
  • The root lib under xla-backend without xla-iree does not pass clippy. The warnings come from host_preprocessor_molmo_tests.rs and worker_failfast.rs, which this PR does not touch.

Real-checkpoint smoke

mlxcel-server (release cuda,xla-iree) on models/gemma-3-4b-it-4bit with MLXCEL_BACKEND=xla MLXCEL_XLA_DEVICE=cuda MLXCEL_XLA_CONTEXT_CAPACITY=512 received one image chat request for tests/fixtures/test_image_shapes.png (278 prompt tokens). It answered "A red square is located in the upper left corner. A blue circle is positioned in the upper right. A green triangle is placed below the circle." The prompt is shorter than the 1024 window, so this run does not exercise the band. The tiny IREE test covers it.

Closes #2781

The OpenXLA Gemma 3 image prefill still used the pre-#2773 mask: every non-padding token attended to every other one on every layer, with no sliding-window band. Text rows read later prompt tokens, so XLA and MLX image outputs diverged even with identical prompt ids (#2779).

prepare_gemma3_vlm_prefill now builds the MLX mask cell for cell: a valid key is visible to a query at or after it, or to any query in the same maximal image-token run. The emitter applies its existing sliding-window band to the caller's bias on sliding layers for every windowed config, so the authoritative-mask flag no longer drops the band. GEMMA3_VLM_MASK_MODE moves to v2 so bundles keyed on the old behavior are rejected. XlaPreparedPrefillLogits exposes final-position embeddings-prefill logits of the ragged engine for parity gates.

Tests: new host-mask unit tests, a root-crate test comparing the OpenXLA mask with vision::merge cell for cell, and an ignored real-IREE test that matches the MLX Gemma 3 forward within 1e-3 on every row of a 12-token prompt with a 4-token window (worst 2.6e-6). All fail on main; with only the band reverted the IREE test fails from row 4, the first row past the window. A gemma-3-4b-it-4bit image chat on MLXCEL_BACKEND=xla names the red square, blue circle and green triangle.

Closes #2781
@inureyes inureyes added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:medium Medium priority area:models Model architectures, weights, loading, metadata modeltype:vlm Vision-language model labels Oct 31, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Prefill Gemma 3 image prompts on the OpenXLA path under the same transformers mask as MLX (causal plus bidirectional image blocks, banded on sliding layers).

Findings Addressed

None needed fixing at CRITICAL or HIGH.

Remaining Items

  • src/multimodal/host_preprocessor.rs:1137: the Gemma3IreeHostPreprocessor doc comment still says it builds an "exact bidirectional additive prefill mask"; it now builds the causal image-block mask (LOW).
  • XlaPreparedPrefillLogits is public in every iree build but only a test uses it, and it repeats Qwen25VlLanguageDiagnosticEngine::capture without the M-RoPE check. The PR body explains why. An alternative is one shared helper, or gating it behind diagnostics and moving the test to a xla-reference-diagnostics target (LOW).

Verification

  • All stated requirements implemented (host mask, band, identity v2, docs, all four tests, real-checkpoint smoke recorded in the body)
  • No placeholder/mock code remaining
  • Integrated into project code flow (Gemma3IreeHostPreprocessor -> prepare_gemma3_vlm_prefill; the band is in the shared embeddings/DeepStack prefill arms)
  • Project conventions followed
  • Existing modules reused where applicable (the existing band builder; no second builder)
  • No unintended structural changes (only Gemma 3 sets embeddings_prefill_uses_authoritative_mask, so other families' bands are unchanged; vmfbs and the bundle fingerprint hash the MLIR text, so the graph change re-keys compiled artifacts on its own)
  • Tests pass (re-run in review: mlxcel-xla prepared_gemma3/gemma3_vlm_mask_tests 12/12, root loading::vlm::gemma::xla_mask_tests 2/2)

@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review of dff56af (diff from 9f06fef): no CRITICAL, HIGH or MEDIUM findings, so nothing was changed.

What was checked:

  • Mask size: the S x S host bias is not new. S is still capped by the existing sequence_len > context_capacity check, and bias_count still uses checked_mul. The new image_blocks vector holds S entries and the block counter is at most S. Each index query * S + key is below the checked bias_count, and token_ids[index - 1] only runs when index > 0.
  • Image token runs from input: the placeholder count still has to match the projected rows exactly, so extra or fake image tokens are rejected. Block ids are computed the same way as MLX image_block_ids.
  • Masked values: the sliding band now also applies to the authoritative mask (it uses -1e30 and the caller's bias uses f32::MIN). Every non-padding query keeps its own key, so no row loses all its keys on account of the band. A padding row is fully masked with finite values, which gives a uniform softmax with no NaN. This was already true before this PR, and those rows are never read.
  • XlaPreparedPrefillLogits: it goes through PreparedIreePrefill::prepare_for_mode, then the slot, hidden size, capacity, position-mode and adapter checks in prefill_prepared_slot_logits. It adds no new FFI surface.
  • Compiled-artifact reuse: vmfbs are keyed by a hash of the MLIR text, the flags and the compiler, so the changed band emission compiles to a new artifact. The mask_mode v2 bump changes the Gemma 3 VLM runtime-bundle identity.

LOW, not fixed:

  • XlaPreparedPrefillLogits loads the ragged bundle with 4 slots but only uses slot 0, so it reserves 4x the KV memory it needs. It is also exported in every iree build, although only the parity test uses it. Possible follow-up: gate it behind diagnostics or load with one slot.

Tests run: cargo test --profile test-fast -p mlxcel-xla --features mlxcel-core/cuda --lib -- prepared_gemma3 gemma3_vlm_mask_tests gemma3_vlm_compatibility_tests (12 passed).

The Gemma3IreeHostPreprocessor doc comment still called the prefill mask an exact bidirectional additive mask. It now states the mask the preprocessor builds (causal plus bidirectional attention within each image block, key padding masked) and notes that the sliding-window band is applied in the graph. No other stale description of the OpenXLA Gemma 3 mask remains outside TECHNICAL_REPORTS and spike.

Comment-only change. Validation: cargo fmt --all -- --check, clippy -p mlxcel-xla --all-targets -D warnings, and the prepared_gemma3 and gemma3_vlm lib tests (12 passed) all pass.

Refs #2781
@inureyes inureyes added status:done Completed and removed status:review Under review labels Oct 31, 2026
Add the English and Korean technical reports for the OpenXLA Gemma 3 image mask fix (#2781): the host mask that mirrors the MLX image-block predicate, the sliding band kept in the graph, the v2 mask identity, the logits entry point for the IREE parity test, and the residuals left unverified.
@inureyes
inureyes marked this pull request as ready for review October 31, 2026 04:20
@inureyes
inureyes merged commit 863ddb7 into main Oct 31, 2026
31 checks passed
@inureyes
inureyes deleted the fix/issue-2781-xla-gemma3-image-mask branch October 31, 2026 04:21
inureyes added a commit that referenced this pull request Oct 31, 2026
Bilingual report (English and Korean) for the five LOW residuals of #2787, #2788 and #2789 closed by this PR.
inureyes added a commit that referenced this pull request Oct 31, 2026
Closes the five LOW residuals of #2787, #2788 and #2789 listed in #2790, in one PR.

## Changes

- **KV storage report (item 1).** `kv_cache_storage_modes` returns `Option<Vec<Option<KVCacheMode>>>`; a `None` entry is a layer with no KV. Families describe layers with `LayerKv` (`Full`, `Sliding`, `Fp16Only`, `None`) from the predicate their cache builder uses. Llama 4 reports chunked layers as FP16 (`uses_chunked_cache` now drives the builder, the masks and the report). Qwen3-Next, Qwen 3.5, Qwen4-Exp, Bailing linear, LFM2 and NemotronNAS report linear, convolution and skipped layers as stateless. Model-owned families without a mode table report real storage instead of `None`: DeepSeek V4, RecurrentGemma, Muse Glimmer, Mamba, Mamba2 and RWKV7 as listed, plus Nemotron-H, Jamba, Falcon-H1, Plamo2, GraniteMoeHybrid, Kimi Linear, Kimi K3 and Inkling, which had the same gap, and the five VLM wrappers around them. The server log adds `kv_cache_mode_stateless_layers`; `logit_trace` prints the stateless count.
- **Sliding window (item 2).** `validate_sliding_window` (via `cache_window`, only when a layer slides) fails the load for 0 or values above `i32::MAX` in Gemma 3, Gemma 4, GPT-OSS, ExaOne 4, Laguna, Step 3.5, Ministral 3, Mellum and AFMoE; Gemma 3 also rejects `sliding_window_pattern: 0`. Gemma 3, GPT-OSS, Laguna, Mellum, ExaOne 4, Ministral 3 and AFMoE store the validated `i32` for their builders. Gemma 4 validates in both the single-process load and the pipeline-stage load (`Gemma4StageModel::from_filtered_weights`) and keeps its casts on the shared `TextConfig` (dozens of sites), now lossless after the check.
- **IREE local-task (item 3).** `csrc/xla_local_task.c` builds the device without the flag registry: executor with 8 MiB worker stacks over `MLXCEL_XLA_LOCAL_TASK_WORKERS` workers (1..=256, IREE's topology limit; anything else fails the load naming the variable) or the physical-core topology, all loaders, heap allocator, task driver, default device with the same proactor pool the runtime uses. Both device-creating entry points use it; other drivers are unchanged. Every IREE symbol used is exported by the pinned CUDA tree and by `iree-dist-3.12.0rc20260721-linux-x86_64` (the only dist published for that release; there is no aarch64 dist), and the new C file compiles against both header trees.
- **Test support (item 4).** `XlaPreparedPrefillLogits` needs mlxcel-xla `test-support` (root `test-utils`) or `diagnostics`, resets slots before each prefill, and `Qwen25VlLanguageDiagnosticEngine` wraps it. `xla_prepared_prefill` requires `test-utils`; the CI link step passes it.
- **Pipeline gate (item 5).** Only `StageUnreachable` (timeout or failed send) opens the gate. A `RunEntry` timeout opens it unattributed, so the entry stage keeps its teardown wait and the next probe names the silent stage; a failed send logs "could not be reached", and a probe that reopens the gate logs its real cause (send failure or timeout). `PipelineUnavailable.stage` is `Option<String>`. `docs/distributed.md` describes the new rule.

## Failing first

Each new test fails on `main` 1a257bc or, where it cannot compile there, under a mutation restoring `main`'s behaviour:

- Existing local-task tests, main binary: all three fail with `thread creation failed with 22; [runtime-init] failed to open IREE HAL device 'local-task'`.
- `local_task_executor_uses_8_mib_stacks_without_iree_flags`, stack set back to 128 KiB: `xla_local_task_probe failed: ... thread creation failed with 22`.
- `llama4_chunked_layers_report_fp16_storage_under_int8`: `left: Some([Some(Int8) x8])` vs expected `Int8` only at 3 and 7.
- `qwen3_next_linear_layers_report_no_kv_storage`: eight `Some(Int8)` vs `[None, None, None, Some(Int8), ...]`.
- `recurrent_gemma_reports_...`, `mamba_reports_every_layer_stateless`, `deepseek_v4_reports_fp16_storage_for_every_layer` (override returning `None`): `left: None` / `a storage report`.
- `gemma3_rejects_zero_sliding_window_pattern_at_load`, `sliding_window_zero_is_a_load_error` (validation off): the loads succeed.
- `run_entry_timeout_does_not_name_the_entry_stage` (main attribution): `failed_peer` is `Some("127.0.0.1:41749")`, the entry stage.
- `send_failure_opens_the_gate_with_a_send_reason`: the open line reads `remote stage 127.0.0.1:40565 did not answer within 1s`.

## Verification (spark-102, GB10)

- `cargo fmt --all -- --check`, `make verify-env-var-docs`: clean.
- `cargo clippy --profile test-fast --features cuda -p mlxcel -p mlxcel-core -p mlxcel-xla --lib --tests -- -D warnings` and `cargo clippy --release --features cuda,xla-iree,test-utils -p mlxcel-xla -p mlxcel --lib --test xla_prepared_prefill -- -D warnings`: clean.
- After the review fixes: clippy on `mlxcel` + `mlxcel-xla` lib and tests clean, `distributed::pipeline::` 416 passed, `mlxcel-xla` `local_task` 6 passed.
- Lib tests (`--test-threads=1`, gpu-lock): `models::` + `vision::` 3429 passed; `distributed::` + `server::batch::scheduler` 1845 passed; `mlxcel-core` `cache::` + `generate::` 624 passed; `mlxcel-xla --lib` 370 passed.
- Integration (`cuda,test-utils`): `distributed_integration` 20, `pipeline_e2e` 30, `pipeline_remote_real_models` 10, `pipeline_server_remote_real_models` 7, `pipeline_ci_multi_stage_real_models` 4 (`--include-ignored --skip glm_moe_dsa`, `MLXCEL_REQUIRE_MODELS=1 MLXCEL_SDPA_DETERMINISTIC=1`), `disaggregated_serving_e2e` 2, `disaggregated_router_e2e` 8: all pass.
- `cargo test --release --features cuda,xla-iree,test-utils --test xla_prepared_prefill -- --ignored`: 4/4 on the default `local-task` device. `MLXCEL_XLA_LOCAL_TASK_WORKERS=0` and `abc` fail the load naming the variable; `2` passes. Unit tests also reject 257 and 1000.
- Item 4 gating: a root `use mlxcel_xla::XlaPreparedPrefillLogits` fails `cargo check --features cuda,xla-iree` with E0432 and passes with `test-utils`. `--features cuda,xla-reference-diagnostics --lib --tests` checks clean. (Both checks ran in the `test-fast` profile.)
- Server smoke, `--kv-cache-mode int8`, release `mlxcel-server`: `llama-4-scout-17b-16e-instruct-4bit` logs `applied_layers=12 total_layers=48 stateless_layers=0`; `gemma-3-1b-it-4bit` logs `applied_layers=4 total_layers=26`.

Not changed: with `MLXCEL_XLA_DEVICE=cuda`, `local_task_gemma3_vlm_prefill_matches_mlx_mask` misses its 1e-3 tolerance (up to 5.4e-3) under the default `f16` CUDA precision, identically on `main`; it passes with `MLXCEL_XLA_PRECISION=f32`.

Closes #2790



## Compatibility notes

- `PipelineUnavailable.stage` is a public field and changes from `String` to `Option<String>` (`None` until a probe names the silent stage); callers that read it need `as_deref()`.
- The `kv_cache_mode_total_layers` startup log now counts only layers that hold KV, so hybrid models (Qwen3-Next, LFM2, Jamba and similar) log a lower total than before; stateless layers are reported in the new `kv_cache_mode_stateless_layers` field.
inureyes added a commit that referenced this pull request Nov 1, 2026
* refactor: move the sliding-window validators into mlxcel-core

Both validators were `pub(crate)` in `src/models/model_owned.rs`, so the drafters in `mlxcel-core` and the OpenXLA emitter could not reach them and every new caller would have re-implemented the check. They now live as `pub fn` in `mlxcel_core::cache` beside `RotatingKVCache`, whose ring arithmetic divides by zero on a zero window and whose size is `i32`.

The model layer re-exports `cache_window`, so the nine existing callers are unchanged. The helper unit test moved with the function, and a second test covers the all-global config whose window stays unused.

Refs #2798

* fix(models): validate every family's sliding window at load

Families that turn a config window into a cache size or a mask still cast with `as i32` and never checked it. A zero silently means full attention for the dense-cache and mask-only families, panics the rotating-cache ring arithmetic, and masks every key to `-1e30` in the OpenXLA band; a value above `i32::MAX` wraps.

Each family now calls `cache_window` once at load with the sliding-layer predicate its layer builder already uses, stores the returned `i32`, and the casts are gone. Families that only rejected zero use the helper, which also rejects values above `i32::MAX`. One test per family asserts that both bounds fail the load with the family named in the message.

Refs #2798

* fix(drafter): validate the assistant drafters' sliding windows

The Muse Glimmer and Gemma 4 assistant drafters built their context windows from `config.sliding_window as i32` and only rejected zero, so a value above `i32::MAX` wrapped to a small or negative window and narrowed the draft context silently.

Both validate through `mlxcel_core::cache::cache_window` at load, store the result, and their config tests cover both bounds.

Refs #2798

* fix(xla): reject unusable sliding windows at config parse

The emitter's local-band predicate reads the window as `i32`. A zero masks every key to `-1e30`, so softmax spreads uniformly over the context and the logits are silently wrong; a wrapped value narrows the band.

Gemma 2, Gemma 3, OLMo3 and Cohere2 now validate the window where the config is parsed and return the helper's error, so `Config::from_json_str` and `Config::from_json` reject a config the graph cannot honor. A config that omits the field still parses.

Refs #2798

* test(xla): check the Gemma 3 mask parity at f32 and f16

The parity test only passed on CUDA with `MLXCEL_XLA_PRECISION=f32`, but f16 contractions are the device default and what deployments run. It now runs two arms in one test: f32 at the strict 1e-3 absolute bound, which is what catches a small masking difference, and the device default with a bound scaled to each row's logit spread plus a top-1 match, which the #2789 mask bugs would still exceed by an order of magnitude.

Both arms print their per-row error and spread. Each arm loads its own engine because the precision is read at emit time and the vmfb cache is keyed per precision.

Refs #2798

* fix(models): check RecurrentGemma's window before the weights

The validation ran after the embedding and layer loads, so an unusable `attention_window_size` surfaced as a missing-weight error first and the window never reached the rotating cache. It now runs right after the block-type expansion, before any weight is read.

Refs #2798

* test(models): expect the band-radius message in the privacy filter

The validator now reports the shared sliding-window error for `sliding_window` rather than the array-dimension one. The hostile-value loop keeps the other dimensions, and a new assertion pins the band radius to the helper's message.

Refs #2798

* test(xla): report both parity arms per row

The failure messages carried a derived Debug dump whose fields the lint could not see as used, and the production arm did not show the bound it missed. Both arms now format the row, error, spread, bound and top-1 explicitly, which removes the dead-code warning and makes a failure readable.

Refs #2798

* fix(models): match each window check to its consumer's predicate

The window validation added for issue #2798 used predicates that disagreed with what the layer builders and mask paths actually do, so four configs still accepted a window the consumer could not take:

- Baichuan looks the layer index up in `sliding_window_layers`, so a list of out-of-range indices has no sliding layer. Such a config now loads with an unused window instead of failing.
- Gemma 3 embedding: `is_full_attention` treats a period of 0 as every layer sliding (`is_multiple_of(0)` is false), so the check is `pattern != 1`, not `pattern > 1`.
- Gemma 3n and OLMo 3 treat every kind that is not `full_attention` as sliding in their mask paths, so an unknown kind can no longer skip the check.

EmbeddingGemma 2 now reads the raw JSON value through `as_u64` first, so a positive integer above `i64::MAX` reaches the validator instead of silently falling back to the 512 default. A JSON null or a non-integer still keeps the default, as `i32_field` did before.

Tests cover the unknown-kind cases for Gemma 3n and OLMo 3, the zero period for Gemma 3 embedding, an out-of-range Baichuan layer list, and a 2^63 window for EmbeddingGemma 2.

Verification: cargo fmt; clippy -D warnings on mlxcel (cuda), mlxcel-core (cuda) and mlxcel-xla; models:: 2529 passed, drafter:: 233, cache:: 588, emitter:: 199.
@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:models Model architectures, weights, loading, metadata modeltype:vlm Vision-language model priority:medium Medium 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(xla): Use the transformers Gemma 3 image mask on the OpenXLA path

1 participant