Skip to content

fix(vision): round resize ties half to even in Qwen-VL and seven other processors - #3464

Merged
inureyes merged 2 commits into
lablup:mainfrom
Jaeyeong-CHOI:fix/qwen-vl-smart-resize-half-even
Nov 27, 2026
Merged

inureyes merged 2 commits into
lablup:mainfrom
Jaeyeong-CHOI:fix/qwen-vl-smart-resize-half-even

Conversation

@Jaeyeong-CHOI

Copy link
Copy Markdown
Contributor

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'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 every edge with edge / factor = 2k + 0.5 got 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_even at 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 of f64::round where the reference uses Python's round. The repo already uses it for the same purpose in falcon_ocr.rs, imagegen/mage_flow/conditioner.rs and decision/clef_media.rs. The std method is the shared helper, so no new function and no Used by: roster were needed.

File What it serves Reference
src/vision/processors/qwen2_vl.rs, Qwen2VLProcessor::smart_resize, the initial rounding Qwen2-VL, Qwen2.5-VL, Qwen3-VL, Qwen3-VL-MoE, Qwen3.5/3.6/3.8, Qwen3-Omni-MoE, Qwen4-Exp, GLM-4V, GLM-4V-MoE, GLM-OCR, Mage-VL, MiMo-V2 VL, Cohere Compass, ColQwen2.5, the XLA Qwen host preprocessor, Qwen-VL video frames transformers qwen2_vl / glm4v smart_resize, mlx-vlm qwen3_vl _smart_resize_image / _smart_resize_video
src/vision/processors/hunyuan_vl.rs Hunyuan-VL transformers and mlx-vlm hunyuan_vl smart_resize
src/vision/processors/ernie4_5_vl.rs ERNIE 4.5 VL round_by_factor, transformers ernie4_5_vl_moe, mlx-vlm ernie4_5_moe_vl
src/vision/processors/minimax_m3.rs, round_by_factor MiniMax-M3-VL transformers and mlx-vlm minimax_m3_vl smart_resize
src/vision/processors/dots_ocr.rs dots.ocr transformers' Qwen2-VL image processor, which mlx-vlm dots_ocr loads
src/vision/processors/lfm2_vl.rs, smart_resize and is_image_too_large LFM2-VL round_by_factor, transformers and mlx-vlm lfm2_vl
src/vision/processors/nemotron_h_nano_omni.rs, compute_target_patches Nemotron-H Nano Omni mlx-vlm round(orig_h / self.patch_size + 0.5)
src/vision/processors/minicpmo.rs, ensure_divide (was integer half-up) MiniCPM-o, MiniCPM-V 4.6 max(round(length / patch_size) * patch_size, patch_size), mlx-vlm minicpmo, transformers minicpmv4_6

Not changed:

  • Youtu-VL, which rounds with ceil on purpose (fix(youtu_vl): match the AutoProcessor patch grid (36864 cap, ceil rounding) #1611).
  • Falcon-OCR, Jina VLM, PaddleOCR-VL, Mage-Flow, Qwen-Image and CLEF media, which already round half to even.
  • Muse Glimmer. Its reference rounds only in a fallback branch, and the mlxcel port is structured differently.
  • The clamp branches of 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. Base db3a231413a51f3c4c4a2a165b8e8a571f45293b. Tested tree 4e6a32517278ecd64d822c8ce8412d0eacfa3f0b, the tree of the commit (fmt/clippy, the fix binaries and the gate were all checked against it).

  • cargo fmt --all -- --check
  • cargo clippy --locked --workspace --all-targets --features cuda -- -D warnings
  • python3 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
  • The new tests, each run alone with --exact: 10 passed after the change; on main 9 failed and 1 passed (the guard below).
  • Related processor and model sets, cargo test --locked --profile test-fast --features cuda -p mlxcel --lib -- --test-threads=1 FILTER for qwen2_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. On main with only the new tests added, the only failures in these sets were the 9 new tie tests.
  • make verify-test-cuda with a private 0700 TMPDIR: 17,246 passed, 7 failed, 517 ignored (199 test result lines). 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:

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.

Test Tie cases (fail on main) Must not move
qwen2_vl::tests::smart_resize_breaks_ties_to_even_like_python_round factor 28: 854x480 -> 476x840 (main 476x868), 1200x630 -> 616x1204, 350x350 -> 336x336; factor 32 with 65536..16777216: 1280x720 -> 704x1280 (main 736x1280), 4032x3024 -> 3008x4032, 1680x1050 -> 1056x1664, 336x336 -> 320x320; compute_grid_thw of 1280x720 is (1, 44, 80)
qwen2_vl::tests::smart_resize_non_ties_and_odd_ties_are_unchanged 1920x1080, 640x480, 1680x1050 (37.5 -> 38) and 1050x700 at factor 28; 1920x1080 and 1920x1200 (37.5 -> 38) at factor 32. Passes on main too.
hunyuan_vl::tests::smart_resize_breaks_ties_to_even_like_python_round 1280x720 -> 704x1280 (main 736x1280), 1680x1050 -> 1056x1664 1920x1080, 1920x1200, 4032x3024 (max clamp) -> 1760x2336, 336x336 (min clamp) -> 512x512
ernie4_5_vl::tests::smart_resize_breaks_ties_to_even_like_python_round 854x480 -> 476x840 (main 476x868), 1200x630, 350x350 640x480, 1050x700
minimax_m3::tests::smart_resize_breaks_ties_to_even_like_python_round 854x480 -> 476x840 (main 476x868), 350x350 640x480, 1920x1080 (max clamp) -> 504x896
dots_ocr::tests::smart_resize_breaks_ties_to_even_like_python_round 854x480 -> 476x840 (main 476x868), 1200x630 1920x1080, 1680x1050
lfm2_vl::tests::smart_resize_breaks_ties_to_even_like_python_round 336x336 -> 320x320 (main 352x352), 600x400 -> 384x608 640x480, 1280x720 (max clamp)
lfm2_vl::tests::too_large_check_breaks_ties_to_even_like_python_round 720x720 and 784x656 stay single-tile (main split them) 752x720 and 784x688 split
nemotron_h_nano_omni::tests::compute_target_patches_breaks_ties_to_even_like_python_round 1024x1024 -> 64x64 patches (main 66x66), 640x480 -> 40x30 1280x720 -> 80x46, 496x496 -> 32x32
minicpmo::tests::ensure_divide_breaks_ties_to_even_like_python_round 35/14 -> 28 (main 42), 63/14 -> 56, 140/56 -> 112 49/14, 84/56, 36/14, 100/56, 5/14

Each test asserts its tie cases first, so a main failure stops at the first one. The other tie values were compared on main through a throwaway dump test that is not in this PR. It printed main'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

Checkpoint Hugging Face revision
mlx-community/Qwen2.5-VL-3B-Instruct-4bit 46d4cf06a06ffc1a766c214174f9cbed2f45bcab
mlx-community/Qwen3-VL-2B-Instruct-4bit 9c4f5209e57b31f4b9dfba735de3fb983739c9cc
mlx-community/Mage-VL-8bit 40dc28d825dfaf0dfdea374f39539475d5ee35f2

Images: 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, sha256 3c704707...e7a4dd) and to 854x480 (854 / 28 = 30.5, sha256 75f8a754...8708cf). Prompt Describe the image., mlxcel generate --temp 0 (128 tokens, 64 for cats.png) on a build of unmodified db3a23141 and on the fix.

Model, image Prompt tokens (main / fix / mlx-vlm) Image tokens (main / fix) Greedy reply, main vs fix
Mage-VL-8bit, 1280x720 945 / 905 / 905 920 / 880 different (617 / 577 bytes)
Qwen3-VL-2B, 1280x720 934 / 894 / 894 920 / 880 different (537 / 539 bytes)
Qwen2.5-VL-3B, 854x480 552 / 535 / 535 527 / 510 different (244 / 343 bytes)
Mage-VL-8bit, 640x480 325 / 325 identical ids identical (295 bytes)
Qwen2.5-VL-3B, 640x480 416 / 416 identical ids identical (295 bytes)

Teacher-forced traces (examples/logit_trace, MLXCEL_TRACE_IMAGE) of the fix build's greedy reply, against mlx-vlm e8035ae3 (mlx 0.32.4, mlx-cuda-13 0.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. The main row compares main's trace (its own longer prompt, the same reply tokens) with that same reference.

MLXCEL_TRACE_IMAGE=IMG MLXCEL_TRACE_IMAGE_PROMPT="Describe the image." logit_trace MODEL reply.txt 128 1 8 > fix.tsv
python scripts/mlx_vlm_image_logit_trace.py MODEL IMG fix.tsv --prompt "Describe the image." --float32 --mlxcel-prompt > ref.tsv
python3 scripts/compare_logit_traces.py ref.tsv fix.tsv --decided 2
Model, image Arm Top-1 disagreement Decided (gap >= 2.0) Largest reference gap at a disagreement Logit delta on the reference's choice, p50 / p99 / max Perplexity vs reference
Mage-VL-8bit, 1280x720 fix 2 / 128 0 / 60 0.184 0.065 / 0.255 / 0.325 1.5207 vs 1.5259 (-0.34%)
main 7 / 128 0 / 60 0.494 0.210 / 0.929 / 0.938 1.5635 vs 1.5259 (+2.46%)
Qwen3-VL-2B, 1280x720 fix 1 / 128 0 / 57 0.037 0.081 / 0.271 / 0.329 1.5902 vs 1.5891 (+0.07%)
main 13 / 128 0 / 57 0.611 0.272 / 1.799 / 2.664 1.6871 vs 1.5891 (+6.17%)
Qwen2.5-VL-3B, 854x480 fix 1 / 75 0 / 42 0.145 0.136 / 0.901 / 0.901 1.5278 vs 1.5258 (+0.13%)
main 10 / 75 0 / 42 0.794 0.427 / 3.364 / 3.364 1.7037 vs 1.5258 (+11.66%)

Run the same way on main's own prompt (Mage-VL-8bit, 1280x720), the reference still exits with image-token count differs: mlx-vlm 880, mlxcel 920; the prompts cannot share pixel features. On the two cats.png controls 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 (host MemAvailable floor 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

  • The clamp branches of Qwen2VLProcessor::smart_resize still differ from transformers, for a reason other than rounding. When the rounded size is over max_pixels or under min_pixels, mlxcel rescales the rounded size and rounds again, where transformers scales the original by beta and floors or ceils once. Measured with the real function on this tree (no tie involved, the same on main): 1372x772 at max_pixels = 1003520 gives (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 in Qwen2VLProcessor still calls f64::round, and I left it alone because the reference has no such step. This needs its own issue.
  • Real-checkpoint runs cover Qwen2.5-VL, Qwen3-VL and Mage-VL only. Hunyuan-VL, ERNIE 4.5 VL, MiniMax-M3, dots.ocr, LFM2-VL, Nemotron-H Nano Omni, MiniCPM-o / MiniCPM-V 4.6, GLM-4V and the other Qwen2VLProcessor families are covered by unit tests against their reference functions only.
  • The MiniMax-M3 port says it follows the checkpoint's own image_processor.py. I compared it with transformers' and mlx-vlm's minimax_m3_vl, not with that file.
  • MiniCPM-o's find_best_resize rounds the rescaled size with .round() where mlx-vlm and transformers truncate with int(). That is not a tie and is not changed here.
  • multimodal/video.rs::round_by_factor (the frame count for an explicit nframes) also rounds half away from zero. Its reference (qwen-vl-utils smart_nframes) is not installed on the test host, so it is not changed here.
  • The video path through Qwen2VLProcessor (frame size) is covered by the same function, but no video was run on a real checkpoint.
  • CUDA on one GB10 only. Metal, ROCm and the XLA builds were not run, but the change is host arithmetic with no backend-specific code.
  • No CHANGELOG.md entry, because the entry should carry the issue number.

…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.
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
@inureyes

Copy link
Copy Markdown
Member

Hardening review

Target PR: #3464. Linked issue: #3463.

Findings

  • The eight processor sites match the reference: each one ports a Python round(x / factor) (half to even), and round_ties_even is applied only there. The floor/ceil clamp branches and Youtu-VL's intentional ceil are untouched. Ties are detected exactly: every rounded quantity is an integer edge divided by a small integer factor (or + 0.5 for Nemotron) in f64, which is exact at x.5, the same arithmetic as Python floats. MiniCPM's rewritten ensure_divide is equivalent to max(round(L / d) * d, d) for every length.
  • Missed site with the same helper: multimodal/video.rs::round_by_factor, used for an explicit frame count (--video-num-frames, smart_nframes). The PR left it out because qwen-vl-utils was not installed; mlx-vlm's utils.py (_round(n) = round(n / frame_factor) * frame_factor) confirms it is Python round. With frame factor 2, every odd count with an even lower half was one factor too high (5 became 6 instead of 4; a 5-frame clip asked for 5 frames was rejected instead of sampling 4). Fixed in 572aac7 with a focused test. The existing out-of-range knob test asked for 301 of 300 frames, which the reference rounds to 300 and accepts, so it now asks for 303.
  • Not changed (out of scope, noted for a follow-up): frame index selection linspace(...).round() in video.rs and gemma4.rs uses f64::round where numpy rounds half to even, so some sampled indices differ by one frame on exact ties. This does not change token counts. The max-branch re-round in Qwen2VLProcessor is fix(vision): Qwen-VL, ERNIE 4.5 VL and dots.ocr rescale out-of-bounds images from the rounded size instead of the original #3465 / fix(vision): rescale out-of-bounds images from the original size like the reference #3466.

Security and performance

Host-side integer arithmetic only, no new allocation or hot-path cost. Out-of-range sizes behave as before (saturating u64 in Qwen, clamps elsewhere).

Validation (Mac Studio M3 Ultra, Metal)

  • cargo fmt --all -- --check: pass
  • cargo clippy -p mlxcel --all-targets --features metal,accelerate -- -D warnings: pass
  • cargo test -p mlxcel --lib --profile test-fast --features metal,accelerate -- <filter> --test-threads=1 for vision::processors::{qwen2_vl,hunyuan_vl,ernie4_5_vl,minimax_m3,dots_ocr,lfm2_vl,minicpmo,nemotron_h_nano_omni}, video, nframes, num_frames: all pass (8, 2, 3, 5, 3, 15, 6, 6, 211, 13, 6).

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.

@inureyes
inureyes merged commit 2b34a2f into lablup:main Nov 27, 2026
30 of 33 checks passed
@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

priority:medium Medium priority status:review Under review type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(vision): smart_resize rounds x.5 ties away from zero where the reference rounds half to even

2 participants