Skip to content

perf(cuda): fuse the f32 tanh GELU into one bit-exact kernel (#2780) - #2967

Merged
inureyes merged 2 commits into
lablup:mainfrom
Jaeyeong-CHOI:perf/2780-cuda-gelu-tanh-kernel
Nov 15, 2026
Merged

inureyes merged 2 commits into
lablup:mainfrom
Jaeyeong-CHOI:perf/2780-cuda-gelu-tanh-kernel

Conversation

@Jaeyeong-CHOI

@Jaeyeong-CHOI Jaeyeong-CHOI commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds the CUDA port of the fused gelu_tanh_f32 kernel that #2858 landed for Metal. On CUDA the f32 tanh GELU was a compile_shapeless region that MLX's CUDA compile backend splits into a cube module and a tail module (TanhF32Compiled, at least two launches per call) or the eager chain (TanhF32, about eleven); both are now one cuda_kernel launch. The body is written so that NVRTC cannot contract its multiply-add, and it returns the eager chain's bits on every lane measured, so nothing downstream moves and the bit-for-bit fold pin stays as it is.

Related issues

Closes #2780.

Type of change

  • perf — performance improvement (before/after numbers below)

Design

  • The port (src/lib/mlxcelverse/kernels/gelu_tanh_f32.cpp): a GELU_TANH_F32_CUDA_SOURCE body with the formula and op order of gelu_tanh_approx, a GeluTanhF32KernelHolderCuda (std::call_once, as fused_norm.cpp), and .cuda in gelu_tanh_f32_ports(). MLX's CUDA launcher rounds the grid up to whole blocks (mlx/backend/cuda/custom_kernel.cpp:339-340 at the pin: dim3 grid((gx + tx - 1) / tx, …)), so the body returns on lanes at or past x_shape[0], which it reads as a launch argument: the JIT cache key stays the dtype alone, one module and one PTX disk-cache entry per dtype, name custom_kernel_mlxcel_fused_gelu_tanh_f32…, far inside the NAME_MAX window from investigate: gelu_approx computes erf GELU where upstream models use the tanh approximation #2423.
  • No contraction. Every multiply and add in the CUDA body is __fmul_rn / __fadd_rn, which NVRTC never merges into a fused multiply-add. A plain-operator body compiles x + 0.044715 * x3 to one FFMA and then differs from the eager chain on about four f32 lanes in a thousand (see "Why the bits match").
  • Routing. TanhF32Compiled takes the kernel wherever fused_gelu_tanh_f32_available() is true, as perf(metal): fuse the tanh-GELU f32 chain into one kernel #2858 set up; that is now Metal and CUDA. TanhF32 takes it where the port returns the eager helper's bits: a new predicate fused_gelu_tanh_f32_matches_eager_bits() reads a second KernelPorts table that lists the CUDA port only, so the question goes through has_kernel_port like every other port question and no backend is compared by hand (make verify-kernel-port-dispatch passes). On Metal, ROCm and the CPU device TanhF32 is the eager helper, unchanged; perf(metal): fuse the tanh-GELU f32 chain into one kernel #2858's decision for Metal stands, because the Metal body may contract.
  • Checker pins: scripts/ci/check_kernel_dtype_keys.py EXPECTED_IN_SCOPE gains the file (it now launches a cuda_kernel), and its self-test's pinned launcher count goes 9 → 10.

Acceptance criteria (issue #2780)

# Criterion Status
1 TanhF32 and TanhF32Compiled run as one kernel launch on CUDA, f32 inside, input dtype out; Metal/CPU unchanged Met. Fresh PTX cache: each variant leaves one custom_kernel_mlxcel_fused_gelu_tanh_f32_<dtype> module with one kernel per dtype; before, TanhF32Compiled left a cube module plus a tail module per dtype and TanhF32 left nothing (eager AOT chain). Metal and CPU-device dispatch untouched.
2 Erf path inspected and recorded; follow-up issue if it is more than one kernel Inspected and recorded (record, "Erf arm considered"): gelu_approx is an eager six-op chain, about six launches per call. The follow-up issue this criterion asks for is drafted at the end of this description and is not filed yet.
3 Gemma 3 and Gemma 4 image prefill within the null floor of erf, GB10 not a CI runner, arms rotated, a null arm per arm, host gate before every arm Met on both: the paired tanh - erf range overlaps every null range, with tanh at or below erf (Gemma 3 -20.4 ms, Gemma 4 -10.9 ms; null floor about 27 ms and 23 ms). Schedule of engine_bench_rounds.py --null-every-arm --hostgate, 8 rounds, a null arm for each arm. Recorded as a standalone file rather than a new section of gelu-erf-vs-tanh-2026-10-23.md, which #2949 retired into versions/v0.8.0.md.
4 :87 becomes a tolerance test; :197 stays bit-exact; new test on the sweep, the tower input and an empty input Met in the stricter direction: :87 did not need to relax. It is unchanged and passes through the kernel on CUDA. New: bit-identity test (sweep, block-boundary sizes, tower input, f32/bf16/f16), sweep tolerance test for ports that make no bit claim, CPU-device dispatch test. Empty input was already covered by empty_input_takes_the_same_route_on_both_paths, which now runs on CUDA.
5 tests/cuda_custom_kernel_disk_cache.rs runs the kernel in a second process with zero NVRTC compiles Met.
6 StableHLO twins re-checked; greedy 32-token image replies unchanged on the five checkpoints Greedy replies (32 tokens, pinned main vs this change): identical on all five (gemma-3-4b-it-4bit, gemma-4-e2b-it-4bit, MiniCPM-V-4.6-bf16, paligemma2-3b-ft-docci-448-6bit, InternVL3-1B-4bit) and on Qwen3-VL-2B-Instruct-4bit, a family on the plain TanhF32 route. Twins: Molmo2, Gemma 3 SigLIP and Qwen3-VL were run against IREE on real checkpoints, on this change and on a clean ce6855bc8, and every per-stage number is identical between the two ("StableHLO twins" below). Molmo2 passes; the Gemma 3 gate fails and Qwen3-VL passes its gate with free-running drift outside tolerance, both exactly as on clean main. The twins of the other tanh-switched families were not run.

Why the bits match

A probe evaluated the eager helper, the compiled chain and the fused kernel on the same array and compared f32 bit patterns per lane: the tests' sweep, 14 element counts from 1 to 65537 on both sides of every block boundary, two 2-D shapes, the tower-shaped [64, 4304] input and a dense [1024, 1024] one, 1527340 lanes per dtype. No lane differs in f32, bf16 or f16, between any two of the three paths, and eleven special values (±0, subnormal, ±inf, NaN, …) agree as well.

The first draft of the port used plain operators, like the Metal string. cuobjdump -sass on its cached f32 module shows FFMA R7, R7, 0.044715, R4, and the same probe found 1171 of 275456 tower lanes and 2062 of 1048576 dense lanes one rounding step of tanh away from the eager chain (at most 2^-22 absolute; none on the 809-point sweep; none on bf16/f16). The compiled chain agreed with the eager chain bit for bit, because its multiply and add are in different modules. With __fmul_rn / __fadd_rn the same lines are FMUL, FADD, and every lane agrees.

The limit of the claim: the multiplies and adds agree by construction; tanhf agrees with the eager chain's tanh kernel on every lane measured, which is what one expects when the AOT kernels and NVRTC come from the same CUDA release (13.0 here) and is not guaranteed across releases. fused_kernel_returns_the_eager_helper_bits_where_it_claims_to is the test that would report it.

Before / after

GB10 (sm_121, driver 580.178.04, CUDA 13.0, MLX 9f806b36), measured on 28d884a5 plus this patch, before the rebase. Full record: docs/benchmark_results/fused-gelu-tanh-f32-cuda-gb10-2026-11-11.md.

Launches per call (fresh PTX cache): TanhF32Compiled 2 or more (cube module + tail module) -> 1; TanhF32 about 11 (eager, no JIT module) -> 1.

Op level (examples/fused_gelu_tanh_microbench.rs, bf16, four runs, µs per call as median (min..max)):

Shape eager compiled fused fused / compiled fused / eager
tower prefill [64, 4304] 187.0 (118.1..216.9) 84.1 (72.0..99.0) 16.6 (14.8..17.8) 0.19x (0.17..0.22) 0.09x (0.08..0.14)
decode row [1, 4304] 109.2 (94.0..114.2) 30.6 (27.2..31.1) 12.5 (10.8..13.2) 0.41x (0.36..0.48) 0.12x (0.11..0.12)
large prefill [1024, 4096] 1571.2 (1557.7..1590.5) 698.8 (657.6..707.3) 184.4 (168.0..208.4) 0.27x (0.24..0.29) 0.12x (0.11..0.13)

Image prefill (generate --image … -n 8 --temp 0 --profile, 8 rounds, every arm with its own null arm, order rotated each round, host gate before every run; ms, median (min..max); deltas paired per round):

Family erf tanh (this PR) compiled (main) tanh - erf tanh - compiled Null arms: erf / tanh / compiled
Gemma 3 4B SigLIP (272 tokens) 831.4 (824.8..847.4) 810.9 (786.1..824.8) 853.2 (838.6..868.8) -20.4 ms, -2.5 % (-55.3..-4.9), negative in 8 of 8 -45.7 ms, -5.3 % (-78.0..-17.4), negative in 8 of 8 +0.3 (-23.0..+26.5) / -14.6 (-23.5..+27.2) / -2.7 (-26.1..+23.5)
Gemma 4 E2B vision GeGLU (278 tokens) 608.5 (596.4..620.2) 597.3 (586.7..610.1) 615.4 (606.7..629.4) -10.9 ms, -1.8 % (-24.7..+2.4), negative in 6 of 8 -20.4 ms, -3.3 % (-41.8..-4.0), negative in 8 of 8 -3.6 (-8.6..+13.3) / -0.4 (-11.3..+22.8) / +0.7 (-14.3..+11.6)

The tanh arm is inside the null floor of erf on both families and below the compiled chain in all 16 paired rounds. compiled - erf, the residual the 2026-10-23 record left open, reads +1.8 % and +0.7 % here.

The plain TanhF32 route (Qwen3-VL 2B vision blocks; pinned main = eager chain, this PR = the kernel; same schedule):

Input (prompt tokens) eager (main) kernel (this PR) kernel - eager Null arms: eager / kernel
448x448 fixture (210) 320.0 (314.6..324.8) 315.9 (310.9..320.9) -1.8 ms, -0.6 % (-13.9..+4.0): unresolved -4.0 (-12.7..+2.9) / -4.3 (-14.1..+2.6)
1240x1754 page fixture (2159) 699.2 (694.2..705.1) 623.0 (616.9..632.7) -76.8 ms, -11.0 % (-84.6..-61.9), negative in 8 of 8, outside both null ranges +10.9 (-8.6..+19.5) / -0.1 (-18.4..+9.4)

Two things about the host that the record spells out: its GPU clock is held to 300-2100 MHz by the operator's clock manager, and it serves an embedding model through ollama that wakes on other clients' requests and burns five to six cores for a minute or two. The second is outside the host gate's lists, so the driver waits for it to be idle and discards and reruns any run it overlapped (one attempt, on Gemma 4).

Test plan

Run on this PR's code (cbbd74fdc, one commit on ce6855bc8; the second commit only edits the benchmark record) on a DGX Spark (GB10, sm_121, CUDA 13.0), unless a line says otherwise.

  • cargo fmt --all -- --check
  • cargo clippy --workspace --all-targets --features cuda -- -D warnings (the Linux spelling of the template's line). Passes with no Rust warning; the build script relays C++ compiler notes from MLX headers and from files this PR does not edit
  • cargo build --release --features cuda
  • make verify-test-cuda (cargo test --workspace --profile test-fast --features cuda --no-fail-fast -- --test-threads=1), the gate CONTRIBUTING.md names for this backend: 186 of 187 test binaries pass (15489 tests passed, 1 failed, 496 ignored). The one failure, native_env_tests::the_cuda_cache_defaults_reach_mlx (MLX_CUDA_GRAPH_CACHE_SIZE reads 400, expected 2000), is the same single failure on a clean 28d884a5 (-p mlxcel-core --lib: 2257 passed, 1 failed) and does not involve this change; see the notes
  • The issue's verification commands: cargo test -p mlxcel-core --features cuda --release gelu_tests -- --test-threads=1, 17 passed (the issue's utils_gelu filter matches no test on current main; the module is utils::gelu_tests); cargo test --features cuda --release --test cuda_custom_kernel_disk_cache -- --test-threads=1, 1 passed; cargo test --features cuda --release --test cpu_device_custom_kernel_gates -- --test-threads=1, 1 passed
  • make verify-kernel-dtype-keys, make verify-kernel-port-dispatch (with their self-tests), make verify-env-var-docs, make verify-benchmark-raw-logs, make verify-python-tooling (219 tests)
  • The self-hosted ci.yml jobs that a pull request opened from a fork does not get, run by hand: clippy (cargo clippy -p mlxcel --lib --tests -- -D warnings, default features); cpu-link (cargo test -p mlxcel-core --profile test-fast --lib --no-run, then -- ptx_cache_dirs empty_mlxcel_cache_dir native_env, 13 passed; on that no-accelerator build gelu_tests passes 16 of 16, the seventeenth being #[cfg(feature = "cuda")]); cuda-blockfloat (its build, its cuobjdump step, and global_scale, 7 passed); xla-compile (cargo check --features cuda,xla-iree --all-targets and cargo check --no-default-features --features xla-diagnostics --all-targets). rocm-build needs a ROCm host and was not run
  • StableHLO twins against real checkpoints, on this change and on a clean ce6855bc8: see "StableHLO twins" below
  • Validated with real checkpoints (all mlx-community/, revisions in the record): gemma-3-4b-it-4bit, gemma-4-e2b-it-4bit, MiniCPM-V-4.6-bf16, paligemma2-3b-ft-docci-448-6bit, InternVL3-1B-4bit, Qwen3-VL-2B-Instruct-4bit: greedy 32-token image replies identical between pinned main and this change on all six, and identical again from a release build of this PR's code
  • Traced per "Judging a change that moves the numbers": on CUDA this change does not move them. No lane of 1527340 per dtype differs from the eager chain or from the compiled chain it replaces, and the greedy replies above are identical
  • cargo deny check: not run and not applicable: ci.yml runs its deny job only when **/Cargo.toml, Cargo.lock or deny.toml change, and none does here
  • Metal: not built or run here. The Metal port and its routing are untouched; two of the new tests are backend-neutral and first run on Metal in the nightly make verify after merge

StableHLO twins

The IREE toolchain comes from scripts/iree/setup-cuda.sh (IREE 3.12.0rc20260721). Each twin compares eager MLX on CUDA with the IREE lowering on local-task, built under --profile test-fast --features xla-diagnostics,xla-reference-diagnostics, once on this change and once on a clean ce6855bc8.

Twin (tanh-GELU route) Command, checkpoint This change Clean ce6855bc8
Molmo2 vision (TanhF32) cargo test --test molmo2_xla_vision_parity -- --include-ignored, Molmo2-8B-4bit passes (8 tests, the real-checkpoint gate among them): vision projection max abs 0.3047 at a magnitude of 8.06e4, rms 0.00167, no element over the limit passes, all 25 stage lines identical
Gemma 3 SigLIP (TanhF32Compiled) cargo run --example xla_gemma3_reference_check, gemma-3-4b-it-4bit fails: first divergence at siglip.hidden.block4.output, max abs 0.1067 against atol 0.08 on 5 of 4718592 elements; siglip.block0.mlp_activation itself passes at max abs 4.8e-4 fails the same way, all 34 stage lines identical
Qwen3-VL DeepStack (TanhF32) cargo run --example xla_qwen3_vl_deepstack_check, Qwen3-VL-2B-Instruct-4bit passes its gate (same-input operator controls clean, greedy top-1 exact, both negative controls detected); 42 of its 67 free-running stage comparisons are outside tolerance passes, all 67 comparisons identical

Every per-stage number is the same with and without this change, which is what an MLX side that is unchanged in bits predicts. The Gemma 3 gate's failure and the Qwen3-VL free-running drift are how main behaves on this host with these 4-bit checkpoints; I did not look into either further.

Notes for reviewers

  • TanhF32 is routed on CUDA only, and its pin is untouched. perf(metal): fuse the tanh-GELU f32 chain into one kernel #2858 left TanhF32 eager on Metal because the kernel would break the bit-for-bit fold pin. The issue expected the pin to relax here for the same reason ("Fusion changes rounding (FMA contraction)"). It does not have to: with the contraction written out of the body the kernel is the eager chain's bits, so BERT (src/models/bert.rs:292), Qwen3-VL (src/vision/encoders/qwen3_vl.rs:772) and Molmo2 (src/vision/encoders/molmo2.rs:94) get one launch instead of about eleven and the pin still passes as written. What it buys depends on how many patches the tower sees: nothing resolvable on Qwen3-VL at 448x448, 11 % of the prefill on a page-sized image. If you would rather keep TanhF32 eager on CUDA as well, it is the one arm in GeluActivation::apply and the second port table.
  • compute-sanitizer says nothing about the grid guard. memcheck reports 0 errors on the probe and on the GELU test module, and also on a build with the guard removed, whose outputs are unchanged: MLX's allocator rounds a buffer to a power of two or to 16384-byte pages (mlx/backend/cuda/allocator.cpp:176-182), so lanes past n land in the buffer's own slack. The guard rests on the launcher code, not on the sanitizer.
  • The gate's one failure is on main already. native_env_tests::the_cuda_cache_defaults_reach_mlx passes alone and fails once any test has touched the CUDA device earlier in the process, because mlx::core::config::get memoizes the first value it reads (mlx/config.cpp) and MLX's device has by then read MLX_CUDA_GRAPH_CACHE_SIZE with its own default of 400. One unrelated GPU test in front of it is enough, on a clean 28d884a5 as well. Not filed as an issue yet.
  • Not measured: the StableHLO twins of the other tanh-switched families; Metal; ROCm; image-prefill timing for MiniCPM-V 4.6, PaliGemma, Molmo2 and BERT; a host whose NVRTC and build toolkit are different CUDA releases.
  • The microbenchmark's two small shapes are launch-bound and move from run to run (the record has the four runs); read those rows as ranges. The large-shape row is stable.

Checklist

  • PR title uses a Conventional Commits prefix
  • One logical change per PR
  • Updated docs/ (docs/benchmarks.md, the benchmark index, the record)
  • Updated // Used by: ... comments on the shared functions I modified
  • No secrets, credentials, or .env files committed
Follow-up issue for the erf path (acceptance criterion 2): drafted, not filed yet

Title: perf(cuda): the erf GELU (gelu_approx) runs as an eager six-kernel chain on the vision towers

Found while closing #2780 (acceptance criterion 2). GeluActivation::Erf reaches gelu_approx in src/lib/mlxcel-core/cpp/mlx_cxx_bridge.cpp, which is an eager chain: erf(divide(x, sqrt2)), add(one, …), multiply(half, …), multiply(x, …), astype(…, x.dtype()); the f32 scalar constants promote a bf16 input to f32 along the way. Each op is one AOT kernel, so the erf GELU is about six launches per call on CUDA (the same eager code runs on Metal). The compile_shapeless form compiled_gelu_approx exists but has no production caller.

Evidence: on GB10 (28d884a5 plus the #2780 port), the Gemma 3 erf arm (vision_config.hidden_act = "gelu") run against an empty MLX_PTX_CACHE_DIR leaves exactly the tanh arm's compiled modules minus the fused tanh kernel, i.e. nothing for the erf GELU, which is what an eager chain looks like in the JIT cache. In the same record's image-prefill rounds the erf arm sits above the single-kernel tanh arm on both families (Gemma 3 831.4 against 810.9 ms, paired -20.4 ms and negative in 8 of 8 rounds; Gemma 4 608.5 against 597.3 ms), inside the null floor in size but consistent in sign, which is what a six-launch chain against one launch would look like. Full record: docs/benchmark_results/fused-gelu-tanh-f32-cuda-gb10-2026-11-11.md.

Proposed: decide between (a) routing Erf to compiled_gelu_approx and checking whether MLX's CUDA compile backend splits that region as it did the tanh one, and (b) an erf port of the gelu_tanh_f32 custom kernel (same launcher shape, erff in f32, store through T, and __fmul_rn / __fadd_rn / __fdiv_rn so it returns the eager chain's bits, as the tanh port does). Either way, measure with the erf-vs-tanh protocol (image prefill, a null arm per arm) before switching, because the families on Erf (InternViT, the Phi-4 SigLIP, …) are the ones that kept erf on purpose in #2423.

Out of scope for #2780, which only ports the tanh kernel.

PR lablup#2858 made GeluActivation::TanhF32Compiled one Metal kernel and left the
port table's .cuda entry null, so on CUDA the variant still went through the
compile_shapeless region. On the pinned main that region leaves one cube
module and one tanh-tail module per output dtype in the PTX cache, at least
two launches per call, which is the split the GELU erf-vs-tanh record
(2026-10-23) saw and issue lablup#2780 asks to close. Plain TanhF32 was the eager
chain, about eleven launches.

Add the CUDA port of the kernel in gelu_tanh_f32.cpp: one thread per
element, f32 arithmetic in the op order of gelu_tanh_approx, tanhf, store
through T. MLX's CUDA launcher rounds the grid up to whole blocks
(mlx/backend/cuda/custom_kernel.cpp:339-340), so the body returns on lanes at
or past x_shape[0], read as a launch argument rather than a template
constant: the JIT cache key stays the dtype alone, one module and one
disk-cache entry per dtype.

Write every multiply and add in the CUDA body as __fmul_rn / __fadd_rn. With
plain operators NVRTC contracts x + 0.044715 * x^3 into one FFMA, and about
four f32 lanes in a thousand then sit one rounding step of tanh away from the
eager chain (1171 of 275456 on the tower-shaped input), because the eager
chain and the compiled chain round the multiply and the add in separate
kernels. With each operation rounded on its own the kernel returns the eager
chain's bits on every lane measured: 1527340 per dtype, f32, bf16 and f16,
against the eager helper and against the compiled chain.

That makes the issue's two-variant routing possible without relaxing a pin.
TanhF32Compiled takes the kernel wherever it has a port, as lablup#2858 set up.
TanhF32, whose call sites (BERT, Qwen3-VL, Molmo2) are pinned bit for bit,
takes it where the port returns the eager helper's bits, asked through
fused_gelu_tanh_f32_matches_eager_bits(), which reads a second port table
listing the CUDA port only. Metal, ROCm and the CPU device keep the eager
helper for TanhF32; the Metal body may contract, which is why lablup#2858 left it
there.

Tests: fused_kernel_is_unreachable_on_cuda becomes
fused_kernel_is_reachable_on_cuda; a new test holds the kernel and both
dispatch arms to the eager helper's bits on the sweep, on element counts
around the 256-thread block and on the tower-shaped input in three dtypes,
and fails on the plain-operator body; a sweep tolerance test covers the
ports that make no bit claim; the CPU device keeps the eager helper; the
disk-cache test launches the kernel and requires its entry and a
compile-free second process. The fold pins are unchanged and pass through
the kernel. The dtype-key checker pins the file as a launcher (9 -> 10 in
its self-test).

Measurements on GB10 are in
docs/benchmark_results/fused-gelu-tanh-f32-cuda-gb10-2026-11-11.md.

Closes lablup#2780.
The record listed the StableHLO twin re-check as not established for want
of an IREE toolchain. scripts/iree/setup-cuda.sh builds one on GB10, so the
three twins issue lablup#2780 names were run against real checkpoints after the
rebase onto ce6855b, on the change and on a clean main: Molmo2 passes,
the Gemma 3 gate fails at siglip.hidden.block4.output, Qwen3-VL passes its
gate with free-running drift outside tolerance, and every per-stage number
is identical with and without the change.

Also note that a release build of the rebased change reproduces the six
greedy replies, and narrow the "not established" list accordingly.
inureyes pushed a commit that referenced this pull request Nov 14, 2026
## Summary

mlxcel handed a model the pixels a picture stores and ignored its EXIF `Orientation` tag, so a portrait photo from a phone reached the model on its side. mlx-vlm's and transformers' `load_image` turn the picture by that tag (`PIL.ImageOps.exif_transpose`). This applies the tag where pictures are decoded: the one decode every server family and `mlxcel generate` share, the Kimi K3 prompt sizing that reads the header ahead of it, and the commands that open a picture themselves.

## Related issues

Closes #2992.

#2717 lists this under "Deferred" for its edit source.

## Type of change

- [x] `fix`: bug fix

## Cause

`decode_request_image_with_limits` in `src/server/model_worker.rs` was `ImageReader::new(..).with_guessed_format()?.decode()`. The `image` crate decodes the stored pixels and leaves the tag to the caller (`ImageDecoder::orientation`, `DynamicImage::apply_orientation`). Every server family, the diffusion, Florence-2 and Nemotron-parse workers and the OpenXLA preprocessors decode through that function, and `mlxcel generate` reaches it through `server::local_media`. `embed`, `rerank`, `generate-image` and the detection predictors called `image::open` / `image::load_from_memory` directly.

## Change

- **`src/multimodal/image_orientation.rs`** (new). `exif_orientation(bytes)` reads the tag from the header and metadata (JPEG `APP1`, PNG `eXIf`, WebP). `turn_upright`, `load_upright_from_memory` and `open_upright` apply it after the decode; `upright_dimensions` answers for a header-only caller. No tag, a value the tag does not define, and metadata that cannot be read all leave the picture as stored: an unreadable tag is no reason to refuse a picture that decodes.
- **The shared decode** calls `turn_upright` after `reader.decode()`. The limits are untouched: width, height and allocation are still checked by the decoder on the stored pixels, and a decode that is refused today is refused the same way.
- **Kimi K3 image prompts** are sized from the header before the worker decodes. `planned_image_size` (the header probe, moved out of `kimi_k3_image_prompts` so it can be tested without a renderer) returns the upright size, so the planned `<|media_pad|>` run still matches the grid the decoded picture produces after a quarter turn.
- **Direct opens**: `mlxcel embed`, `mlxcel rerank`, `mlxcel generate-image` references, the diffusion path of `mlxcel generate`, `Yolo11Predictor::predict_path_with_size` and the RT-DETRv2 `process_path`.
- **Docs**: a paragraph under "Multimodal projectors and request media" in `docs/llama-server-compat.md`, and a sentence in `docs/embeddings.md`.
- Not changed: the benchmark binaries and diagnostics, which read repository fixtures, and video frames, which are decoded from frames without an EXIF tag.

## Before / after

GB10 (sm_121, CUDA 13.0), release builds of `ce6855bc8` (`main`) and of this PR, greedy. The pictures are the shapes fixture (red square top left, blue circle top right, green triangle at the bottom) and a white picture with the text `HELLO 739`, stored turned and tagged with PIL as in the issue; PIL's `exif_transpose` gives the upright picture back for each.

`mlxcel generate --image <picture> -n 40 --temp 0 -p "Which shape is at the bottom of the image, and which shapes are at the top? Answer briefly."` (the text rows: `-n 24 -p "Read the text in the image. Reply with the text only."`):

| Picture | Model | `main` | This PR |
|---|---|---|---|
| JPEG, tag 6 | Qwen3-VL-4B-Instruct-4bit | The red square is at the bottom. The blue circle and green triangle are at the top. | The green triangle is at the bottom. The red square and blue circle are at the top. |
| JPEG, tag 3 | same | Bottom: circle and square. Top: triangle. | Shape at bottom: triangle. Shapes at top: square and circle. |
| JPEG, tag 8 | same | Shape at bottom: blue circle. Shapes at top: red square and green triangle. | The green triangle is at the bottom. The red square and blue circle are at the top. |
| PNG (`eXIf`), tag 6 | same | Shape at bottom: red square. Shapes at top: blue circle, green triangle | Triangle is at the bottom. Square and circle are at the top. (the upright PNG's reply, word for word) |
| WebP, tag 6 | same | the same as the PNG | the same as the PNG |
| text, JPEG tag 6 | same | 30 30 30 30 30 30 30 30 | Hello 73 (the upright picture's reply) |
| text, JPEG tag 3 | same | 631007122222222222222222 | Hello 73 |
| JPEG, tag 6 | gemma-3-4b-it-4bit | Bottom: Square. Top: Circle and triangle | Bottom: Triangle. Top: Square and Circle (the upright reply, word for word) |
| JPEG, tag 3 | same | Bottom: Square. Top: Triangle, Circle | the upright reply |
| JPEG, tag 8 | same | Bottom: Circle. Top: Triangle and Square | the upright reply |
| PNG (`eXIf`) and WebP, tag 6 | same | Bottom: Square. Top: Circle and triangle | the upright reply |

Those are the 12 of 28 replies that change. The other 16 are word for word the same on both builds: the 14 for pictures without a tag (the upright pictures, and the turned pixels saved without the tag, which stay turned), and Gemma 3's two for the tagged text pictures, which it reads as `HELLO 739` in any orientation.

**The server.** `mlxcel-server -m Qwen3-VL-4B-Instruct-4bit`, `POST /v1/chat/completions` with the picture as a base64 `image_url`, `temperature: 0`, the same question:

| Picture | `main` | This PR |
|---|---|---|
| upright JPEG | Shape at bottom: triangle. Shapes at top: square and circle | identical |
| JPEG, tag 6 | The red square is at the bottom. The blue circle and green triangle are at the top. | The green triangle is at the bottom. The red square and blue circle are at the top. |
| the same pixels, no tag | The red square is at the bottom. The blue circle and green triangle are at the top. | identical |
| JPEG, tag 3 | Bottom: circle and square. Top: triangle. | Shape at bottom: triangle. Shapes at top: square and circle. |
| PNG (`eXIf`), tag 6 | Shape at bottom: red square. Shapes at top: blue circle, green triangle | Triangle is at the bottom. Square and circle are at the top. |
| WebP, tag 6 | the same as the PNG | the same as the PNG |

**A picture without a tag, across the families.** `tests/fixtures/test_image_shapes.png` (chunks `IHDR`, `IDAT`, `IEND`: no `eXIf`), `-p "Describe the image." -n 48 --temp 0` (`<CAPTION>` for Florence-2), both builds, on 35 checkpoints: Bunny-Llama-3-8B-V, Florence-2-base-ft, GLM-4.1V-9B-Thinking, Idefics2-8B, Idefics3-8B-Llama3, InternVL3-1B and -2B, Kimi-VL-A3B-Thinking, LFM2-VL-450M and -1.6B, Llama-3.2-11B-Vision, Molmo-7B-D-0924, Molmo2-4B and -8B (6 and 8 bit), Phi-3.5-vision, Qwen2-VL-2B, Qwen2.5-VL-3B, Qwen3-VL-4B, SmolVLM-Instruct, aya-vision-8b, deepseek-vl2-small, fastvlm-0.5b, gemma-3-4b, gemma-3n-E2B, gemma-4-e2b, granite-vision-3.2-2b, llava-1.5-7b, llava-interleave-qwen-0.5b, llava-v1.6-mistral-7b, MiniCPM-V-4.6, nanoLLaVA-1.5, PaliGemma 2 (two conversions), pixtral-12b.

- 29 describe the picture. 27 of them give the same reply on both builds, word for word.
- The other two, granite-vision-3.2-2b-4bit and nanoLLaVA-1.5-4bit, gave a different text, and they do that between two runs of one binary: over 20 alternating runs each, `main` gave two texts for granite-vision (18 and 2 runs) and two for nanoLLaVA (17 and 3), and this PR's binary gave the same two (15 and 5, 17 and 3). Qwen3-VL-4B, run the same way as a control, gave one text in all 40 runs. It is the default one-row decode SDPA of #2128, not this change: with `MLXCEL_SDPA_DETERMINISTIC=1` each of the two checkpoints gave one text in 20 of 20 runs on `main` and the same text in 20 of 20 on this PR.
- Six show no reply to compare, the same on both builds: GLM-4.1V, Kimi-VL, gemma-4-e2b and MiniCPM-V-4.6 spend the 48 tokens in the reasoning channel, and the two Molmo2-8B conversions print `!` (#2968).

## Test plan

Run on this PR's commit (`23edeeb40`, 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] `cargo test --profile test-fast --features cuda --lib multimodal::image_orientation -- --test-threads=1`: 6 passed. All eight tag values come back pixel for pixel through a PNG whose `eXIf` chunk the test writes by hand, and through a JPEG `APP1` segment; the stored pixels are computed from the tag's definition, not with the crate's own transforms
- [x] The same command for `server::model_provider::model_worker` (41 passed), `server::chat_request` (131 passed), `kimi_k3` (109 passed) and `vision::detection` (110 passed)
- [x] Mutations. With the `turn_upright` call taken out of the shared decode, `decode_request_images_turns_a_picture_upright_by_its_exif_orientation` fails (a 4 x 6 picture for the 6 x 4 one). With the stored size back in the Kimi K3 planning, `an_image_prompt_is_sized_for_the_upright_picture` fails at tag 5 (`(4, 6)` for `(6, 4)`)
- [x] Evidence identity audit (2026-11-12): all eight newly added test names are present and passing in the targeted logs and in the full CUDA gate; the two removed-call controls fail by name, and the recorded final tree matches this commit. This is a read-only audit of the retained runs, not a rerun.
- [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 (15494 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` (the build and its 13 tests) and `xla-compile` (`cargo check --features cuda,xla-iree --all-targets`, `cargo check --no-default-features --features xla-diagnostics --all-targets`), plus `cargo check --features cuda,xla-reference-diagnostics --all-targets`: all pass
- [x] `make verify-python-tooling` (219 tests OK), license headers, cross-repo refs, env-var docs, native-env writes, the llama-compat manifest (the new paragraph is in that document) and the binary-asset budget (the tests build their pictures in memory and add no file)
- [x] Validated with real checkpoints: the tables above
- [x] Traced per "Judging a change that moves the numbers": a reply moves only for a picture whose tag is 2 to 8. A picture without a tag decodes to the same pixels (`a_picture_without_a_readable_tag_is_left_as_it_is`), and 27 of the 29 checkpoints that describe such a picture give the same reply word for word; the two that do not vary between runs on `main` as well, and give one text on both builds with `MLXCEL_SDPA_DETERMINISTIC=1`
- [ ] `cargo deny check`: not run and not applicable (no manifest, lockfile or `deny.toml` change; `image` is already a dependency)
- [ ] Metal: not built or run here. The change is in the decode, before any array exists; the new tests first run on Metal in the nightly `make verify`

## Notes for reviewers

- **This changes what a model sees for a tagged picture, on purpose.** A client that already sends upright pixels without the tag is not affected (PIL's `exif_transpose` removes the tag when it turns a picture). A picture whose pixels are upright but whose tag still says otherwise is turned, as it is in mlx-vlm, transformers and any viewer.
- **Detection boxes are in upright coordinates now**, the picture the user looks at. Before, a tagged picture gave boxes in the stored frame.
- **Memory.** A quarter turn makes a second buffer of the same size for a moment. The decode allocation limit bounds the first; the copy is the same size and is not counted against it.
- **The tag is read in a second pass over the header**, not from the decoder that produces the pixels. `ImageReader::decode` reserves the output buffer against `max_alloc` before it hands the limits to the decoder, and `into_decoder` does not; reading the tag from a separate header parse keeps the limit path exactly as it was.
- **Not run:** `embed`, `rerank`, `generate-image` and the two detectors on a real checkpoint (I have none of those here; the call sites are one-line swaps to the tested helper). A real phone photo: the pictures are synthetic, built with PIL and, in the unit tests, by hand. The `WebUI installed artifact` job, which `src/server/**` triggers and a fork PR does not get: it needs pnpm and Playwright, which this host does not have. Metal.

## Checklist

- [x] PR title uses a Conventional Commits prefix
- [x] One logical change per PR
- [x] Updated `docs/`: `docs/llama-server-compat.md`, `docs/embeddings.md`
- [x] Updated `// Used by: ...` comments: on the new functions; no existing shared function changes its contract
- [x] No secrets, credentials, or `.env` files committed
@inureyes inureyes added area:core mlxcel-core: MLX FFI, primitives, KV cache, layers platform:linux Linux (CUDA / packaging) specific priority:low Low priority status:review Under review type:performance Performance improvements labels Nov 15, 2026
@inureyes

Copy link
Copy Markdown
Member

Implementation hardening for #2967.

Reviewed #2780: f32 CUDA tanh GELU uses explicit rounded arithmetic to preserve the eager result, bounds its flat launch, and keeps CPU/dtype fallbacks. No further correctness, memory-safety, or hot-path performance defect was found.

Validation: The CUDA core suite passed 2,279 tests, including fused/eager bit comparisons, dtype dispatch, noncontiguous inputs, and CPU fallback. The committed performance evidence was reviewed; throughput benchmarks were not re-run.

Commands: cargo test --workspace --profile test-fast --features cuda --no-fail-fast -- --test-threads=1 on the combined candidate tree has passed the affected module tests noted above; the broader run is still finishing. cargo fmt --all -- --check and python3 scripts/ci/check_kernel_dtype_keys.py passed. Required GitHub checks are checked again immediately before merge.

@inureyes
inureyes merged commit d084a04 into lablup:main Nov 15, 2026
31 checks passed
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 15, 2026
inureyes pushed a commit that referenced this pull request Nov 15, 2026
)

## Summary

An image prompt on `mlx-community/Molmo2-8B-4bit` answered with token 0 (`!`) at every position, while a text-only prompt on the same checkpoint was fine. The checkpoint's float tensors are float16, two values of the vision tower's output are above the float16 maximum, and the merge cast them to the text dtype and scattered them with a one-hot matmul, which spreads the resulting `inf` over the whole sequence as NaN. This ports the clamp mlx-vlm applies at that point (Neywa-Labs/mlx-vlm#1165).

## Related issues

Closes #2968.

## Type of change

- [x] `fix` — bug fix

## Cause

Statistics from `Molmo2VLModel::get_input_embeddings` with temporary instrumentation (never committed), on `ce6855bc8` and on this change, same prompt (436 tokens, 392 of them image patches, `tests/fixtures/test_image_shapes.png`):

| Stage | dtype | `main` | This PR |
|---|---|---|---|
| text embeddings | float16 | finite, max 0.8125 | same |
| vision tower output | float32 | finite, max 81998.11, 2 of 1605632 values above 65504 | same |
| features after the cast to the text dtype | float16 | 2 values `+inf` | finite, max 64992 |
| `one_hot @ image_features` | float16 | 436 NaN | no NaN |
| merged embeddings | float16 | 436 NaN | no NaN, max 64992 |

`src/vision/molmo2_vl.rs` cast the tower's float32 output to the text dtype and added it with `matmul(one_hot, image_features)`. `0 * inf` is NaN, so a single overflowed value makes its hidden dimension NaN in every row, image patch or not: 436 NaN is one column of the 436-token sequence. NaN logits, argmax 0, and token 0 of this vocabulary is `!`. The second fixture (`test_image.png`) reads the same with a largest value of 80604.72.

The projector has no output norm, and the Hugging Face model adds the features in the model dtype, which is float32 in the original config. mlx-vlm clamps the tower's output before the add since Neywa-Labs/mlx-vlm#1165 (`clip_image_features`: NaN to zero, ±65000 for float16, the dtype's largest value otherwise).

## Change

- `image_feature_clip_limit` and `clip_image_features`: mlx-vlm's clamp, keyed on the dtype the features are added in. Here the tower output is float32 and is cast afterwards; mlx-vlm runs the tower in the weight dtype and clamps there. Both end at ±64992 in float16 (65000 rounded to the float16 grid).
- `merge_image_features`: the clamp, the cast and the existing one-hot scatter, moved out of `get_input_embeddings` so the merge can be tested on synthetic arrays. The scatter is unchanged, and values inside the range merge bit for bit as before.
- Molmo2 only. Molmo-Point merges in float32. Molmo v1 has the same cast-then-matmul shape, but mlx-vlm does not clamp there and I have no checkpoint that fails, so it is left as it is. The OpenXLA Molmo2 path prepares float32 embeddings and is not touched.

## Before / after

GB10 (sm_121, CUDA 13.0), `generate --image <fixture> -p "Describe the image." -n 48 --temp 0`, release builds: `main` is the pinned `28d884a5` binary, which answers the same as `ce6855bc8`.

| Checkpoint | Fixture | `main` | This PR |
|---|---|---|---|
| `mlx-community/Molmo2-8B-4bit` @ `4fcbe9265776` (floats F16) | `test_image_shapes.png` | `!` × 48 | "The image features a minimalist composition with three distinct geometric shapes arranged against a light gray background. At the top left is a solid red square, while the top right contains a solid blue circle. Below these, centered at the bottom of the image" |
| same | `test_image.png` | `!` × 48 | "The image shows a large, solid orange square. It's a simple, minimalist design with no text, objects, or additional elements. The orange color is vibrant and uniform throughout the square, creating a bold and eye-catching visual. The square" |
| `Aliyovic/molmo2-4b-mlx-8bit` @ `7fdd4d51c51c` (floats F32, largest tower value 27412) | both | a correct description | identical reply |

The shapes fixture is a red square (top left), a blue circle (top right) and a green triangle (bottom) on light gray; the other is a solid orange square. A text-only prompt on the 8B checkpoint answers "Hello!" before and after.

## Test plan

Run on this PR's commit (`262c09f55`, 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] `cargo test --profile test-fast --features cuda --lib vision::molmo2_vl -- --test-threads=1`: 5 passed. With the clamp removed, 3 of the 5 fail, among them `a_feature_past_the_float16_maximum_stays_finite_and_local`
- [x] `cargo test --profile test-fast --features cuda --lib molmo2 -- --test-threads=1`: 15 passed
- [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 (15491 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 and this change can reach, run by hand: `clippy` (`cargo clippy -p mlxcel --lib --tests -- -D warnings`, default features) and `xla-compile` (`cargo check --features cuda,xla-iree --all-targets`, `cargo check --no-default-features --features xla-diagnostics --all-targets`): all three pass
- [x] `make verify-python-tooling`, license headers, cross-repo refs: 219 Python tests OK, license headers OK, the one cross-repository reference this adds is qualified (`Neywa-Labs/mlx-vlm#1165`)
- [x] Validated with real checkpoints: the table above
- [x] Traced per "Judging a change that moves the numbers": the change moves numbers only where they were NaN. Values inside the range merge bit for bit (`features_inside_the_range_merge_exactly_as_before`), and the 4B checkpoint's replies are identical
- [ ] `cargo deny check`: not run and not applicable (no manifest, lockfile or `deny.toml` change)
- [ ] Metal: not built or run here. The change is backend-neutral array code; the new tests first run on Metal in the nightly `make verify`

## Notes for reviewers

- **The clamp is the reference's behaviour, not the float32 original's.** On this checkpoint two values per image go from about 8.2e4 to 64992. A float16 residual stream cannot hold the original values, and with the clamp the 8B answers correctly on both fixtures.
- **The other `mlx-community/Molmo2-8B-*` conversions were not run.** Only the 4-bit checkpoint was.
- **mlx-vlm's output was not compared.** Its CPU build on this host (mlx 0.32.4, mlx-vlm 0.7.12) had printed nothing for the first prompt after 31 minutes and was stopped, so the reference here is its source (`mlx_vlm/models/molmo2/molmo2.py`) and not its reply.

## 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 beyond the fix
- [x] Updated `// Used by: ...` comments on the functions I added
- [x] No secrets, credentials, or `.env` files committed
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.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:core mlxcel-core: MLX FFI, primitives, KV cache, layers platform:linux Linux (CUDA / packaging) specific priority:low Low priority status:done Completed type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(cuda): single-kernel tanh GELU so tanh-switched families match erf prefill cost

2 participants