Repository navigation
fix(vision): rescale out-of-bounds images from the original size like the reference - #3466
Merged
inureyes merged 3 commits intoNov 27, 2026
Conversation
… 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.
3 of 4 tasks
5 of 6 tasks
…nds-rescale-from-original
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
Member
Hardening reviewTarget PR: #3466. Linked issue: #3465. Findings
Left for follow-up (not changed)
Validation (Mac Studio M3 Ultra, Metal)
Remote CI was cancelled by maintainer decision. The CUDA real-checkpoint parity runs in the PR body were not repeated on this host. |
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 #3465.
When an image's rounded size is outside
[min_pixels, max_pixels], transformers' Qwen2-VLsmart_resizescales the original height and width bybeta = sqrt(h * w / max_pixels)(ormin_pixels) and floors (or ceils)h / beta / factoronce.Qwen2VLProcessor,Ernie45VlProcessorandDotsOcrProcessorrescaled 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 betweenmainand the fix on all three checkpoints.This is independent of #3464 (tie rounding). It touches different lines, merges with
be4aa4919without conflicts, and no test input is anx.5tie 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: overmax_pixels,beta = sqrt(orig_h * orig_w / max_pixels)andfloor(orig_h / beta / factor) * factor(at least onefactor); otherwise, undermin_pixels,beta = sqrt(min_pixels / (orig_h * orig_w))andceil(orig_h * beta / factor) * factor. Both expressions keep the reference's operation order, the area is the exactu64product, and the branches areif/else ifas upstream. This replaces the old three steps (a half-away rescale of the rounded size, a secondfloorpass when that overshot, and an independentmin_pixelspass). The initialround_to(.., 1.0, f64::round)lines are untouched.ValueErrorinstead of resizing): when the short edge has clamped to onefactorand the area is still overmax_pixels, the long edge is cut tomax_pixels / short / factormultiples. This keepsmax_image_tokens(the bound the XLA context floor inhost_preprocessor.rsrelies 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.rsandsrc/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'smin_pixelscheck becomes anelse if, as in the reference.testsmodule (see "Tests").Qwen2VLProcessorsizes 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 noUsed 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 underfactorfirst, 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. Basedb3a231413a51f3c4c4a2a165b8e8a571f45293b(currentmain). Tested tree6d1286d7292303c8a11d631de22882faf4d043dd, the tree of the commit (see the note under "Real checkpoints" for the one earlier tree).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 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.pycargo test --locked --profile test-fast --features cuda -p mlxcel --lib -- NAME --exact): 5 / 5 pass.-- FILTER --test-threads=1), all pass:qwen2_vl18,qwen2_5_vl16,qwen3_vl62,qwen3_550,qwen_image_policy13,qwen_vl30,mage960,glm4v17,glm_ocr9,colqwen6,cohere_compass30,mimo38,ernie81,dots_ocr5,host_preprocessor29 (includesqwen2_vl_image_floor_bounds_every_admissible_image),image_token_overrides10,video210,vlm_family_batched_decode18,wrapper_native_batched_decode10.make verify-test-cudawith a private 0700TMPDIR: 17,241 passed, 7 failed, 517 ignored (199test resultlines); the tree was the tested tree before and after (the same counts on the earlier treefd60443b). The seven failures are the same on unmodifiedmain: I reran exactly these seven tests from a build ofdb3a23141with the gate's cargo invocation and all seven fail at the same lines with the same messages.models::deepseek_v32::rope_tests::prefill_and_decode_cache_yarn_rotated_keys_past_the_original_context(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(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}, tracked in fix: Raon-1 mini correctness and validation follow-ups #3457.mlxcel-xlavalidation::tests::{emit_all_reproduces_registered_goldens, registered_fixtures_are_byte_exact}(plamo2/prefill.mlir re-emits its golden,arch plamo2: FAIL). Not touched by this change (nomlxcel-xlafile changes); I did not find an issue for it.Tests
mainqwen2_vl::tests::smart_resize_rescales_out_of_bounds_images_from_the_original_sizeleft: (2660, 4760) right: (2688, 4760)(5120x2880 at the default bounds)qwen2_vl::tests::smart_resize_in_bounds_and_agreeing_clamps_are_unchangedqwen2_vl::tests::smart_resize_extreme_aspect_follows_the_reference_then_keeps_the_capleft: (28, 2016) right: (28, 2240)(3000x30 under 64 tokens)ernie4_5_vl::tests::smart_resize_rescales_out_of_bounds_images_from_the_original_sizeleft: (784, 1232) right: (784, 1260)(1680x1050)dots_ocr::tests::smart_resize_rescales_out_of_bounds_images_from_the_original_sizeleft: (2744, 4088) right: (2716, 4088)(6000x4000)The
qwen2_vlout-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 themin_pixelsside, 6000x4000 on themax_pixelsside) 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 undermax_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 (maingives 28x8792 = 246,176 pixels for 16384x1 against a cap of 200,704).Every expected value is the output of the reference function itself:
smart_resizelifted 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-vlme8035ae3(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 anx.5tie 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
mainit matched a Python transcription ofmain'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-boundsx.5ties (#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-treeof this commit andbe4aa4919gives tree7d397942c0137beec6e56c72bdd72ebfc9f8635fwithout 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-8bit40dc28d825dfaf0dfdea374f39539475d5ee35f2,mlx-community/Qwen3-VL-2B-Instruct-4bit9c4f5209e57b31f4b9dfba735de3fb983739c9cc,mlx-community/Qwen2.5-VL-3B-Instruct-4bit46d4cf06a06ffc1a766c214174f9cbed2f45bcab, each with its ownpreprocessor_config.jsonbounds (Mage-VL 3136..4000000, Qwen3-VL 65536..16777216, Qwen2.5-VL 3136..12845056). Images aretests/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 0onmainand on the fix (separate binaries, different sha256, each built from its own tree), and mlx-vlme8035ae3(mlx 0.32.4,mlx-cuda-130.32.4, transformers 5.24.1, same GPU) preprocessing the same file throughscripts/mlx_vlm_image_logit_trace.py:main/ fix / mlx-vlmmain/ fix / mlx-vlmmain's promptimage-token count differs: mlx-vlm 3818, mlxcel 3901mlx-vlm 66, mlxcel 77mlx-vlm 6, mlxcel 4mlx-vlm 4, mlxcel 8main= fixmain= fix (Mage-VL 325, Qwen2.5-VL 416, Qwen3-VL 314)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). Themainrow scoresmain's own prompt (its own image grid) against the same reference, so it measures how farmain's distribution is from the reference's on the same continuation:mainmainmainmainThe greedy replies differ between
mainand the fix in three of the four cases (Mage-VL's 594-byte reply is identical). On the 640x480 controls,mainand 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
generateand trace binaries were built from treefd60443b, an earlier version of this commit that differs only in one test doc comment. Rebuilt from the final tree6d1286d7,mlxcel,mlxcel-serverandlogit_traceare 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
MemAvailabledrops 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
max_pixelsside 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 generateon that image drove hostMemAvailableunder the 25 GiB floor on bothmain(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-VLmax_pixelsbranch is covered by the unit tests only; the real-checkpoint Qwen2.5-VL runs are on themin_pixelsside.mainhas none. No arm disagrees at a decided position anywhere, so the trace gate itself does not separatemainand the fix. The image-token count, and the reference's refusal ofmain's prompt, do.Qwen2VLProcessorfamilies only Qwen2.5-VL, Qwen3-VL and Mage-VL were run.Qwen2VLProcessorfor 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.smart_resize; no video was run.