Skip to content

update(xla): round the Qwen3-VL vision tower at eager's BF16 boundaries - #3336

Merged
inureyes merged 4 commits into
mainfrom
update/issue-3291-qwen3vl-bf16-vision
Nov 23, 2026
Merged

inureyes merged 4 commits into
mainfrom
update/issue-3291-qwen3vl-bf16-vision

Conversation

@inureyes

@inureyes inureyes commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Summary

The XLA Qwen3-VL vision graph now rounds to BF16 wherever eager MLX stores a BF16 tensor for the BF16 checkpoint, instead of running the whole tower in f32. GEMMs, norm reductions and softmax statistics still accumulate in f32, as MLX's kernels do.

  • Rounding points (emitter/qwen3_vl_ops.rs): input patches; patch embedding and every linear (matmul product, then bias add, two roundings); interpolated position embeddings (f32 corner sum (c0+c1)+(c2+c3), then one rounding); LayerNorm as MLX's CUDA kernel computes it (f32 stats, then normalized value, w*n and +b each rounded); RoPE'd q and k; attention as cuDNN flash SDPA computes it (f32 scores and row sum, BF16 unnormalized probabilities into the value GEMM, normalized context rounded); both GELUs (f32, rounded once); residual adds; main and DeepStack mergers.
  • Rounding is integer round-to-nearest-even on the f32 bit pattern with a NaN guard, so the graph lowers on Metal too. Contractions take BF16 inputs where the target lowers BF16 and the BF16-exact f32 carrier on Metal (qwen3_vl_vision_precision(device)).
  • The operator numeric contract declares BF16 output rounding on every Qwen3-VL operator except the attention scores. The production contract digest changes from ae5bfb35... to bdd1632d..., and the artifact from 18e85256... (defac5fb) to 4d3934a5... (775dbb9f). The old cached artifact is not reused.

Results (GB10 CUDA, xla_qwen3_vl_deepstack_check, atol/rtol 0.08 unchanged)

before after
shapes224 final-logit max_abs 0.205 0.198
shapes224 chained block 23 (ref 2528) 230 184
shapes224 main merger 1.82 1.00
fixture chained block 23 (ref 2656) 1020 1100
fixture main merger 1.52 5.16
fixture same-input block 23 control (fused) 3 failures 0 failures
Qwen3-VL greedy vs eager (fixture, 64 tokens) diverges at 8 diverges at 27
Qwen2.5-VL greedy vs eager exact (EOS at 8) exact (EOS at 8)
warm iree_vision_seconds (single run) 1.85 s 1.67 s

Same-input controls of the production eager block now sit at 1 BF16 step or less in every block except fixture block 10 (2 steps; report-only, was 0.338). Index 27 is an exact eager tie, 576 and 2619 both at 30.375 (margin 0.0). XLA has 2619 over 576 by 0.021, inside one BF16 step (0.125) at that magnitude.

Criteria revised by the maintainer on #3291: chained block-23 drift (184 against Qwen2.5-VL's 133) is recorded, not gated, because block 10 amplifies 1-step summation-order differences about 40x on both images and matching rounding boundaries cannot remove that; final-logit drift passes. The report-only block-23 host_dequant_dense_f32 control compares against an f32 reference, which BF16 matching is expected to widen (6 values over tolerance on shapes224, BF16 cancellation at magnitude 2545 where one step is 16); the fused control against eager BF16 keeps the 2 failures already present on main. No tolerance changed.

Finalization added tests pinning qwen3_vl_vision_precision per target and asserting the Metal-precision graph contains no bf16 type, and a CHANGELOG entry.

Test plan

  • cargo test -p mlxcel-xla --lib qwen3_vl (17 pass) and operator_numeric_contract; cargo clippy -p mlxcel-xla --lib --tests -- -D warnings
  • cargo check --features cuda,xla-iree --all-targets; cargo check --no-default-features --features xla-diagnostics --all-targets
  • Deepstack check on shapes224 and on the fixture with --token-ids at indexes 8 and 27, before and after
  • mlxcel generate -n 64 --temp 0, eager vs MLXCEL_BACKEND=xla, for qwen3-vl-2b-instruct-4bit and qwen2.5-vl-3b-instruct-4bit

Closes #3291

The XLA Qwen3-VL vision graph ran in f32 while eager MLX runs the BF16 checkpoint's tower on BF16 tensors, so the two drifted apart over 24 blocks and the fixture's greedy output split at a near-tie (index 8).

The graph now keeps its f32 ABI carrier but rounds to BF16 wherever eager stores a BF16 tensor: input patches, patch embedding, interpolated position embeddings, each linear (product, then bias add), LayerNorm (normalized value, weight product, bias sum, as MLX's CUDA kernel does), RoPE'd query and key, attention probabilities and context, GELU outputs, residual adds, and both mergers. Reductions, softmax statistics, and GEMMs still accumulate in f32. Rounding is integer round-to-nearest-even on the bit pattern, so the graph lowers on Metal too; contractions read BF16 where the target supports it and the BF16-exact f32 carrier on Metal.

The operator numeric contract declares the BF16 output rounding on every operator except the attention scores, so the v3 auxiliary manifest's contract digest changes and cached f32 artifacts recompile.

Validated on GB10: per-block same-input controls pass at 0.08/0.08, Qwen3-VL greedy on the fixture now matches eager through index 26 (index 27 is an exact eager BF16 tie), and Qwen2.5-VL stays token-exact.

Refs #3291
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:high High priority area:architecture Architecture and code structure changes area:inference Generation, sampling, decoding (incl. speculative, DRY) labels Nov 23, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Round the XLA Qwen3-VL vision tower to BF16 where eager MLX CUDA materialises BF16, keep f32 accumulation inside ops, and bind the change into the operator numeric contract.

Rounding points checked against eager

Every point matches the eager source for this checkpoint, whose vision tower is unquantized BF16, so every linear is matmul then a separate bias add:

  • Input cast, patch embedding (two roundings), and the f32 position-embedding corner sum with one cast. The fixture diff is exactly 0 at all three stages.
  • LayerNorm: f32 statistics, then w * T(norm) + b in BF16 with two roundings, per the overlay layer_norm.cu line 127.
  • RoPE: widened to f32, then one cast.
  • SDPA: cuDNN is selected for unmasked BF16 attention at head_dim 64. P is unnormalized BF16, the row sum is f32, and the output is BF16.
  • Tanh GELU and the merger's exact GELU: f32 evaluation with one cast, matching gelu_tanh_f32 and the bridge gelu op order.
  • Residual adds, plus both merger orders (main merger: norm, then reshape; DeepStack mergers: reshape, then norm).

No rounding point is wrong or missing. Each merger's drift moves in the same direction as the chained drift of the block that feeds it, in 8 of 8 image/merger pairs (blocks 5/11/17/23 against DeepStack 0/1/2 and the main merger). DeepStack merger 0, whose input drift is under one step, stays within half a step. The fixture's main merger got worse (1.52 to 5.16) because its input, block 23, got worse (1020 to 1100). The merger itself is not the cause.

Remaining Items

  • The PR body says every same-input control is within one BF16 step. Fixture block 10 is at 2.0 on reference 224, which is two steps (MEDIUM). Please correct the description.
  • No test emits the full graph at Precision::F32 and asserts that it contains no bf16, and none pins qwen3_vl_vision_precision("metal") == F32 (MEDIUM). Metal compilability currently holds only by construction.
  • There is no same-input merger control, so the merger evidence above is indirect (LOW).
  • The Metal note says the f32 carrier "forms the same products". That holds for this BF16 vision checkpoint. It would not hold for a quantized vision tower, because host-dequantized weights are not BF16-exact (LOW).
  • round_bf16 is the fourth emitter copy of this helper. The integer form is justified by Metal; the other three convert through bf16 (LOW).

Verification

  • All stated requirements implemented (two acceptance criteria are open for the user to decide)
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass (qwen3_vl 15/15, operator_numeric_contract 19/19, clippy and fmt clean; no tolerance changed)

@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review of the BF16 rounding change: no CRITICAL or HIGH findings, no commits pushed.

Cache binding: the vmfb path comes from cached_vmfb_path over the emitted MLIR text, and compiler_generation_identity hashes the same MLIR into the contract, so the new graph changes both the cache key and the v3 manifest identity. The declared operators now carry rounded_to(bf16) and the precision is passed through ProductionNumerics, so the numeric contract differs from pre-change artifacts and old entries fail closed instead of being reused.

Shape arithmetic: the new ops derive every dimension from the validated config and the static patch bucket (bucket_for_patches, hidden % heads check). The only assert on this path is the internal bucket-membership check, which request sizes cannot reach. round_bf16 asserts an f32 carrier, a compile-time graph property. No unchecked request-sized arithmetic added.

Performance: the converts and selects are elementwise integer ops that XLA fuses, and the reported warm vision time did not regress (1.85s to 1.67s, single run).

LOW: the flash-attention running maximum is approximated by the row maximum (documented in the code), which is a parity nuance, not a safety issue.

Ran cargo test -p mlxcel-xla --lib --profile test-fast qwen3_vl (15 passed) and operator_numeric_contract (19 passed).

…elog

Pin qwen3_vl_vision_precision to F32 on Metal and BF16 on CUDA, and emit the full vision graph at the Metal precision for the smallest and largest buckets, asserting the MLIR names no bf16 type. Correct the Metal doc comment: the f32 carrier forms the same products only while the vision weights are BF16-exact, which a quantized vision tower is not. Add the Changed entry for the operator numeric contract change, including the one-time artifact recompile.

Validation:
- cargo test -p mlxcel-xla --lib --profile test-fast qwen3_vl: 17 passed

Refs #3291
Adds the English and Korean reports for the Qwen3-VL vision BF16 rounding change: the op-by-op rounding design, the integer round-to-nearest-even with NaN guard, the contract and digest change, results, the revised acceptance criteria, and the remaining limits.
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 23, 2026
@inureyes
inureyes marked this pull request as ready for review November 23, 2026 16:16
@inureyes
inureyes merged commit 0804ce8 into main Nov 23, 2026
33 checks passed
@inureyes
inureyes deleted the update/issue-3291-qwen3vl-bf16-vision branch November 23, 2026 16:22
@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:architecture Architecture and code structure changes area:inference Generation, sampling, decoding (incl. speculative, DRY) priority:high High priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

update: run the XLA Qwen3-VL vision tower at eager's bf16 rounding boundaries

1 participant