Repository navigation
fix(vision): round resize ties half to even in Qwen-VL and seven other processors - #3464
Merged
inureyes merged 2 commits intoNov 27, 2026
Merged
Conversation
…r processors
transformers' Qwen2-VL `smart_resize` and the processors of several other
families snap each edge to the patch grid with Python's
`round(edge / factor) * factor`, which breaks a tie towards the even
integer. mlxcel ported those lines with `f64::round` (half away from zero),
so whenever `edge / factor` is exactly `2k + 0.5` the grid gained one row or
column of merged patches. With factor 32 every 720-pixel edge is a tie: a
1280x720 image got 920 Qwen3-VL / Mage-VL image tokens where mlx-vlm and
transformers use 880, and the mlx-vlm teacher-forced trace refused to run
("image-token count differs"). With factor 28, 854x480 got 527 instead of
510.
Use `f64::round_ties_even` where the reference uses Python's `round`:
- `Qwen2VLProcessor::smart_resize`, the initial rounding (Qwen2-VL,
Qwen2.5-VL, the Qwen3-VL generation, Qwen3-Omni, Qwen4-Exp, GLM-4V,
GLM-OCR, Mage-VL, MiMo-V2 VL, Cohere Compass, ColQwen2.5, the XLA host
preprocessor and the Qwen-VL video frame resize)
- Hunyuan-VL, ERNIE 4.5 VL, MiniMax-M3, dots.ocr and LFM2-VL (`smart_resize`
and the single-tile check), whose `round_by_factor` is the same rule
- Nemotron-H Nano Omni `compute_target_patches` (`round(edge / patch + 0.5)`,
so 1024x1024 is 64x64 patches, not 66x66)
- MiniCPM-o / MiniCPM-V 4.6 `ensure_divide`, which rounded half up in
integer arithmetic
Only exact ties move; non-tie sizes and ties whose lower neighbour is odd
round the same under both rules. Youtu-VL keeps its deliberate `ceil`
(lablup#1611); Falcon-OCR, Jina VLM, PaddleOCR-VL, Mage-Flow and CLEF media already
rounded half to even. The clamp branches of `Qwen2VLProcessor::smart_resize`
(rescale after rounding, where transformers rescales the original size) are a
separate difference and are not changed here.
Each processor gets a test that pins tie cases to the value the reference
function returns (fails before this change) and non-tie / odd-tie cases that
must not move.
This was referenced Nov 26, 2026
The explicit `nframes` path of `smart_nframes` rounds with `round_by_factor`, the same `round(n / factor) * factor` helper the image processors in this PR use. Its reference (mlx-vlm `utils.py` `_round`, qwen-vl-utils `round_by_factor`) uses Python's half-to-even `round`, so an odd frame count that lands on an even tie went one factor too high: 5 frames at factor 2 became 6 instead of 4, and a 5-frame clip asked for 5 frames was rejected as out of range instead of sampling 4. The out-of-range frame-knob test asked for 301 of 300 frames, which now rounds to 300 as in the reference; it asks for 303 instead. Refs lablup#3463, lablup#3464
Member
Hardening reviewTarget PR: #3464. Linked issue: #3463. Findings
Security and performanceHost-side integer arithmetic only, no new allocation or hot-path cost. Out-of-range sizes behave as before (saturating Validation (Mac Studio M3 Ultra, Metal)
Remote CI for the follow-up push was cancelled by maintainer decision; the PR's earlier CI run on be4aa49 passed. The CUDA real-checkpoint parity runs in the PR body were not repeated here. |
This was referenced Nov 27, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Closes #3463
transformers' Qwen2-VL
smart_resize, and the processors of seven other families, snap an image edge to the patch grid with Python'sround(edge / factor) * factor, which breaks a tie towards the even integer. mlxcel ported those lines withf64::round(half away from zero), so every edge withedge / factor = 2k + 0.5got one extra row or column of merged patches. With factor 32 that is every 720-pixel edge: a 1280x720 image gave Qwen3-VL and Mage-VL 920 image tokens where transformers and mlx-vlm use 880, and the mlx-vlm teacher-forced trace refused to compare the two (image-token count differs: mlx-vlm 880, mlxcel 920). With factor 28, 854x480 gave Qwen2.5-VL 527 instead of 510.This PR uses
f64::round_ties_evenat every one of those lines. Only exact ties move. With the fix, all three tie cases tested on real checkpoints have the same image-token count as mlx-vlm, the reference trace runs, and there are 0 decided-position disagreements.main, scored against the same reference, is further off on every summary number (top-1 2 vs 7, 1 vs 10, 1 vs 13 disagreements; perplexity delta -0.34% / +0.13% / +0.07% vs +2.46% / +11.66% / +6.17%). Images without a tie give byte-identical prompts and traces.What changed
f64::round_ties_even(Rust 1.77) in place off64::roundwhere the reference uses Python'sround. The repo already uses it for the same purpose infalcon_ocr.rs,imagegen/mage_flow/conditioner.rsanddecision/clef_media.rs. The std method is the shared helper, so no new function and noUsed by:roster were needed.src/vision/processors/qwen2_vl.rs,Qwen2VLProcessor::smart_resize, the initial roundingqwen2_vl/glm4vsmart_resize, mlx-vlmqwen3_vl_smart_resize_image/_smart_resize_videosrc/vision/processors/hunyuan_vl.rshunyuan_vlsmart_resizesrc/vision/processors/ernie4_5_vl.rsround_by_factor, transformersernie4_5_vl_moe, mlx-vlmernie4_5_moe_vlsrc/vision/processors/minimax_m3.rs,round_by_factorminimax_m3_vlsmart_resizesrc/vision/processors/dots_ocr.rsdots_ocrloadssrc/vision/processors/lfm2_vl.rs,smart_resizeandis_image_too_largeround_by_factor, transformers and mlx-vlmlfm2_vlsrc/vision/processors/nemotron_h_nano_omni.rs,compute_target_patchesround(orig_h / self.patch_size + 0.5)src/vision/processors/minicpmo.rs,ensure_divide(was integer half-up)max(round(length / patch_size) * patch_size, patch_size), mlx-vlmminicpmo, transformersminicpmv4_6Not changed:
ceilon purpose (fix(youtu_vl): match the AutoProcessor patch grid (36864 cap, ceil rounding) #1611).Qwen2VLProcessor::smart_resize. These rescale the already rounded size where transformers rescales the original, which is a separate difference; see "Verification limits".Verification
Spark2: NVIDIA GB10, driver 580.178.04, CUDA 13.0.88, Linux 7.0.0-1019-nvidia aarch64, rustc 1.97.1 (the pinned toolchain),
--features cuda,--profile test-fast,MLX_ENABLE_TF32=0 MLXCEL_SDPA_DETERMINISTIC=1. Basedb3a231413a51f3c4c4a2a165b8e8a571f45293b. Tested tree4e6a32517278ecd64d822c8ce8412d0eacfa3f0b, the tree of the commit (fmt/clippy, the fix binaries and the gate were all checked against it).cargo fmt --all -- --checkcargo clippy --locked --workspace --all-targets --features cuda -- -D warningspython3 scripts/ci/check_used_by.py,bash scripts/ci/check_used_by_test.sh(on the GB10 host and on macOS),python3 scripts/insert_apache_header.py --check,python3 scripts/ci/check_env_var_docs.py,python3 scripts/ci/check_kernel_dtype_keys.py,python3 scripts/ci/check_cross_repo_refs.py--exact: 10 passed after the change; onmain9 failed and 1 passed (the guard below).cargo test --locked --profile test-fast --features cuda -p mlxcel --lib -- --test-threads=1 FILTERforqwen2_vl qwen2_5_vl qwen3_vl qwen3_5 qwen_image_policy qwen_vl mage glm4v glm_ocr colqwen cohere_compass mimo hunyuan ernie minimax dots_ocr lfm2 nemotron_h_nano_omni minicpm host_preprocessor clef image_token_overrides video: all 23 filters pass. Onmainwith only the new tests added, the only failures in these sets were the 9 new tie tests.make verify-test-cudawith a private 0700TMPDIR: 17,246 passed, 7 failed, 517 ignored (199test resultlines). The tree was the tested tree before and after the run. None of the 7 failures involve this change, and each also fails on unmodified main:models::deepseek_v32::rope_tests::prefill_and_decode_cache_yarn_rotated_keys_past_the_original_context(cached k_pe at positions 16..24 must be YaRN-rotated (max diff 1.6620973)), fix(cuda): MLX CUDA RoPE gives every row of a broadcast input the same rotation, failingmake verify-test-cudaon main #3442, fix in fix(cuda): rotate broadcast RoPE inputs in a dense output #3443.models::raon1_mini::speculative::tests::{a_steered_verify_block_applies_the_alpha_exactly_as_decode_does, a_verify_block_equals_the_decode_chain_byte_for_byte, rollback_after_a_partial_accept_equals_a_fresh_decode_of_the_accepted_tokens, the_exactness_probe_passes_on_the_tiny_model}. They panic atraon1_mini_speculative_tests.rs:115, 115, 203, 154, the same lines as an earlier main-only run on this host atd43915faf, andsrc/modelsis unchanged between that commit and this base. Tracked by the maintainers (fix: Raon-1 mini correctness and validation follow-ups #3457).mlxcel-xlavalidation::tests::{emit_all_reproduces_registered_goldens, registered_fixtures_are_byte_exact}:arch plamo2: FAIL, withprefill.mlirandprefill_logits.mlirfirst differing at line 231 (955 golden lines vs 1015 emitted; 939 vs 999). Rerun on unmodifieddb3a23141, both fail with the same message. The Plamo2 goldens came in with feat(xla): add Plamo2 hybrid support #3449 (01e6516b7), and fix(xla): replace the reduce_window cumsum in the Mamba2 SSD scan #3434 (db3a23141) then replaced the prefill scan and regenerated only the Nemotron-H and Falcon-H1 goldens.mlxcel-xladoes not depend on the files this PR touches.Tests
Every expected value is what the reference function returns for that input. The function was lifted verbatim (by AST) from transformers 5.24.1 and mlx-vlm
e8035ae3, then executed. The refenv has no torch, so the transformers modules could not be imported whole.main)qwen2_vl::tests::smart_resize_breaks_ties_to_even_like_python_roundmain476x868), 1200x630 -> 616x1204, 350x350 -> 336x336; factor 32 with 65536..16777216: 1280x720 -> 704x1280 (main736x1280), 4032x3024 -> 3008x4032, 1680x1050 -> 1056x1664, 336x336 -> 320x320;compute_grid_thwof 1280x720 is(1, 44, 80)qwen2_vl::tests::smart_resize_non_ties_and_odd_ties_are_unchangedmaintoo.hunyuan_vl::tests::smart_resize_breaks_ties_to_even_like_python_roundmain736x1280), 1680x1050 -> 1056x1664ernie4_5_vl::tests::smart_resize_breaks_ties_to_even_like_python_roundmain476x868), 1200x630, 350x350minimax_m3::tests::smart_resize_breaks_ties_to_even_like_python_roundmain476x868), 350x350dots_ocr::tests::smart_resize_breaks_ties_to_even_like_python_roundmain476x868), 1200x630lfm2_vl::tests::smart_resize_breaks_ties_to_even_like_python_roundmain352x352), 600x400 -> 384x608lfm2_vl::tests::too_large_check_breaks_ties_to_even_like_python_roundmainsplit them)nemotron_h_nano_omni::tests::compute_target_patches_breaks_ties_to_even_like_python_roundmain66x66), 640x480 -> 40x30minicpmo::tests::ensure_divide_breaks_ties_to_even_like_python_roundmain42), 63/14 -> 56, 140/56 -> 112Each test asserts its tie cases first, so a
mainfailure stops at the first one. The other tie values were compared onmainthrough a throwaway dump test that is not in this PR. It printedmain's Qwen2-VL results for every input above, and all of them are the half-away values.Real checkpoints, main against fix against mlx-vlm
mlx-community/Qwen2.5-VL-3B-Instruct-4bit46d4cf06a06ffc1a766c214174f9cbed2f45bcabmlx-community/Qwen3-VL-2B-Instruct-4bit9c4f5209e57b31f4b9dfba735de3fb983739c9ccmlx-community/Mage-VL-8bit40dc28d825dfaf0dfdea374f39539475d5ee35f2Images:
tests/fixtures/sam3/cats.png(640x480, no tie at factor 28 or 32), and the same photo resized with PIL Lanczos to 1280x720 (720 / 32 = 22.5, sha2563c704707...e7a4dd) and to 854x480 (854 / 28 = 30.5, sha25675f8a754...8708cf). PromptDescribe the image.,mlxcel generate --temp 0(128 tokens, 64 forcats.png) on a build of unmodifieddb3a23141and on the fix.Teacher-forced traces (
examples/logit_trace,MLXCEL_TRACE_IMAGE) of the fix build's greedy reply, against mlx-vlme8035ae3(mlx 0.32.4,mlx-cuda-130.32.4, mlx-lm 0.32.2, transformers 5.24.1) on the same GPU with--float32. The reference scores the fix trace's prompt ids (--mlxcel-prompt). It preprocesses the image itself and refuses when its image-token count differs. Themainrow comparesmain's trace (its own longer prompt, the same reply tokens) with that same reference.Run the same way on
main's own prompt (Mage-VL-8bit, 1280x720), the reference still exits withimage-token count differs: mlx-vlm 880, mlxcel 920; the prompts cannot share pixel features. On the twocats.pngcontrols the main and fix traces are byte-identical row for row (65 and 64 rows) and the prompt ids are identical.The reference ran through
ref_gpu.py, a small wrapper that is not part of this PR. It answers a zero-length attention query with an empty array, because mlx 0.32.4's CUDA backend hands every SDPA to cuDNN, which rejects one. The wrapper reported 0 empty windows on these runs, so the stock forward was used throughout. Every model and reference process ran under a watchdog (hostMemAvailablefloor 25 GiB, RSS bound 16 or 32 GiB): 24 runs, 0 trips, minimum available 86.7 GiB, largest RSS 5.2 GiB. No cargo build ran at the same time.Verification limits
Qwen2VLProcessor::smart_resizestill differ from transformers, for a reason other than rounding. When the rounded size is overmax_pixelsor undermin_pixels, mlxcel rescales the rounded size and rounds again, where transformers scales the original bybetaand floors or ceils once. Measured with the real function on this tree (no tie involved, the same onmain): 1372x772 atmax_pixels = 1003520gives (756, 1316) against (728, 1316); 4782x2690 at the defaults gives (2660, 4760) against (2688, 4760); 177x100 at the Qwen3-VL bounds gives (192, 384) against (224, 352). ERNIE (1680x1050: (784, 1232) vs (784, 1260)) and dots.ocr (6000x4000: (2744, 4088) vs (2716, 4088)) have the same shape. The max-branch re-round inQwen2VLProcessorstill callsf64::round, and I left it alone because the reference has no such step. This needs its own issue.Qwen2VLProcessorfamilies are covered by unit tests against their reference functions only.image_processor.py. I compared it with transformers' and mlx-vlm'sminimax_m3_vl, not with that file.find_best_resizerounds the rescaled size with.round()where mlx-vlm and transformers truncate withint(). That is not a tie and is not changed here.multimodal/video.rs::round_by_factor(the frame count for an explicitnframes) also rounds half away from zero. Its reference (qwen-vl-utilssmart_nframes) is not installed on the test host, so it is not changed here.Qwen2VLProcessor(frame size) is covered by the same function, but no video was run on a real checkpoint.CHANGELOG.mdentry, because the entry should carry the issue number.