Repository navigation
fix(vision): RF-DETR, Muse Glimmer and Mage-VL-Cowork parity fixes - #3460
Merged
inureyes merged 3 commits intoNov 27, 2026
Merged
Conversation
Four vision-side fixes mlx-vlm landed for families mlxcel already ships. - RF-DETR: the projector's ConvX LayerNorms (every C2f cv1, cv2 and bottleneck conv, stored as `bn`) and the final projector norm load at eps 1e-6, rfdetr's channel LayerNorm default, instead of nn.LayerNorm's 1e-5 (Neywa-Labs/mlx-vlm#2709). Segmentation mask logits are upsampled with resize_bilinear_nhwc(.., align_corners false, no antialias) and kept at `> 0`, as rfdetr's PostProcess does, instead of bicubic (Neywa-Labs/mlx-vlm#2713). The other RF-DETR norms already matched and are unchanged. - Muse Glimmer: the reference samples the learned position table with meshgrid(pos_h, pos_w, indexing="xy"), so height and width swap roles in bilinear_indices_and_weights (Neywa-Labs/mlx-vlm#2746). The flattened order changes with them, so every non-square grid gets different embeddings; square grids are unchanged. The vision RoPE is not touched. - Mage-VL-Cowork: microsoft/Mage-VL-Cowork declares model_type "llava_onevision2" and stores the tower under bare `visual.*`. Detection and the registry aliases map it to Mage-VL, and remap_mage_vl_weight_key rewrites `visual.` to `vision_tower.` (Neywa-Labs/mlx-vlm#2636). Its preprocessor_config.json has the same pixel bounds and normalization keys as Mage-VL's. Its config states tie_word_embeddings nowhere, and its lm_head differs from embed_tokens (max |diff| 0.177). Transformers' Qwen3 config and mlx-vlm's Mage-VL config default to untied, the shared Qwen3 args to tied, so mage_vl_text_config now fills in the top-level flag or false. Without this the loaded model decoded through the embedding matrix. - Mage ViT: layernorm_pre, layer_norm1, layer_norm2 and the merger's ln_q go through layer_norm_f32 (f32 input, weight and bias, one rounding back to the activation dtype), and the MLP and merger GELUs through gelu_f32 (f32 upcast, one rounding), as upstream's tower does since ae763da4. The weights stay in their loaded dtype. The shared kernel in f16 or bf16 rounds the normalized value before the affine. The bridge GELU widens a half input through its f32 constants, but the CUDA build promotes bf16 with f32 to bf16, so on CUDA a bf16 activation ran the whole GELU in bf16. Tests: projector eps and the bilinear mask path for RF-DETR, the xy position-table order and an unchanged square grid for Muse Glimmer, Cowork detection, key remap and the untied default, and Mage LayerNorm/GELU rounding against an f32 reference in f16 and bf16. The mask test uses [[-1, 3.2], [3.2, -1]] rather than [[-1, 1], [1, -1]], which thresholds to the same plane under both resizes. Closes lablup#3236
Jaeyeong-CHOI
force-pushed
the
fix/3236-vision-parity-fixes
branch
from
November 27, 2026 02:42
e3d915d to
9f2116e
Compare
Contributor
Author
|
Rebased onto |
lablup#3456 moved the DeepSeek-OCR CLIP MLP activation from line 100 to line 106 of `deepseekocr_clip.rs`. This PR refreshes the line references of `docs/gelu-call-sites.md` row V42, so V54 is brought up to date in the same pass to keep the inventory consistent with the code after both land. Refs lablup#3236, Refs lablup#3460
Member
Hardening reviewTarget PR: #3460. Linked issue: #3236. FindingsEach change was checked against mlx-vlm
Validation (Mac Studio M3 Ultra, Metal, merged tree)Remote CI was cancelled by maintainer decision; the merge relies on the local checks below.
|
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 #3236.
Four vision-side fixes that mlx-vlm landed for families mlxcel already ships, in one PR as the issue asks: RF-DETR's projector LayerNorm eps and mask resize, Muse Glimmer's position-table axis order on non-square grids, loading
microsoft/Mage-VL-Cowork, and f32 LayerNorm/GELU in the Mage ViT. Each item's reproduction test failed onmain, and reverting any one production change fails its own test and no other. Item 3 needed one change beyond the issue text: Cowork loaded, but decoded through its embedding matrix until a Mage-VL config withouttie_word_embeddingswas read as untied (see "Where this differs from the issue text").With the change, on Spark2 (GB10, CUDA):
mlxcel detectmatch mlx-vlme8035ae3pixel for pixel (0 differing pixels on all four masks; main: 341, 398, 37 and 46 of 307,200). Raw logits against the same reference are within 3.6e-4 (base) and 6.1e-4 (seg); main is at 3.8e-3 and 4.4e-3.Unsupported model type: llava_onevision2. With the card's system prompt the greedy reply is<think>…</think>,Action: Click the Save button in the dialog.,<tool_call>{"name": "computer_use", "arguments": {"action": "screenshot"}}</tool_call>, which is the same tool call mlx-vlm produces for the same request. A teacher-forced trace against mlx-vlm f32 disagrees on top-1 at 1 of 87 positions, none decided.--decided 2gate does not separate them.What changed
src/vision/detection/rfdetr/layers.rs:ConvNorm::from_weightsloads itsbnLayerNorm at eps1.0e-6(was1.0e-5). This covers every projectorcv1,cv2and bottleneck conv;ConvNormhas no other user in RF-DETR (pp_doclayout_v3andrt_detr_v2have their ownConvNorm).src/vision/detection/rfdetr/projector.rs: the final normprojector.stages.0.1at1.0e-6.src/vision/detection/rfdetr/predictor.rs:decode_masksresizes the selected mask logits withresize_bilinear_nhwc(.., (height, width), false, false)instead ofresize_bicubic_nhwc, keeping the f32 cast and the> 0threshold.enc_output_norm1e-5, segmentation 1e-6) are unchanged.ConvNorm::norm_epsandProjector::norm_eps(#[cfg(test)]).src/vision/encoders/muse_glimmer_pos.rsbilinear_indices_and_weightsbindslet (h, w) = (w, h);inside the per-grid loop. The outer loop walks the grid width againsttable_hand the inner loop the grid height againsttable_w, which is upstream'smeshgrid(.., indexing="xy")order. Token count is unchanged;muse_2d_ropeis not touched.src/models/detection.rs:"mage_vl" | "llava_onevision2" => ModelType::MageVLM.src/models/registry.rs:llava_onevision2added toModelType::MageVLM's aliases.src/loading/vlm_mage_vl.rs:remap_mage_vl_weight_keymapsvisual.*tovision_tower.*after themodel.visual.arm.src/loading/vlm_mage_vl.rs:mage_vl_text_configfills intie_word_embeddingswhentext_configdoes not state it: the top-level boolean if there is one, otherwisefalse. Not in the issue; see below.preprocessor_config.jsonhas the samemin_pixels/max_pixels/image_mean/image_stdkeys and values as Mage-VL's, andvision_config(temporal_patch_size: 1,layer_norm_type: "layer_norm", hidden 1024, 16 heads,use_head: false) passesMageVlVisionConfig::validate.ae763da4):src/vision/encoders/mage_vl.rsgains privatelayer_norm_f32(casts input, weight and bias to f32, runs the fast layer norm through a temporaryLayerNorm, casts back to the input dtype) andgelu_f32(f32 upcast,mlxcel_core::gelu, cast back). They are used atlayernorm_pre,layer_norm1,layer_norm2, the merger'sln_q, and the SigLIP MLP and merger GELUs. Mage-ViT has nolayernorm_post(use_head: falseis refused at load), so there are four norm sites, not five. The weights stay in their loaded dtype, andmlxcel_core::layers::LayerNormis not changed.Docs:
CHANGELOG.md(Unreleased / Fixed), the Mage-VL entry indocs/supported-models.md(Cowork), and row V42 ofdocs/gelu-call-sites.md(new line numbers,gelu_f32). No shared helper gained a caller, so noUsed by:annotation changed;check_used_by.pypasses.Where this differs from the issue text
lm_head.weightamong the keys that "already pass through unchanged". They do, but Cowork's config statestie_word_embeddingsnowhere, and the shared Qwen3ModelArgsdefault it totrue, so the loaded model ignoredlm_headand decoded throughembed_tokens. In the checkpoint the two differ (max |diff| 0.177, mean 0.0078). Transformers'Qwen3Configand mlx-vlm's Mage-VLTextConfigboth default to untied, andmicrosoft/Mage-VLstatesfalse. Before this change the loaded Cowork model produced repetitive text that drifted into Chinese ("…changes belong belonging belong belonging…") on every greedy and sampled request, and a teacher-forced trace against mlx-vlm disagreed on top-1 at 42 of 87 positions (13 of 54 decided), perplexity 84.8 against the reference's 6.0. After it: 1 of 87, 0 decided, 5.97. Without this, item 3's acceptance ("a well-formed<tool_call>reply") was not met.[[-1, 1], [1, -1]]. Upsampled to 4x4, both bicubic and bilinear keep its sign pattern, so it thresholds to the same plane either way (computed, and checked on main: the test passed). The test uses[[-1, 3.2], [3.2, -1]], which differs at four pixels, and it asserts that the bicubic plane differs from the bilinear one, so a future change of input cannot make it vacuous.MLXCEL_CUDA_F16_NORMALIZEis set), and Mage-VL-8bit keeps a bf16 tower on every backend because the checkpoint is quantized. With f16 only, the GELU test showed thatmlxcel_core::gelualready rounds once from f32: its f32 constants promote a half input. bf16 is different on CUDA. The CUDA overlaysrc/lib/mlxcelverse/overlays/cuda/mlx/dtype.cpppromotes bf16 with f32 to bf16, so on CUDA a bf16 GELU ran entirely in bf16 (for examplegelu(-5)came out as-0where the f32-rounded value is about-1.4e-6). The GELU test asserts that today's path differs only for bf16 on CUDA, the one case where it can differ; on Metal and for f16 that path already matches.Verification
Spark2: NVIDIA GB10 (sm_121), Linux aarch64, pinned toolchain,
--features cuda,--profile test-fast,MLX_ENABLE_TF32=0 MLXCEL_SDPA_DETERMINISTIC=1. Basef74dd84eb923f42a95d212f5bbd666a00bcb914f. Tested tree15de7a6d084959bf150269c26201d4017505a039, the tree of the commit.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,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.pymake verify-test-cudawith a private 0700TMPDIR: 17,193 passed, 1 failed, 517 ignored over 197test resultlines (35 min). The tree was the tested tree before and after. The one failure ismodels::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)), the known CUDA failure on main (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). The same test, run alone from a build of unmodifiedf74dd84eb, fails with the same message and the samemax diff 1.6620973. The library target has 13,192 tests on main and 13,200 here.Tests
projector_norms_use_eps_1e6rfdetr/tests.rs1e-5!=1e-6)mask_resize_is_bilinear_half_pixelrfdetr/tests.rsposition_table_uses_xy_meshgrid_ordermuse_glimmer_pos.rs[0, 1, 2, 3, 8, 9, 10, 11])square_grid_position_table_is_unchangedmuse_glimmer_pos.rshub_and_converted_keys_remap_to_one_layout(extended)vlm_mage_vl_tests.rsvisual.merger.mlp.0.weightkept)text_config_without_a_tie_flag_is_untiedvlm_mage_vl_tests.rsllava_onevision2_detects_as_mage_vldetection_tests.rsUnsupported model type: llava_onevision2)mage_layer_norm_rounds_once_from_f32mage_vl_tests.rsmage_gelu_rounds_once_from_f32mage_vl_tests.rs"main" is
f74dd84ebwith the tests added and a#[cfg(test)]shim that mapslayer_norm_f32/gelu_f32to today'sLayerNorm::forward/mlxcel_core::gelu. The main run used the first version of the two Mage tests (f16 only). The bf16 rows were added after it, so on main the GELU test failed only its "today must differ" assertion; the bf16 failure is shown by the mutation below. The Glimmer expected arrays are the output of upstream's numpy code on those grids.Mutation: each production change reverted on its own, tests kept, lib test binary rebuilt each time.
projector_norms_use_eps_1e6mask_resize_is_bilinear_half_pixel(h, w)swapposition_table_uses_xy_meshgrid_orderllava_onevision2detection armllava_onevision2_detects_as_mage_vlvisual.remap armhub_and_converted_keys_remap_to_one_layoutunwrap_or(true))text_config_without_a_tie_flag_is_untiedlayer_norm_f32body ->ln.forward(x)mage_layer_norm_rounds_once_from_f32(f16)gelu_f32body ->mlxcel_core::gelu(x)mage_gelu_rounds_once_from_f32(bf16)Related sets on the fix tree (
cargo test -p mlxcel --lib -- FILTER --test-threads=1):rfdetr25 passed, 2 ignored;muse_glimmer122;mage961 passed, 41 ignored;detection_tests113;registry73;interpolate18. On main the same filters failed only on the new tests.Real checkpoints
All on Spark2, one model process at a time under a memory watchdog (stop below 25 GiB available or above an RSS bound). 66 watched runs, none stopped; the lowest available memory seen was 83.0 GiB and the largest process-group RSS 4.9 GiB (on GB10 unified memory CUDA allocations need not show in RSS, so the available-memory floor is the main guard). Reference: mlx-vlm
e8035ae3(mlx 0.32.4, CUDA), which contains #2709, #2713, #2746 and #2636.mlx-community/rfdetr-base-fp32eddb85a12c5996074fac2f2e769ca5e947bd80d3mlx-community/rfdetr-seg-small-fp32a7a2375b4ca7b2ef0427af91b55d8176ca647b35microsoft/Mage-VL-Cowork6fbe7f91da477c1c73790dbb1f08d001b8626be1mlx-community/Mage-VL-8bit40dc28d825dfaf0dfdea374f39539475d5ee35f2mlx-community/Muse-Glimmer-30B-4bit3e7677d7a40d348a3daba263a2b1c0aa41910710RF-DETR. The committed fixtures in
tests/fixtures/rfdetrwere generated with mlx-vlm4319ef2c, before #2709 / #2713. Re-running that predictor ate8035ae3with the two fixes reverted in-process reproduces them (identical masks, logits within 5.7e-4), so they are a pre-fix reference. New references were captured ate8035ae3as is ("post") and with the two fixes reverted ("pre"), samecats.pnginput.real_tests.rsasserts a ROCm backend, so the numbers below come from an evidence-only copy of it (not in this PR) that prints the metrics and feeds the reference's own input tensor (processor output was byte-identical in every run):Against the pre-fix reference the picture inverts (main: base logits 1.98e-4, masks 0 px; fix: 3.74e-3, 398/37/341/46 px). In every arm the selected queries, labels and NMS survivors match the reference, with scores within 5.4e-6.
The issue's command,
mlxcel detect -m rfdetr-seg-small-fp32 -i cats.png --format json --masks-dir …: fix masks equal the mlx-vlm post-fix masks exactly (IoU 1.000000 on all four); main's are 0.994565, 0.992694, 0.991578 and 0.979860. Main and fix print the same detections and labels oncats.pngand on a 1280x720 resize of it for both checkpoints (confidence differences at most 1.8e-4). Seg masks on the wide image differ by 1,020 / 1,170 / 128 / 120 pixels between the arms.Mage-VL-Cowork.
mlxcel generate -m Mage-VL-Cowork --image screenshot.png -p "Click the Save button." -n 256on a synthetic 1280x800 editor screenshot with a "Save changes to report.txt?" dialog: main exits withError: Unsupported model type: llava_onevision2, as doesmlxcel-server. With the fix it loads in 1.5 s (8.22 GB resident) and describes the dialog and the blue Save button, all in the reasoning channel (no system prompt, so no tool format). Throughmlxcel-serverwith the model card's verbatimMAGE_HYBRID_SYSTEM_PROMPTandTask: Click the Save button in the dialog.(2,122 prompt tokens, the same count mlx-vlm renders):Action: Click the Save button in the dialog., and the token stream (fromlogprobs) ends in<tool_call>\n{"name": "computer_use", "arguments": {"action": "screenshot"}}\n</tool_call>. mlx-vlm greedy on the same request emits the same<tool_call>line after a differently worded reasoning paragraph. Withouttoolsin the request the server leavestool_callsunset; with the two functions passed astoolsit returnsfinish_reason: tool_callsandcomputer_usewith{"action": "screenshot"}.temperature 0.7, top_p 0.8, seeds 0, 1 and 2: three coherent replies, each ending with anAction:line (129 to 163 tokens,finish_reason: stop).Teacher-forced trace (
MLXCEL_TRACE_IMAGE, promptClick the Save button., 87 forced tokens of a card-style reply) againstmlx_vlm_image_logit_trace.py --float32 --mlxcel-prompt, prompt ids identical (1,017):Mage-VL-8bit (no-regression check; main loads it):
Describe the image., 128 greedy tokens. On the 1280x720 image main and fix produce the same text. Oncats.png(640x480) they diverge at character 38 (pink couchvsred couch). Trace oncats.pngagainst mlx-vlm f32 (prompt ids identical, 325):The 1280x720 trace has no reference arm: mlx-vlm makes 880 image tokens and mlxcel 920, and the script refuses the pair. That difference is outside this PR; see "Verification limits".
Muse Glimmer (
Describe the image.). Reference without--float32: the 30B checkpoint dequantized to f32 is about 120 GB, more than the host, so the reference runs the 4-bit weights natively. mlx-vlm renders 2 more prompt tokens than mlxcel (1,259 vs 1,257 and 454 vs 452), so the reference scores mlxcel's ids (--mlxcel-prompt). Greedy text differs between main and fix from about the 40th character on both images.Verification limits
cats.pngthe fix has fewer undecided flips (1 vs 3) but larger logit deltas (p90 0.28 vs 0.20). The unit tests show the rounding difference exists in both half types; on these traces it sits below the decoder's own bf16 noise. Metal was not run, so the f16 tower path (Metal, unquantized checkpoint) was not measured on a real model.--decided 2) is 0 in both arms, and oncats.pngthe fix has more undecided top-1 flips (3 vs 1). The reference ran the 4-bit weights, not f32.action: screenshotin both mlxcel and mlx-vlm greedy, not a click on Save; the pass criterion is a well-formed<tool_call>, which both meet. The screenshot is synthetic. Under greedy the server stops after the call withfinish_reason: stopand notool_callsfield unlesstoolsis passed (existing server behaviour, not changed here).real_tests.rsis the ROCm-only parity test and was not run as committed); the video path; tensor parallelism.Qwen2VLProcessor::smart_resize(src/vision/processors/qwen2_vl.rs) rounds withf64::round, half away from zero; transformers and mlx-vlm use Pythonround, half to even. A 1280x720 image gives a 736x1280 grid here and 704x1280 upstream (920 vs 880 Mage-VL image tokens). This affects every family on that processor and is a separate issue.mainmoved toed7f31e46(two commits) while this was tested;git merge-treereports no conflict, and the tests were not re-run on the new base.