Skip to content

fix(vision): rescale out-of-bounds images from the original size like the reference - #3466

Merged
inureyes merged 3 commits into
lablup:mainfrom
Jaeyeong-CHOI:fix/vision-resize-bounds-rescale-from-original
Nov 27, 2026
Merged

inureyes merged 3 commits into
lablup:mainfrom
Jaeyeong-CHOI:fix/vision-resize-bounds-rescale-from-original

Conversation

@Jaeyeong-CHOI

Copy link
Copy Markdown
Contributor

Summary

Closes #3465.

When an image's rounded size is outside [min_pixels, max_pixels], transformers' Qwen2-VL smart_resize scales the original height and width by beta = sqrt(h * w / max_pixels) (or min_pixels) and floors (or ceils) h / beta / factor once. Qwen2VLProcessor, Ernie45VlProcessor and DotsOcrProcessor rescaled the already rounded size instead, and often landed on a different multiple of the factor. This PR ports the reference's branch in those three processors and changes nothing for images inside the bounds.

On real checkpoints, an image that takes the branch now gets the reference's image-token count: Mage-VL-8bit at 3840x2160 3818 (was 3901), Qwen3-VL-2B at 320x180 66 (was 77), Qwen2.5-VL-3B at 40x30 6 (was 4) and at 96x24 4 (was 8). mlx-vlm's teacher-forced trace refuses main's prompt in all four cases (image-token count differs) and runs on the fix's, with no disagreement at a decided position. A 640x480 control is byte-identical between main and the fix on all three checkpoints.

This is independent of #3464 (tie rounding). It touches different lines, merges with be4aa4919 without conflicts, and no test input is an x.5 tie that the two rules round differently, so the expected values hold with or without it (both PRs' tests pass on the merged tree, see below).

What changed

  • src/vision/processors/qwen2_vl.rs, Qwen2VLProcessor::smart_resize: over max_pixels, beta = sqrt(orig_h * orig_w / max_pixels) and floor(orig_h / beta / factor) * factor (at least one factor); otherwise, under min_pixels, beta = sqrt(min_pixels / (orig_h * orig_w)) and ceil(orig_h * beta / factor) * factor. Both expressions keep the reference's operation order, the area is the exact u64 product, and the branches are if / else if as upstream. This replaces the old three steps (a half-away rescale of the rounded size, a second floor pass when that overshot, and an independent min_pixels pass). The initial round_to(.., 1.0, f64::round) lines are untouched.
  • In the same branch, only for an aspect ratio above 200:1 (where the reference raises ValueError instead of resizing): when the short edge has clamped to one factor and the area is still over max_pixels, the long edge is cut to max_pixels / short / factor multiples. This keeps max_image_tokens (the bound the XLA context floor in host_preprocessor.rs relies on) true for every image. Below 200:1 the reference's result is kept even when it overshoots a very small cap, as the reference does.
  • src/vision/processors/ernie4_5_vl.rs and src/vision/processors/dots_ocr.rs: the same branch from the original size, written like the existing Hunyuan-VL port (hunyuan_vl.rs:59-67). ERNIE's min_pixels check becomes an else if, as in the reference.
  • Tests, at the end of each file's tests module (see "Tests").

Qwen2VLProcessor sizes images for Qwen2-VL, Qwen2.5-VL, Qwen3-VL, Qwen3-VL-MoE, Qwen3.5-VL, Qwen3-Omni-MoE, Qwen4-Exp, GLM-4V, GLM-4V-MoE, GLM-OCR, Mage-VL, MiMo-V2 VL, Cohere Compass, ColQwen2.5 and the XLA Qwen host preprocessor, and Qwen-VL video frames go through the same function. No new shared helper, so no Used by: change.

Left alone on purpose: Hunyuan-VL, MiniMax-M3, LFM2-VL, PaddleOCR-VL, Falcon-OCR, Jina VLM, Mage-Flow and CLEF media already scale the original size. GLM-4V and GLM-OCR change with Qwen2VLProcessor, but their reference also multiplies the area by the temporal patch size and upsizes edges under factor first, so they match their reference neither before nor after (issue, "Deliberately left alone").

Verification

Spark2: NVIDIA GB10, CUDA 13.0.88, rustc 1.97.1, --features cuda, --profile test-fast, MLX_ENABLE_TF32=0 MLXCEL_SDPA_DETERMINISTIC=1. Base db3a231413a51f3c4c4a2a165b8e8a571f45293b (current main). Tested tree 6d1286d7292303c8a11d631de22882faf4d043dd, the tree of the commit (see the note under "Real checkpoints" for the one earlier tree).

  • 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 Spark2 and locally), 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
  • New tests, each run alone (cargo test --locked --profile test-fast --features cuda -p mlxcel --lib -- NAME --exact): 5 / 5 pass.
  • Related sets (-- FILTER --test-threads=1), all pass: qwen2_vl 18, qwen2_5_vl 16, qwen3_vl 62, qwen3_5 50, qwen_image_policy 13, qwen_vl 30, mage 960, glm4v 17, glm_ocr 9, colqwen 6, cohere_compass 30, mimo 38, ernie 81, dots_ocr 5, host_preprocessor 29 (includes qwen2_vl_image_floor_bounds_every_admissible_image), image_token_overrides 10, video 210, vlm_family_batched_decode 18, wrapper_native_batched_decode 10.
  • make verify-test-cuda with a private 0700 TMPDIR: 17,241 passed, 7 failed, 517 ignored (199 test result lines); the tree was the tested tree before and after (the same counts on the earlier tree fd60443b). The seven failures are the same on unmodified main: I reran exactly these seven tests from a build of db3a23141 with the gate's cargo invocation and all seven fail at the same lines with the same messages.

Tests

Test On main After
qwen2_vl::tests::smart_resize_rescales_out_of_bounds_images_from_the_original_size fails, left: (2660, 4760) right: (2688, 4760) (5120x2880 at the default bounds) passes
qwen2_vl::tests::smart_resize_in_bounds_and_agreeing_clamps_are_unchanged passes passes
qwen2_vl::tests::smart_resize_extreme_aspect_follows_the_reference_then_keeps_the_cap fails, left: (28, 2016) right: (28, 2240) (3000x30 under 64 tokens) passes
ernie4_5_vl::tests::smart_resize_rescales_out_of_bounds_images_from_the_original_size fails, left: (784, 1232) right: (784, 1260) (1680x1050) passes
dots_ocr::tests::smart_resize_rescales_out_of_bounds_images_from_the_original_size fails, left: (2744, 4088) right: (2716, 4088) (6000x4000) passes

The qwen2_vl out-of-bounds test pins the Qwen2.5-VL checkpoint bounds (5120x2880, 4782x2690, 5184x3456), the 1280-token cap (1372x772 to 728x1316, 4032x3024 to 840x1148), the Qwen3-VL bounds (100x177, 120x160, 180x320 on the min_pixels side, 6000x4000 on the max_pixels side) and the Mage-VL bounds (3840x2160 to 1472x2656, i.e. grid (1, 92, 166) and 3818 merged tokens; 6000x4000). The "unchanged" test pins in-bounds sizes and out-of-bounds sizes where both rules land on the same multiple. The extreme-aspect test pins the reference result for 3000x30 under max_pixels = 50176 (64 tokens, 100:1, where the reference does not raise) and checks that 16384x1, 1x16384 and 16000x40 under 256 tokens stay within the cap (main gives 28x8792 = 246,176 pixels for 16384x1 against a cap of 200,704).

Every expected value is the output of the reference function itself: smart_resize lifted verbatim (by AST) from transformers 5.24.1 (qwen2_vl/image_processing_pil_qwen2_vl.py, ernie4_5_vl_moe/image_processing_pil_ernie4_5_vl_moe.py) and mlx-vlm e8035ae3 (qwen3_vl/processing_qwen3_vl.py _smart_resize_image, ernie4_5_moe_vl/processing_ernie4_5_moe_vl.py) and executed. For the pinned inputs transformers and mlx-vlm agree. No pinned input is an x.5 tie with an even lower neighbour, so the two tie rules agree on all of them (2160 / 32 = 67.5 and 6000 / 32 = 187.5 round up under both).

Beyond the tests, a scratch test (not committed) printed the real function's result for 45 common sizes under six bound sets (270 pairs). On main it matched a Python transcription of main's code on all 270 and the reference on 205; the 65 differences are the 55 out-of-bounds pairs of the issue's survey plus 10 in-bounds x.5 ties (#3463). On the fix it matches the reference on all 260 other pairs; the remaining 10 are those ties.

On top of #3464

git merge-tree --write-tree of this commit and be4aa4919 gives tree 7d397942c0137beec6e56c72bdd72ebfc9f8635f without conflicts. On that tree (built and run on Spark2 the same way): this PR's 5 new tests and #3464's 10 new tests pass, all the related sets above pass, and the scratch test's 270 pairs equal the reference on every pair, ties included.

Real checkpoints

Checkpoints, by Hugging Face revision: mlx-community/Mage-VL-8bit 40dc28d825dfaf0dfdea374f39539475d5ee35f2, mlx-community/Qwen3-VL-2B-Instruct-4bit 9c4f5209e57b31f4b9dfba735de3fb983739c9cc, mlx-community/Qwen2.5-VL-3B-Instruct-4bit 46d4cf06a06ffc1a766c214174f9cbed2f45bcab, each with its own preprocessor_config.json bounds (Mage-VL 3136..4000000, Qwen3-VL 65536..16777216, Qwen2.5-VL 3136..12845056). Images are tests/fixtures/sam3/cats.png (640x480) resized with PIL bicubic to the sizes below.

mlxcel generate -m MODEL --image IMAGE -p "Describe the image." -n N --temp 0 on main and on the fix (separate binaries, different sha256, each built from its own tree), and mlx-vlm e8035ae3 (mlx 0.32.4, mlx-cuda-13 0.32.4, transformers 5.24.1, same GPU) preprocessing the same file through scripts/mlx_vlm_image_logit_trace.py:

Checkpoint Image Branch Image tokens main / fix / mlx-vlm Prompt tokens main / fix / mlx-vlm mlx-vlm on main's prompt
Mage-VL-8bit 3840x2160 max 3901 / 3818 / 3818 3926 / 3843 / 3843 refuses: image-token count differs: mlx-vlm 3818, mlxcel 3901
Qwen3-VL-2B 320x180 min 77 / 66 / 66 91 / 80 / 80 refuses: mlx-vlm 66, mlxcel 77
Qwen2.5-VL-3B 40x30 min 4 / 6 / 6 29 / 31 / 31 refuses: mlx-vlm 6, mlxcel 4
Qwen2.5-VL-3B 96x24 min 8 / 4 / 4 33 / 29 / 29 refuses: mlx-vlm 4, mlxcel 8
all three (control) 640x480 in bounds main = fix main = fix (Mage-VL 325, Qwen2.5-VL 416, Qwen3-VL 314) not run

On the fix, mlx-vlm's own preprocessing gives the same prompt length as mlxcel in all four cases (3843, 80, 31, 29), and the reference then scores mlxcel's prompt ids (--mlxcel-prompt). Teacher-forced on the fix's own greedy reply, reference in float32 (scripts/compare_logit_traces.py REF CANDIDATE --decided 2). The main row scores main's own prompt (its own image grid) against the same reference, so it measures how far main's distribution is from the reference's on the same continuation:

Case Arm Top-1 disagreement Decided (gap >= 2) Largest reference gap at a disagreement Logit delta on the reference's choice, p50 / p99 / max Perplexity vs reference
Mage-VL 3840x2160, 128 positions fix 1 / 128 0 / 55 0.209 0.068 / 0.203 / 0.221 -0.09%
main 0 / 128 0 / 55 none 0.166 / 0.541 / 0.656 -0.90%
Qwen3-VL 320x180, 128 positions fix 3 / 128 0 / 62 0.240 0.076 / 0.315 / 0.736 -0.67%
main 9 / 128 0 / 62 1.805 0.210 / 1.471 / 1.599 +5.08%
Qwen2.5-VL 40x30, 74 positions fix 4 / 74 0 / 26 0.736 0.127 / 1.628 / 1.628 -3.31%
main 8 / 74 0 / 26 1.000 0.188 / 3.932 / 3.932 +7.41%
Qwen2.5-VL 96x24, 26 positions fix 0 / 26 0 / 13 none 0.082 / 0.341 / 0.341 -0.73%
main 2 / 26 0 / 13 0.671 0.297 / 1.356 / 1.356 +5.84%

The greedy replies differ between main and the fix in three of the four cases (Mage-VL's 594-byte reply is identical). On the 640x480 controls, main and the fix give the same prompt ids, byte-identical trace rows (65, 64 and 64 rows) and identical replies on all three checkpoints.

The mlx-vlm reference ran through a small wrapper (ref_gpu.py, not part of this PR) that answers an empty attention window with an empty array, because mlx 0.32.4's CUDA backend hands every SDPA to cuDNN, which rejects a zero-length query. It skipped 28 empty windows in the Qwen2.5-VL 96x24 run and none in the other three.

The generate and trace binaries were built from tree fd60443b, an earlier version of this commit that differs only in one test doc comment. Rebuilt from the final tree 6d1286d7, mlxcel, mlxcel-server and logit_trace are byte-identical to them (same sha256).

Every model and reference process ran alone (never beside a build or the test gate) under a watchdog that stops it when MemAvailable drops under 25 GiB or its RSS passes a bound: 42 runs, peak RSS 4.96 GiB. Two runs were stopped, see the next section.

Verification limits

  • Qwen2.5-VL on the max_pixels side was not run. At its default bounds the branch needs more than 12.8 M pixels (5120x2880 gives about 65k patches and 16k image tokens). mlxcel generate on that image drove host MemAvailable under the 25 GiB floor on both main (43 s) and the fix (33 s), and the watchdog stopped it. That is a property of the Qwen2.5-VL vision path at 16k image tokens on this 121 GiB host, the same for both builds, and not investigated here. The Qwen2.5-VL max_pixels branch is covered by the unit tests only; the real-checkpoint Qwen2.5-VL runs are on the min_pixels side.
  • The trace comparison favours the fix on logit delta and perplexity in all four cases, and on top-1 in three. On Mage-VL 3840x2160 the fix has one top-1 disagreement (at a reference gap of 0.209) where main has none. No arm disagrees at a decided position anywhere, so the trace gate itself does not separate main and the fix. The image-token count, and the reference's refusal of main's prompt, do.
  • ERNIE 4.5 VL and dots.ocr are covered by unit tests against the reference functions only; neither checkpoint was run. Of the other Qwen2VLProcessor families only Qwen2.5-VL, Qwen3-VL and Mage-VL were run.
  • GLM-4V and GLM-OCR change with Qwen2VLProcessor for out-of-bounds images but did not match their reference before and do not now (the reference multiplies the area by the temporal patch size). Not run.
  • The aspect-ratio trim above 200:1 is mlxcel's own behaviour, because the reference raises there. A request with such an image now gets a resized image within the cap rather than an error.
  • Qwen-VL video frames go through the same smart_resize; no video was run.
  • Metal and ROCm were not built or run.

… the reference

When an image's rounded size falls outside [min_pixels, max_pixels],
transformers' Qwen2-VL `smart_resize` (and mlx-vlm's Qwen3-VL
`_smart_resize_image`, ERNIE 4.5 VL's `smart_resize`) computes
`beta = sqrt(h * w / max_pixels)` from the original height and width and
floors `h / beta / factor` once (`ceil(h * beta / factor)` under
`min_pixels`). Qwen2VLProcessor, Ernie45VlProcessor and DotsOcrProcessor
instead rescaled the already rounded size; Qwen2VLProcessor also rounded
that first pass half away and then floored a second time. The result is
often a different multiple of the factor: 1372x772 under 1003520 pixels
gives 756x1316 instead of 728x1316, a 4K screenshot on Mage-VL gets
3901 image tokens instead of 3818, a 320x180 thumbnail on Qwen3-VL 77
instead of 66.

Port the reference's branch in all three, keeping its operation order.
Qwen2VLProcessor serves the Qwen2/2.5/3/3.5-VL, Qwen3-Omni, Qwen4-Exp,
GLM-4V, GLM-OCR, Mage-VL, MiMo-V2, Cohere Compass and ColQwen2.5
families. Beyond 200:1, where the reference raises, it trims the long
side so the area stays under max_pixels, as `max_image_tokens` assumes.

Hunyuan-VL, MiniMax-M3, LFM2-VL, PaddleOCR-VL, Falcon-OCR, Jina VLM,
Mage-Flow and CLEF media already scale the original size and are
unchanged. GLM-4V and GLM-OCR share Qwen2VLProcessor but their reference
also multiplies the area by the temporal patch size; that is left alone.
@inureyes inureyes added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:medium Medium priority labels Nov 27, 2026
The out-of-bounds branch now derives `beta` from the original height and width. A zero edge (which the reference rejects with a ZeroDivisionError) made `beta` infinite in the `min_pixels` branch, so the other edge became `inf` and saturated to `u32::MAX` in Qwen2-VL and dots.ocr, or overflowed the `u32 * factor` multiply in ERNIE. The old code rescaled the rounded size, which is never zero, so this was a regression of the branch port. The rescale now treats a zero edge as one pixel in all three processors, with a test each.

Refs lablup#3465, lablup#3466
@inureyes

Copy link
Copy Markdown
Member

Hardening review

Target PR: #3466. Linked issue: #3465.

Findings

  • The ported branch matches transformers' smart_resize (qwen2_vl and ernie4_5_vl_moe) and mlx-vlm's Qwen3-VL _smart_resize_image: beta comes from the original height and width, floor over max_pixels, ceil under min_pixels, if / else if as upstream. The 200:1 trim only applies where the reference raises, and keeps max_image_tokens true.
  • Regression fixed in e84eb2d: a zero edge made beta infinite in the min_pixels branch (the old code rescaled the rounded size, which is never zero). Qwen2-VL and dots.ocr then saturated the other edge to u32::MAX (a multi-gigabyte resize target), and ERNIE overflowed u32 * factor. The rescale now treats a zero edge as one pixel; one test per processor (smart_resize_zero_edge_stays_bounded). The reference raises on a zero edge, so there is no parity value to match.
  • Merged origin/main (with fix(vision): round resize ties half to even in Qwen-VL and seven other processors #3464's tie rounding) into the branch in fc47e66; no conflicts, and both PRs' tests pass on the merged tree.
  • Large inputs: area is u64 (Qwen) or bounded by decodable image sizes (ERNIE, dots.ocr); extreme aspect ratios stay under the cap in Qwen. No new hot-path cost.

Left for follow-up (not changed)

  • The initial rounding clamps each edge to at least one factor before the bounds check, where transformers does not (round(h / factor) * factor can be 0). For an edge under factor / 2 the reference takes the min_pixels branch and mlxcel may not (10x1000 at factor 28: reference 28x560, mlxcel 28x1008). This pattern is shared with Hunyuan-VL and the other processors.
  • mlx-vlm's ERNIE port truncates with int() before ceil_by_factor and clamps the aspect ratio instead of raising, so it differs from transformers on some min_pixels inputs. This PR follows transformers.
  • Hunyuan-VL has the same zero-edge beta issue (pre-existing, not touched by this PR).

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,ernie4_5_vl,dots_ocr}, qwen2_5_vl, qwen3_vl, mage, glm4v, glm_ocr, host_preprocessor, image_token_overrides, colqwen, cohere_compass, mimo: all pass.

Remote CI was cancelled by maintainer decision. The CUDA real-checkpoint parity runs in the PR body were not repeated on this host.

@inureyes
inureyes merged commit 4688c38 into lablup:main Nov 27, 2026
29 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): Qwen-VL, ERNIE 4.5 VL and dots.ocr rescale out-of-bounds images from the rounded size instead of the original

2 participants