Skip to content

feat(xla): support Molmo sparse additive visual embeddings (#870) - #918

Merged
inureyes merged 1 commit into
mainfrom
feature/issue-870-molmo-xla
Oct 16, 2026
Merged

inureyes merged 1 commit into
mainfrom
feature/issue-870-molmo-xla

Conversation

@inureyes

@inureyes inureyes commented Jul 24, 2026 •

Copy link
Copy Markdown
Member

Summary

Implements Molmo v1 (MolmoVLM / model_type: "molmo") sparse additive visual embeddings on the OpenXLA / IREE execution path:

  • Emits the Molmo v1 dual-layer CLIP ViT (selected_layers = [-2, -9], indices 21 and 14 of 23 layers), 2x2 attention pooling (image_pooling_2d), and SwiGLU MLP (image_projector) in mlxcel-xla, along with intermediate diagnostic boundaries (patch_embedding, selected_layer_21, selected_layer_14, projector).
  • Implements MolmoSparseAddPlan in mlxcel-xla::prepared_molmo to validate and apply sparse additive visual features (target = round_bf16(text + round_bf16(projected))) indexed by image_input_idx while preserving sentinel (< 0) skips and rejecting duplicate or out-of-range indices.
  • Maps Molmo v1 fused OLMo decoder weights (language_model.model.wte.embedding, att_proj, ff_proj value-then-gate SwiGLU halves, ff_out), enables f16 resident row-sliced projections for WeightScheme::Molmo, and defaults rope_impl to "llama" (non-interleaved rotate-half) unless "interleave" is explicitly configured.
  • Streams decoder weights shard-by-shard into IREE device buffers via xla_llama_upload_weight so 7B checkpoints do not double-materialize all dequantized weights in host RAM during load.
  • Adds xla_molmo_reference_check for actual-checkpoint boundary verification across local-task and GPU (hip / cuda) backends.

Verification

  • Unit tests:
    • cargo test -p mlxcel-xla --lib (323 passed; 0 failed)
    • cargo test --lib multimodal --features rocm,xla-reference-diagnostics
  • Actual-checkpoint boundary gate (xla_molmo_reference_check on mlx-community/Molmo-7B-D-0924-4bit revision 5c04b3a418979597b1968e41414ad799c87533e8, tests/fixtures/test_image.png):
    • MLXCEL_MOLMO_IREE_DEVICE=local-task: all 14 stages PASS with failures=0 (vision.patch_embedding max_abs=1.336575e-3, vision.selected_layer_21 max_abs=2.002304e0, vision.selected_layer_14 max_abs=2.016567e0, vision.projector max_abs=3.934250e-1, prepared.non_visual_rows max_abs=0.0, prepared.sparse_add_visual_rows max_abs=3.750000e-1, decoder.layer0_kv max_abs=0.0, decoder.all_layer_kv max_abs=4.089439e-2, decoder.prefill_logits max_abs=1.099339e-1).
    • MLXCEL_MOLMO_IREE_DEVICE=hip (gfx1151, AMD Radeon 8060S): all 14 stages PASS with failures=0 (vision.patch_embedding max_abs=1.336575e-3, vision.selected_layer_21 max_abs=2.002304e0, vision.selected_layer_14 max_abs=2.016567e0, vision.projector max_abs=3.934250e-1, prepared.non_visual_rows max_abs=0.0, prepared.sparse_add_visual_rows max_abs=3.750000e-1, decoder.layer0_kv max_abs=0.0, decoder.all_layer_kv max_abs=3.109646e-2, decoder.prefill_logits max_abs=6.121254e-2).
  • End-to-end /v1/chat/completions 16-token greedy parity on gfx1151 (MLXCEL_BACKEND=xla MLXCEL_XLA_DEVICE=hip MLXCEL_XLA_CONTEXT_CAPACITY=512 across 2 sequential image requests vs MLX reference serve):
    • Both MLX and OpenXLA (hip, Requests 1 and 2) produce exact 16-token greedy match: "A vibrant, solid orange square dominates the image, filling the entire frame with its".

Closes #870

@inureyes inureyes added area:inference Generation, sampling, decoding (incl. speculative, DRY) area:models Model architectures, weights, loading, metadata priority:low Low priority status:review Under review type:enhancement New features, capabilities, or significant additions labels Jul 24, 2026
@inureyes
inureyes force-pushed the feature/issue-870-molmo-xla branch from ac54a07 to 2c6c9d4 Compare July 24, 2026 10:22
@inureyes

Copy link
Copy Markdown
Member Author

Bounded actual-checkpoint follow-up on commit 6481443: all pinned processor boundaries passed exactly (677,376 patch values, 1,152 mask values, image token IDs, sparse image_input_idx, and grid metadata). The staged eager capture then materialized the patch embedding successfully and entered selected ViT layer 14. That named stage produced no completion marker within the five-minute no-output limit and was interrupted once with exit 130. The CPU run will not be repeated unchanged; the remaining numeric oracle requires a small GPU eager diagnostic runner or a cached/staged equivalent. No parity result is claimed, and the PR remains draft.

@inureyes

Copy link
Copy Markdown
Member Author

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

Post-rebase validation:

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

The Molmo runtime now uses the explicit new_legacy_unqualified auxiliary-artifact path. The prior real-checkpoint run never completed its boundary report, and independent token-exact/KV/greedy acceptance remains absent. CUDA is currently unavailable on this host, so no new actual result is claimed. This PR remains draft and #870 remains blocked by #932.

@inureyes
inureyes force-pushed the feature/issue-870-molmo-xla branch from d20b06e to a4047b2 Compare July 27, 2026 04:09
@inureyes

Copy link
Copy Markdown
Member Author

Rebased #918 onto origin/main@ec6fbb6d and pushed a4047b22. The only conflicts were narrow unions of the merged numeric-oracle foundation with the Molmo module and reference-diagnostics registrations.

The actual-run assets are present and pinned: the 5.0 GB checkpoint, image and config hashes, GB10 CUDA device, and local-task IREE distribution all match. The local fixture lacks Hugging Face metadata, so the runner documentation now supplies its already-supported pinned revision environment value.

One sm_121a release build reached the final GNU root build/link but exceeded the five-minute bound, was interrupted once with exit 130, and produced no executable. This host has neither lld nor mold; no identical retry or speculative build change was attempted. Consequently no actual checkpoint comparison ran.

Validation completed: default mlxcel-xla Clippy, Molmo 15/15, F16 conversion 4/4, formatting, and diff checks. The PR remains draft; intermediate, KV/logit, token-exact, and lifecycle acceptance are still required.

@inureyes

Copy link
Copy Markdown
Member Author

Additional bounded linker audit after the rebase evidence:

  • /usr/bin/ld.gold is present even though lld/mold are not.
  • A target-linker override and a final-example cargo rustc override were each attempted once. Both stopped in about 15 seconds, before final link or model execution, because changing the linker invalidated Cargo fingerprints; mlxcel-core then saw cached=none, purged that new build output's MLX _deps, and the sandbox could not resolve the pinned MLX clone.
  • No executable was produced, no checkpoint comparison ran, and no repository file changed. The temporary linker wrapper was removed.

This does not alter the qualification result: #918 remains draft/fail-closed pending a reproducible cached release runner and the original intermediate/KV/token/lifecycle gates.

Refs #870
Refs #932

@inureyes

Copy link
Copy Markdown
Member Author

First completed actual for this gate, at a954d214

The pinned 5.0 GB checkpoint gate has now run end to end on the GB10 host
(driver 580.159.03, CUDA 13.0, IREE 3.12.0rc20260721, Rust 1.93.1, MLX pin
b7c3dd6d27f4). Two separate things were blocking it, one environmental and one a
real defect on this branch.

1. The release build was never actually failing

cargo build --locked --release --example xla_molmo_reference_check --features cuda,xla-reference-diagnostics completes in 10 minutes 34 seconds from a cold
MLX CUDA tree. The earlier interruption at five minutes was a budget that was too
short for a from-scratch MLX CUDA build plus the GNU root link, not a linker or
toolchain problem. No lld or mold is needed. The incremental rebuild after the
code fix below took 2 minutes 52 seconds.

One prerequisite: this host needs MLX_CUDA_ARCHITECTURES=121a exported before the
build. src/lib/mlxcel-core/build.rs resolves the architecture as
MLX_CUDA_ARCHITECTURES else detect_cuda_arch() else the literal "90a", and
detect_cuda_arch() shells out to nvidia-smi. Where the GPU is not exposed to the
build, it silently produces 90a binaries that cannot launch on sm_121, failing later
with invalid resource handle or no kernel image is available for execution on the device. That is a build-environment failure and is recorded separately from numerics.

2. Real defect: the #945 local-task configuration was never applied here

The runner created its production IREE preprocessor without applying the
diagnostics-only local-task thread configuration. configure_diagnostic_local_task_threads
had no callers on this branch, while the Gemma3 runner already applies it before its
first IREE instance. The gate therefore aborted before any comparison:

xla_aux_create failed (status 13):
src/runtime/src/iree/base/threading/thread_pthreads.c:159: INTERNAL; thread creation failed with 22

followed by Destroy(handle_) failed: driver shutting down and SIGABRT (exit 134).
a954d214 calls it immediately before load_iree. IREE parses its process-global flag
registry when the first instance is created, so the ordering is load-bearing.

Result

MLXCEL_DEVICE=gpu, MLXCEL_MOLMO_FIXTURE=/home/inureyes/models/molmo-7b,
MLXCEL_MOLMO_REVISION=5c04b3a418979597b1968e41414ad799c87533e8,
MLXCEL_MOLMO_IMAGE=tests/fixtures/test_image.png, unchanged tolerances
atol=0.25, rtol=0.05, no override.

stage status elements max_abs failures
processor.patches PASS 677376 0.0 exact 0
processor.patch_masks PASS 1152 0.0 exact 0
processor.image_token_ids PASS 316 0
processor.image_input_idx PASS 288 0
processor.grid PASS 3 0
vision.patch_embedding PASS 1179648 1.336575e-3 0
vision.selected_layer_14 PASS 1181696 2.258102 0
vision.selected_layer_21 FAIL 1181696 2.317841 4
vision.projector PASS 1032192 2.251205e-1 0
prepared.non_visual_rows PASS 132608 0.0 exact (atol=0, rtol=0) 0
prepared.sparse_add_visual_rows PASS 1032192 2.500000e-1 0
decoder.layer0_kv PASS 128 0.0 exact 0
decoder.all_layer_kv PASS 3584 5.212402e-2 0
decoder.prefill_logits PASS 152064 1.176004e-1 0

Exit 101 is the intended first-divergence panic on the single failing stage.

Four values out of 1,181,696, and the divergence does not propagate: the projector that
consumes the ViT output, the authoritative sparse-add merge, all-layer KV and the prefill
logits all pass downstream of it. elements=1181696 is 2 crops times 577 tokens times
1024 hidden, so flat index 514613 is crop 0, token 502, channel 565.

The 4 values are deterministic, and the gate is cross-device by construction

Re-running with MLXCEL_MOLMO_IREE_DEVICE=local-sync, which is single-threaded and
deterministic, reproduces the failure identically: same max_abs=2.317841, same
max_rel=5.661761e3, same 4 failures, same first_failure=514613. So this is not a
local-task worker or reduction-order artifact.

MLXCEL_MOLMO_IREE_DEVICE=cuda is rejected by the gate itself
(the #870 reference gate requires IREE local-task or local-sync), so the comparison is
by design MLX on CUDA against IREE on CPU. The two selected layers straddle the threshold
narrowly under atol + rtol*|expected|:

  • selected_layer_14 max difference 2.258102 passes, its worst element sitting where
    |expected| is at least about 40.2
  • selected_layer_21 max difference 2.317841 fails, its worst element sitting where
    |expected| is below about 41.4

Both layers differ by roughly the same amount; layer 21's worst element simply lands at a
slightly smaller |expected|. That looks like the residual of a GPU reference against a
CPU candidate rather than a semantic mismatch, especially since every downstream production
stage including the prefill logits passes. Deciding it properly needs the comparison to run
with both sides on the same device, which this gate currently forbids.

No tolerance was changed and no production arithmetic was touched. Greedy token exactness,
CLI and server paths, cancellation and slot reuse, and mixed batching were not reached
because the strict first-divergence panic stands. This PR stays draft.

@inureyes

Copy link
Copy Markdown
Member Author

Correction to the numbers above: the reference was TF32, not F32

The results I posted earlier were collected with MLX's default MLX_ENABLE_TF32=1, which
selects CUBLAS_COMPUTE_32F_FAST_TF32 (10-bit mantissa) for f32 contractions.
src/lib/mlxcel-xla/README.md declares that mode is not valid F32 reference evidence. The
gate does not set the variable and neither did I, so those numbers compared a TF32 MLX
reference against a true-F32 IREE candidate. Re-running at a954d214 with
MLX_ENABLE_TF32=0, everything else identical:

stage TF32 default MLX_ENABLE_TF32=0
vision.patch_embedding 1.336575e-3, 0 fail 1.336575e-3, 0 fail
vision.selected_layer_14 2.258102, 0 fail 1.991226, 0 fail
vision.selected_layer_21 2.317841, 4 fail 2.046043, 4 fail
vision.projector 2.251205e-1, 0 fail 1.643753e-1, 0 fail
prepared.sparse_add_visual_rows 2.500000e-1, 0 fail 1.875000e-1, 0 fail
decoder.all_layer_kv 5.212402e-2, 0 fail 5.070114e-2, 0 fail
decoder.prefill_logits 1.176004e-1, 0 fail 1.173029e-1, 0 fail

True F32 removes about 12 percent of the drift at both selected ViT layers and 25 to 27
percent at the projector and the sparse-add merge. The patch embedding is unchanged, which
matches mlx/backend/cuda/conv.cpp:139 gating the convolution path on enable_tf32()
separately.

It does not close the gate. The same four elements at flat index 514613 still exceed
atol=0.25, rtol=0.05, and every other stage still passes. So the residual at
vision.selected_layer_21 is now attributable to the graph rather than to the reference
policy, which is a cleaner statement of the remaining blocker than the earlier numbers
supported.

Two further observations on that residual, both from runs at this head:

  • It is device independent. local-task, local-sync and cuda all produce 4 failures at
    the same flat index 514613 with max_abs 2.317841, 2.317841 and 2.316116 respectively
    under the TF32 default. IREE agrees with itself across CPU and GPU, so the variation is not
    an IREE backend or reduction-order artifact.
  • It is not a precision-policy mismatch of the kind seen in the Qwen families. This
    checkpoint has torch_dtype: float32 with an unquantized vision tower
    (skip_vision_non_divisible: true), and the Molmo emitter applies no Precision demotion,
    so both sides are plain f32 by construction.

MLXCEL_MOLMO_IREE_DEVICE=cuda currently trips the gate's own assertion at line 122. I
tested it by widening that assertion locally and reverted the change, since it fixes nothing;
the result is recorded above only as evidence that the residual is device independent.

Filed the reference-policy issue and the two build.rs architecture defects on #932.
This PR stays draft.

@inureyes

Copy link
Copy Markdown
Member Author

Reopening to retrigger CI. The red cargo-fmt on this PR is not a formatting problem: its last run (2026-07-27) used a merge ref against a main that briefly carried dtolnay/[email protected], a nonexistent Rust release dependabot produced by treating the action tag as an action version (bdad2328, PR #146). The job died at rustup toolchain install 1.100.0 ... 404 before it ever formatted anything. Reverted the next day in #954, which also added the dtolnay/rust-toolchain ignore to .github/dependabot.yml, and the pin is 1.97.1 now. Checked this branch against the current rustfmt: cargo fmt --all --check is clean, so a fresh run should be green. No content change here.

@inureyes inureyes closed this Aug 18, 2026
@inureyes inureyes reopened this Aug 18, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Correction to my previous comment: this red cannot be cleared by re-running, and I have now measured why.

gh run rerun --failed replays the workflow file recorded with the original run, not a freshly computed merge ref. The replay I just triggered logs Run dtolnay/[email protected] verbatim and dies at the same 404, so the red is pinned to that run for as long as the run is the latest one. Reopening the PR does not dispatch a new run either.

Only a push to the branch (a synchronize event) produces a merge ref against current main, and merging origin/main into this branch conflicts today, src/multimodal/host_preprocessor.rs among others, after three weeks of drift. That is this PR's own rebase work rather than a CI fix, so I am leaving it.

The useful part for whoever picks the branch up: there is nothing to fix in the formatting. cargo fmt --all --check on this branch under the current pinned rustfmt (1.97.1) is clean. The red is an artifact of the roughly one-day window on 2026-07-27 when main carried dtolnay/[email protected], a Rust release that does not exist, from dependabot treating the action tag as an action version (bdad2328, PR #146). It was reverted the next day in #954, which also added the dtolnay/rust-toolchain ignore to .github/dependabot.yml. Rebasing this branch for its own sake will take the red with it.

@inureyes
inureyes force-pushed the feature/issue-870-molmo-xla branch from a954d21 to fa3e1d8 Compare October 16, 2026 01:29
@inureyes inureyes changed the title feat(xla): support Molmo sparse additive visual embeddings feat(xla): support Molmo sparse additive visual embeddings (#870) Oct 16, 2026
@inureyes
inureyes marked this pull request as ready for review October 16, 2026 01:29
Wire Molmo v1 (`MolmoVLM` / `model_type: "molmo"`) sparse additive visual embeddings through the OpenXLA / IREE path:

- Emit the Molmo v1 dual-layer CLIP ViT (`selected_layers = [-2, -9]`), 2x2 attention pooling, and SwiGLU MLP projector in `mlxcel-xla`, plus diagnostic outputs for patch embedding, selected layers 21 and 14, and projector output.
- Implement `MolmoSparseAddPlan` to validate and apply sparse additive visual features (`target = round_bf16(text + round_bf16(projected))`) indexed by `image_input_idx` while preserving sentinel (`< 0`) skips.
- Map Molmo v1 fused OLMo decoder weights (`wte`, `att_proj`, `ff_proj` value-then-gate SwiGLU halves, `ff_out`), enable `f16` resident row-sliced projections on `WeightScheme::Molmo`, and default `rope_impl` to `"llama"` (non-interleaved rotate-half) unless `"interleave"` is explicitly set.
- Stream decoder weights shard-by-shard into IREE device buffers via `xla_llama_upload_weight` so 7B checkpoints do not double-materialize all weights in host RAM during load.
- Add `xla_molmo_reference_check` actual-checkpoint boundary verification across `local-task` and GPU (`hip` / `cuda`) backends.

Refs #870
@inureyes
inureyes force-pushed the feature/issue-870-molmo-xla branch from fa3e1d8 to 641d5e2 Compare October 16, 2026 02:08
@inureyes
inureyes merged commit 3ba57b3 into main Oct 16, 2026
27 checks passed
@inureyes
inureyes deleted the feature/issue-870-molmo-xla branch October 16, 2026 03:06
inureyes added a commit that referenced this pull request Oct 17, 2026
…loop (#2436)

Closes #2420

The `xla-iree` serve loop never sent `GenerateEvent::Prefill` and reported the logical (placeholder) prompt length, so a media body's `usage`, `/v1/messages/count_tokens` and the streaming `message_start` that #2415 holds for the prefill report all carried the placeholder count. This makes the loop match the batch scheduler and `docs/llama-server-compat.md`.

## Changes

- `ServeState` keeps one count, `effective_prefill_len` (the expanded prepared length for media, the prompt length for text), and a `prefill_reported` flag. `ServeState::report_prefill` sends `PrefillStats { prompt_tokens, cached_tokens: 0, processed, first_token: true, prompt_ms }` once, before the first `Token` or before `Done` when the engine finishes with no token (withheld EOS), and stamps the decode state's first-token instant as `sequence.rs` does.
- `Done`, the stop-string finish and the zero-budget media finish report the expanded length. The count route follows, since the XLA worker answers it with a one-token generation.
- Every XLA image family goes through `handle_preprocessed`, including the new Molmo (#918) and Youtu-VL (#919) producers, so they are covered too. So are the DeepStack (Qwen3-VL) and Phi4MM audio/image paths. The disaggregated coordinator stays out of scope, as the issue says.
- No doc change: `docs/llama-server-compat.md` has no XLA-specific statement, and its general promise now holds on this loop.

## Tests

The new and updated tests drive the real `admit`, preprocessing and `dispatch` path with a fake engine: text gets `Prefill(2)`, the image gets `Prefill(5)`, and Phi4MM audio and image each get `Prefill(6)`, every one sent before its `Token`, with `Done` reporting the same length. They also cover zero-budget image and audio, and a bare EOS finish. The fake Phi4MM producer now expands placeholders. Two existing assertions in this module were already failing on main because the error messages had changed (`structured` is now `constrained decoding`, and `refusing text fallback` is now `image resolution cardinality mismatch`). I updated them so the module runs green.

- Fix: `server::batch::xla_worker`, 15 passed (`--release --features cuda,xla-iree`, `--test-threads=1`, under gpu-lock).
- Revert check: with the production files restored to main, 9 failed. That is the 7 new or updated tests plus the 2 stale assertions.
- `cargo clippy --release --features cuda,xla-iree --lib --tests -- -D warnings`, `cargo check --release --features cuda,xla-iree --all-targets`, `cargo fmt --check` and the repository check scripts pass.

## Real checkpoint

`~/models/mlx/gemma-3-4b-it-4bit`, `MLXCEL_BACKEND=xla MLXCEL_XLA_DEVICE=cuda MLXCEL_XLA_CONTEXT_CAPACITY=512 mlxcel-server` on the GB10 (the default 256 capacity refuses a Gemma 3 image). I sent one body (`tests/fixtures/test_image.png` plus a short prompt) to `count_tokens`, non-streaming and streaming `/v1/messages`:

| Body | Build | count_tokens | usage.input_tokens | message_start.input_tokens |
|---|---|---|---|---|
| image | main cadc636, XLA | 18 | 18 | 18 |
| image | this PR, XLA | 277 | 277 | 277 |
| image | this PR, MLX path | 277 | 277 | 277 |
| text | both builds, XLA | 17 | 17 | 17 |

In every stream `message_start` was the first event, and it was sent once. Phi4MM audio was not run on a real checkpoint (none is present locally), so the fake-producer test covers it.
@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: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 Molmo sparse additive visual embeddings

1 participant