Skip to content

feat: add Gemma3 VLM OpenXLA path (#869) - #917

Merged
inureyes merged 1 commit into
mainfrom
feature/issue-869-gemma3-vlm-xla
Oct 15, 2026
Merged

inureyes merged 1 commit into
mainfrom
feature/issue-869-gemma3-vlm-xla

Conversation

@inureyes

@inureyes inureyes commented Jul 24, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Emit the Gemma3 SigLIP vision encoder and 2D average-pooling + RMSNorm + linear multi_modal_projector in StableHLO without the LLaVA 2-layer MLP contract.
  • Add the Gemma3 prepared-prefill seam with one-time text embedding scaling (sqrt(hidden_size)), native projector rows, and the authoritative bidirectional image-block and padding mask used by embeddings prefill.
  • Bind the prepared-prefill ABI, additive-mask mode/value, post-scale policy, newline/image/pad/BOI/EOI tokens, SigLIP/projector configuration, and Gemma3 sliding/global settings into an explicit stable identity used by both single-sequence and ragged IREE bundle fingerprints while preserving the existing dense identity byte-for-byte for ordinary text-only Gemma3 configs.
  • Parse the nested Gemma3 text configuration for the shared language emitter and preserve local/global RoPE behavior without changing ordinary text-only token prefill.
  • Treat root text-only Gemma3 configurations as direct language-model configs unless they also declare a vision configuration, preserving existing text-session startup while retaining nested VLM defaults.
  • Route CLI and continuous-batch image requests through a filtered host embedding table and resident IREE projector, with no duplicate decoder and no silent host/LLaVA fallback.
  • Preserve Gemma3Processor's exact newline, BOI, image-token, EOI, newline block for both existing placeholders and bare CLI/server prompts, with checked capacity accounting for every wrapper token.
  • Expose the mixed-runtime boundary diagnostic as the standalone xla_gemma3_reference_check example capturing processor pixels, twelve block-0 sub-stages, ordered intermediate/final SigLIP states, post-layernorm, average-pool projection, prepared image rows, one-time sqrt(hidden) scaling, and the exact bidirectional padding mask.
  • Widen BF16 vision_tower.* and multi_modal_projector.* weights to F32 on the MLX reference side of xla_gemma3_reference_check to match IreeVisionProjector's F32 execution contract, resolving the previous BF16 mantissa drift across the 27-block 4096 x 4096 SigLIP encoder without changing tolerances.
  • Configure IREE's diagnostics-only process-global task threading with --task_topology_group_count=1 and --task_worker_stack_size=8388608 (8 MiB, preventing worker.c from clamping 0 to 32 KiB below GPU runtime TLS size).

Validation

  • cargo test -p mlxcel-xla --lib --features iree,diagnostics -- gemma3
  • cargo test -p mlxcel-xla --lib --features iree,diagnostics -- diagnostic_flags
  • cargo test --lib --features rocm,xla-reference-diagnostics -- vlm_gemma_xla_tests
  • cargo test --lib --features rocm,xla-iree -- host_preprocessor (30 passed)
  • cargo fmt --all -- --check
  • cargo clippy --lib --bins --tests -- -D warnings
  • cargo clippy --lib --bins --tests --examples --features rocm,xla-reference-diagnostics -- -D warnings
  • xla_gemma3_reference_check --model models/mlx/gemma-3-4b-it-4bit --image tests/fixtures/test_image.png --device hip: PASS across all stages (processor.pixel_values max_abs=0.0, siglip.hidden.embedding max_abs=7.63e-6, all 12 siglip.block0.* stages max_abs<=5.53e-5, siglip.hidden.block1..26 PASS with 0 failures, siglip.selected.post_layernorm max_abs=2.56e-3, projector.avg_pool_projection max_abs=5.03e-4, prepared.mlx_vs_iree_image_rows max_abs=5.03e-4, prepared.mask.* max_abs=0.0, 0 failures).
  • xla_gemma3_reference_check --model models/mlx/gemma-3-4b-it-4bit --image tests/fixtures/test_image.png --device local-task: PASS across all stages (projector.avg_pool_projection max_abs=7.64e-4, prepared.mask.* max_abs=0.0, 0 failures).
  • E2E 16-token greedy generation parity on models/mlx/gemma-3-4b-it-4bit (tests/fixtures/test_image.png, MLXCEL_XLA_CONTEXT_CAPACITY=512, --device hip): XLA CLI and XLA /v1/chat/completions server match token-for-token ("This is an image of a solid, bright-orange color.", 13 tokens, finish_reason="stop"), and repeated image + follow-up text-only requests on the same server slot verify clean additive prefill mask reset and slot reuse.

Runtime notes

  • Gemma3 image execution requires the xla-iree feature and rejects MLXCEL_XLA_VISION_BACKEND=host explicitly.
  • Text-only Gemma3 stays on the ordinary token-prefill path and retains its pre-existing dense artifact identity.
  • Runtime artifacts are cached outside the repository; no generated CSV or model artifact is committed.

Closes #869

@inureyes inureyes added area:inference Generation, sampling, decoding (incl. speculative, DRY) area:models Model architectures, weights, loading, metadata priority:medium Medium priority status:review Under review type:enhancement New features, capabilities, or significant additions labels Jul 24, 2026
@inureyes
inureyes force-pushed the feature/issue-869-gemma3-vlm-xla branch from 002bb77 to c4e5d22 Compare July 27, 2026 00:22
@inureyes

Copy link
Copy Markdown
Member Author

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

Post-rebase validation:

  • cargo fmt --all -- --check
  • git diff --check
  • cargo test -p mlxcel-xla --lib gemma3_: 8 passed
  • cargo check -p mlxcel-xla --features iree: passed with existing warnings

The shared vision runtime inherited #934’s explicit new_legacy_unqualified artifact path during the rebase; no additional branch-local adaptation commit was needed. The strict SigLIP block-1 numeric failure (8 values, prior max_abs=0.6672516) and continuous-batching gates remain unresolved. With CUDA unavailable on the current host, no fresh actual-checkpoint result is claimed. This PR remains draft and #869 remains blocked by #932.

@inureyes
inureyes force-pushed the feature/issue-869-gemma3-vlm-xla branch from c4e5d22 to 9ab1399 Compare July 27, 2026 04:13
@inureyes

Copy link
Copy Markdown
Member Author

Rebase and bounded SigLIP evidence — 2026-07-27

  • Rebased the feature branch onto origin/main@ec6fbb6d and force-with-lease pushed 9ab13992. The vision conflict adopts the shared numeric_ops LayerNorm/GELU/softmax helpers from main, the feature conflict preserves the CPU-capable xla-micro-oracle, and the diagnostics conflict adopts the shared one-group plus host-default-stack helper from main.
  • The only authorized actual command was env IREE_CUDA_HOME=/home/inureyes/.cache/mlxcel/iree-cuda-3.12.0rc20260721 IREE_CUDA_COMPILE=/home/inureyes/.cache/mlxcel/iree-cuda-3.12.0rc20260721/venv/bin/iree-compile MLXCEL_GEMMA3_REVISION=93724907d4ed1745d2fe50baadf3b0b01a65abf2 RUSTC=/home/inureyes/.rustup/toolchains/1.93.1-aarch64-unknown-linux-gnu/bin/rustc /home/inureyes/.rustup/toolchains/1.93.1-aarch64-unknown-linux-gnu/bin/cargo run --locked --example xla_gemma3_reference_check --features cuda,xla-reference-diagnostics -- --model /home/inureyes/models/gemma-3-4b-it-4bit --image tests/fixtures/test_image.png --device local-task.
  • That current-head actual was stopped at the bounded eight-minute cap before the model runner began. The new Rust 1.93.1 target caused mlxcel-core to classify its MLX cache as stale, purge _deps, and attempt the pinned MLX clone; the sandboxed attempt could not resolve GitHub. After allowing the required fetch, rebuilding pinned MLX revision b7c3dd6d27f45b5365b08a840310187dc503f1db completed and the same current-head example passed cargo check in 7m07s. No second actual or full-model run was started.
  • Therefore there is no new current-head numeric result. The last completed actual remains the documented 002bb77e run: first divergence siglip.hidden.block1.output, flat index 658517, 8 failing values, max absolute difference 0.6672516; exact first failing block 1. This remains a numeric acceptance blocker and was not waived.
  • Focused validation after the rebase: cargo check --locked --features cuda,xla-reference-diagnostics --example xla_gemma3_reference_check passed with existing warnings; cargo test --locked -p mlxcel-xla --lib gemma3 passed 54 with 2 ignored; cargo test --locked -p mlxcel-xla --lib diagnostic_flags::tests passed 2; cargo fmt --all -- --check passed.
  • No tolerance, production graph, CSV, or additional numeric fix was introduced. The PR remains draft; SigLIP intermediate acceptance, final token-exact output, padding/multi-image continuous batching, cancellation, and slot reuse remain open.

@inureyes

Copy link
Copy Markdown
Member Author

TF32 reference policy checked here: immaterial, so the numbers above stand

I filed on #932 that MLX defaults MLX_ENABLE_TF32=1, selecting a 10-bit-mantissa
CUBLAS_COMPUTE_32F_FAST_TF32, while src/lib/mlxcel-xla/README.md declares that mode is
not valid F32 reference evidence. That defect decided the Molmo2 gate in #916 (failed at the
first ViT block under the default, passes the whole gate with it off, 300x at vit.block.0),
so it had to be re-checked here before relying on the numbers above.

Re-run at 9ab13992 with MLX_ENABLE_TF32=0, everything else identical
(local-task, MLX_CUDA_ARCHITECTURES=121, unchanged atol=0.08, rtol=0.04). The result is
unchanged at every stage:

stage TF32 default MLX_ENABLE_TF32=0
siglip.hidden.embedding 4.852448e-1, 0 fail 4.852448e-1, 0 fail
siglip.block0.output 3.646393e-1, 0 fail 3.646393e-1, 0 fail
siglip.hidden.block1.output 6.672516e-1, 8 fail 6.672516e-1, 8 fail
siglip.hidden.block6.output 1.760086, 333 fail 1.760086, 333 fail
siglip.hidden.block20.output 6.806642e1, 489930 fail 6.806642e1, 489930 fail
siglip.hidden.last_pre_layernorm 1.302648e3, 1408110 fail 1.302648e3, 1408110 fail

exact_first_failing_block=1 and first_failure=Some(658517) are identical under both.

This is consistent with the mechanism: the flag only reaches genuine f32 contractions, and
this checkpoint's vision tower weights are BF16, so the SigLIP path never takes the TF32
route. The same check on the Qwen2.5-VL tower in #920 was likewise unchanged, while the two
Molmo gates, which do have f32 paths, both moved.

So unlike #916, the divergence recorded here is a property of the emitted graph rather than
of the reference policy, and the blocker in the PR body is unchanged.

For completeness, this run also reconfirms at current head the numbers the PR body carried
from 002bb77e: block1 8 failures at max_abs=0.6672516 first failure 658517, block2 18,
block3 61, block4 73, block5 133, block6 333, block13 35808, block20 489930,
last_pre_layernorm 1408110 at max_abs=1302.648. Every block-0 substage passes
(layer_norm1, q_proj, k_proj, v_proj, attention_context, attention_output,
attention_residual, layer_norm2, mlp_fc1, mlp_activation, mlp_fc2, output), as do
the processor pixels, the prepared text/image identity and both mask cell checks, all exact.
So the stale-evidence concern for this PR is closed: the recorded numbers are current-head
numbers.

@inureyes
inureyes force-pushed the feature/issue-869-gemma3-vlm-xla branch from 9ab1399 to 63a4cfa Compare October 15, 2026 21:11
@inureyes
inureyes marked this pull request as ready for review October 15, 2026 21:11
Add the Gemma3 VLM OpenXLA execution path with SigLIP 2D average-pool
projection, one-time sqrt(hidden_size) text embedding scaling, and
exact bidirectional image-block plus padding additive prefill masks:

- Emit the Gemma3 SigLIP vision encoder and 2D average-pooling + RMSNorm
  + linear multi_modal_projector in StableHLO without the LLaVA 2-layer
  MLP contract.
- Add the Gemma3 prepared-prefill boundary with one-time text embedding
  scaling, native projector rows, and the authoritative bidirectional
  image-block / padding additive mask for embeddings prefill.
- Bind the prepared-prefill ABI, additive-mask mode/value, post-scale
  policy, wrapper tokens, SigLIP/projector configuration, and Gemma3
  sliding/global attention settings into stable single-sequence and
  batched IREE bundle fingerprints while preserving existing dense
  text-only identities byte-for-byte.
- Route CLI and continuous-batch server image requests through the
  filtered host embedding table and resident IREE vision projector.
- Widen BF16 SigLIP and projector weights to F32 on the MLX reference
  side of xla_gemma3_reference_check to match IreeVisionProjector's F32
  execution contract, and set --task_worker_stack_size=8388608 in the
  diagnostics-only local-task thread helper so IREE worker.c does not
  clamp 0 to 32 KiB below GPU runtime TLS size.

Refs #869
@inureyes
inureyes force-pushed the feature/issue-869-gemma3-vlm-xla branch from 63a4cfa to 49c2b32 Compare October 15, 2026 22:04
@inureyes
inureyes merged commit 94190e1 into main Oct 15, 2026
27 checks passed
@inureyes
inureyes deleted the feature/issue-869-gemma3-vlm-xla branch October 15, 2026 22:35
inureyes added a commit that referenced this pull request Oct 15, 2026
Nightly verify run 38819880080 on main 93748aa failed `make verify-clippy` (`--workspace --all-targets -- -D warnings`) on code added by #917, while its test and video steps passed:

- `Gemma3VlmCompatibilityContract`, its `new`/`stable_identity`, and `bind_gemma3_vlm_compatibility` (`prepared_gemma3.rs`) are only called from `iree.rs`, so they are dead without the `iree` feature. They now carry `#[cfg_attr(not(feature = "iree"), allow(dead_code))]`, the attribute `lib.rs` already uses for `prepared`.
- Four `1 * 4 + col` / `1 * 8 + col` mask indices in the Gemma3 export test tripped `identity_op`. The test allows that lint so the indices keep their `row * width + col` form.
- `mod gemma3_vlm_mask_tests` in `emitter/model.rs` sat before the MoE probe emitters (`items_after_test_module`); it now ends the file, unchanged.

No behavior change. `cargo clippy -p mlxcel-xla --all-targets -- -D warnings`, `cargo clippy --workspace --all-targets --features cuda -- -D warnings` and fmt are clean, and the mlxcel-xla lib tests pass (308 passed). The `iree` feature build needs an IREE install that this host lacks; the attribute is a no-op there.

Refs #917
inureyes pushed a commit that referenced this pull request Nov 15, 2026
…config (#2986)

## Summary

The pinned Gemma 3 eager-MLX-versus-IREE boundary gate (`xla_gemma3_reference_check`, the #869 gate) fails on `main` at `siglip.hidden.block4.output`. Its eager reference builds the SigLIP tower on the erf GELU, while the loader and the OpenXLA graph have run the tanh GELU for this checkpoint since #2552. This moves the loader's config parse into one function that the loader and the gate both call. The gate then passes all 34 stages.

## Related issues

Closes #2985.

## Type of change

- [x] `fix` — bug fix

## Cause

`run_gemma3_eager_mlx_iree_prepared_boundary` parsed the pinned config with `serde_json::from_value::<VLMConfig>` and built `SigLipVisionModel` from it. The pinned `config.json` has no `vision_config.hidden_act`, so the field stayed the serde default, `VisionHiddenActivation::ExactGelu`. #2552 resolved an omitted key to the tanh GELU in `load_gemma3_vlm` (`default_missing_hidden_act_to_siglip`) and in the OpenXLA vision config; the gate's own parse dates from #917 and was not part of that change. The gate has compared an erf tower with a tanh graph since.

## Change

- `parse_gemma3_vlm_config` in `src/loading/vlm_gemma.rs`: the `VLMConfig` parse and the `default_missing_hidden_act_to_siglip` call that `load_gemma3_vlm` had inline, as one function. `load_gemma3_vlm` calls it. Generation does not change.
- The gate calls the same function instead of parsing `VLMConfig` itself, so its reference is the tower the loader builds and cannot drift from it again.
- Two unit tests in `src/loading/vlm_gemma_tests.rs`, which run in the default suite and need no checkpoint: an omitted or null `hidden_act` resolves to tanh while the direct parse stays erf, a declared name is kept, and a parse error keeps the loader's message.
- Not changed: the gate's tolerances, stages and pinned hashes. `load_gemma3_iree_host_preprocessor` also parses `VLMConfig` directly, but it builds no host tower and never reads `hidden_act`, so it is left as it is.

## Before / after

GB10 (sm_121, CUDA 13.0), IREE `3.12.0rc20260721` from `scripts/iree/setup-cuda.sh`, `mlx-community/gemma-3-4b-it-4bit` @ `93724907d4ed`. `main` is `ce6855bc8`. Same command on both:

```bash
cargo run --locked --profile test-fast --features cuda,xla-reference-diagnostics \
  --example xla_gemma3_reference_check -- \
  --model models/gemma-3-4b-it-4bit --image tests/fixtures/test_image.png --device local-task
```

| | `main` | This PR |
|---|---|---|
| Exit code | 101 | 0 |
| Stage lines PASS / FAIL | 23 / 11 | 34 / 0 |
| Last line | `first divergence: siglip.hidden.block4.output at flat index 61889` | `PASS all pinned Gemma3 eager MLX/IREE boundary stages` |

`max_abs` of the IREE output against the eager MLX reference:

| Stage | `main` | This PR |
|---|---|---|
| `siglip.block0.mlp_fc1` | 3.058e-5 | 3.058e-5 |
| `siglip.block0.mlp_activation` | 4.766e-4 | 1.274e-5 |
| `siglip.block0.output` | 2.270e-2 | 1.669e-5 |
| `siglip.hidden.block4.output` | 1.067e-1, FAIL | 7.629e-4 |
| `siglip.hidden.block20.output` | 5.604, FAIL | 1.000e-2 |
| `siglip.hidden.last_pre_layernorm` | 343.3, FAIL | 0.2395 |
| `projector.avg_pool_projection` | 0.4582, FAIL | 4.331e-4 |

Every stage up to `mlp_fc1` reads the same on both sides of the change. The first one that moves is the activation, by 4.766e-4 on `main`; the largest difference between the erf and the tanh GELU is 4.732e-4 (at |x| = 2.70). The stage lines are the same, on both sides, with `--features xla-diagnostics,xla-reference-diagnostics`.

Generation, to confirm that the loader refactor moves nothing. `generate --image <fixture> -p "Describe the image." -n 48 --temp 0`, release builds of `ce6855bc8` and of this PR:

| Checkpoint | Fixtures | `main` against this PR |
|---|---|---|
| `mlx-community/gemma-3-4b-it-4bit`, no `hidden_act` | `test_image_shapes.png`, `test_image.png` | identical replies |
| A copy of it whose config declares `"hidden_act": "gelu"` | the same two | identical replies |

The two checkpoints answer differently from each other on both fixtures, in both builds, so a declared key is still read.

## Test plan

Run on this PR's commit (`752e7ad4d`, one commit on `ce6855bc8`) on a DGX Spark (GB10).

- [x] `cargo fmt --all -- --check`
- [x] `cargo clippy --workspace --all-targets --features cuda -- -D warnings` (the Linux spelling of the template's line)
- [x] `cargo build --release --features cuda`
- [x] The gate, as in the tables above: exit 101 on `main`, exit 0 with 34 of 34 stages on this PR. Its retained libtest wrapper passes as well (`MLXCEL_GEMMA3_FIXTURE=<checkpoint> cargo test --profile test-fast --features xla-diagnostics,xla-reference-diagnostics --lib pinned_gemma3_eager_mlx_matches_iree_prepared_boundary -- --include-ignored`)
- [x] `cargo test --profile test-fast --features xla-diagnostics,xla-reference-diagnostics --lib reference_boundary -- --test-threads=1`: 11 passed, which are the 10 unit tests of the gate module and one audio test whose name the filter also matches
- [x] `cargo test --profile test-fast --features cuda --lib loading::vlm::gemma -- --test-threads=1`: 18 passed, the two new tests among them. With the resolution removed from `parse_gemma3_vlm_config`, `gemma3_vlm_config_resolves_an_omitted_hidden_act_to_the_siglip_tanh_gelu` fails (`left: ExactGelu`, `right: GeluPytorchTanh`)
- [x] `make verify-test-cuda` (`cargo test --workspace --profile test-fast --features cuda --no-fail-fast -- --test-threads=1`): 186 of 187 test binaries pass (15488 tests passed, 1 failed, 496 ignored). The one failure is `native_env_tests::the_cuda_cache_defaults_reach_mlx`, which fails the same way on a clean `main` (it is order-dependent; described in the notes of #2967)
- [x] The self-hosted `ci.yml` jobs a pull request from a fork does not get, run by hand: `clippy` (`cargo clippy -p mlxcel --lib --tests -- -D warnings`, default features), `cpu-link` (both commands; 13 tests passed), `xla-compile` (`cargo check --features cuda,xla-iree --all-targets`, `cargo check --no-default-features --features xla-diagnostics --all-targets`): all pass
- [x] `cargo check --features xla-diagnostics,xla-reference-diagnostics --all-targets`, the feature set that compiles the gate: passes
- [ ] `cargo clippy -p mlxcel --lib --tests --example xla_gemma3_reference_check --features xla-diagnostics,xla-reference-diagnostics -- -D warnings`: the lib test target stops at one finding, `field_reassign_with_default` in `src/server/batch/xla_worker_tests.rs:1417`. A clean `main` stops at the same single finding, and it is not in a file this PR touches
- [x] `python3 -m unittest discover -s tests -p 'test_*.py'` (the command of `make verify-python-tooling`), `scripts/insert_apache_header.py --check`, `scripts/ci/check_cross_repo_refs.py`: 219 Python tests OK, license headers OK, cross-repo refs OK
- [x] Validated with a real checkpoint: the gate and the replies above, `mlx-community/gemma-3-4b-it-4bit`
- [ ] Traced per "Judging a change that moves the numbers": not applicable. Generation does not move (identical replies); what moves is the gate's reference, on purpose
- [ ] `cargo deny check`: not run and not applicable (no manifest, lockfile or `deny.toml` change)
- [ ] Metal: not built or run here. The gate's example needs CUDA; the new unit tests are backend-neutral and first run on Metal in the nightly `make verify`

## Notes for reviewers

- **CI does not build this gate.** `reference_boundary` is compiled only with `xla-reference-diagnostics`, which no workflow turns on, and running it needs the pinned checkpoint. That is why the failure went unreported, and it is why I ran the gate by hand here. This PR does not add a job for it.
- **The unit tests pin the function, not the gate.** They fail if the resolution is removed from `parse_gemma3_vlm_config`. The gate itself is covered only by running it, which is the table above.
- **"Since #2552" is read from the diff.** #2552 changed the loader and the OpenXLA vision config and did not touch `vlm_gemma_xla_tests.rs`. I did not run the gate on an older commit.
- **The other reference gates were not run** (`xla_molmo_reference_check`, `xla_llava_reference_check`, `xla_youtu_vl_reference_check`): I do not have their checkpoints on this host.
- This is the gate failure that the description of #2967 records as the behaviour of `main` on this host.

## Checklist

- [x] PR title uses a Conventional Commits prefix
- [x] One logical change per PR
- [ ] Updated `docs/`: no user-facing behavior or supported-model change
- [x] Updated `// Used by: ...` comments: `parse_gemma3_vlm_config` is new and carries one
- [x] No secrets, credentials, or `.env` files committed
@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:medium Medium priority status:review Under review type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(xla): support Gemma3 VLM additive prefill masks

1 participant