Repository navigation
fix(xla): use the transformers Gemma 3 image mask on the OpenXLA path - #2789
Merged
Merged
Conversation
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
Member
Author
Implementation Review SummaryIntent
Findings AddressedNone needed fixing at CRITICAL or HIGH. Remaining Items
Verification
|
Member
Author
|
Security and performance review of dff56af (diff from 9f06fef): no CRITICAL, HIGH or MEDIUM findings, so nothing was changed. What was checked:
LOW, not fixed:
Tests run: |
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
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
marked this pull request as ready for review
October 31, 2026 04:20
This was referenced Oct 31, 2026
inureyes
added a commit
that referenced
this pull request
Oct 31, 2026
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.
This was referenced Oct 31, 2026
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
prepare_gemma3_vlm_prefill) now matchesvision::merge::attention_mask_for_image_runscell for cell: causal, plus bidirectional inside each maximal image-token run, padding keys masked, query validity not applied.embeddings_prefill_uses_authoritative_maskstill controls thef32::MINvalue check and the VLM gate; its doc comment says the window still applies.GEMMA3_VLM_MASK_MODEis nowgemma3-vlm-causal-image-blocks-sliding-band-f32-min-v2, so bundles keyed on the old behavior are rejected. The prepared-prefill schema is unchanged.mlxcel_xla::XlaPreparedPrefillLogitsreturns final-position embeddings-prefill logits from the ragged engine the server uses. No logits API existed outside thediagnosticsfeature, and the parity test needs one.xla_gemma3_reference_checkexpected mask and progress text now describe the new mask.docs/benchmarks.mdand the module doc say the OpenXLA path uses the same mask, and theGemma3IreeHostPreprocessordoc 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_causalalso fails.authoritative_embeddings_mask_keeps_the_sliding_window_band:left: None, right: Some(4096).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.Test results (fixed)
cargo fmt --all -- --check: clean.--profile test-fast --features mlxcel-core/cuda): pass. Clippy--all-targets -D warnings: clean.--features cuda,xla-backendlib,loading::module: 383 passed.cuda,xla-ireeclippy (-p mlxcel-xla -p mlxcel --lib --test xla_prepared_prefill -D warnings): clean.cargo check --features cuda,xla-reference-diagnostics -p mlxcel --lib --tests(covers thexla_gemma3_reference_checkexpected-mask change): clean.xla_prepared_prefill --ignoredwithMLXCEL_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 fromMLXCEL_XLA_DEVICE(defaultlocal-task).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.xla-backendwithoutxla-ireedoes not pass clippy. The warnings come fromhost_preprocessor_molmo_tests.rsandworker_failfast.rs, which this PR does not touch.Real-checkpoint smoke
mlxcel-server(releasecuda,xla-iree) onmodels/gemma-3-4b-it-4bitwithMLXCEL_BACKEND=xla MLXCEL_XLA_DEVICE=cuda MLXCEL_XLA_CONTEXT_CAPACITY=512received one image chat request fortests/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