Repository navigation
fix: harden MiniCPM-V 4.6 image grid handling - #83
Merged
Merged
Conversation
Harden MiniCPM-V 4.6 dynamic image grid preprocessing and prompt placeholder spans so multi-image and non-square inputs produce correct per-image visual-token counts. Previously the MiniCPM-V 4.6 path assumed a single fixed `image_feature_size` for every image when building prompt placeholders, and the encoder did not validate that the spatial grid was divisible by the merge and window group sizes. With dynamic-resolution inputs (multiple images, or aspect ratios that resize to different grids) this produced placeholder spans that did not match the number of visual tokens each image actually yields, and could feed a non-divisible grid into the VitMerger and Merger. Changes: - Build prompt placeholders from a per-image feature size derived from each preprocessed image. `prepare_minicpmo_prompt_tokens_with_image_feature_sizes` takes a slice of per-image feature sizes instead of one shared size times the image count, and the MiniCPM-V 4.6 runtime arm now preprocesses images first, derives each image's feature size via `image_feature_size_for_processed`, and threads the slice through. - Add a divisibility guard in the encoder: the Merger and VitMerger reject a spatial grid that is not a multiple of their merge and window group sizes, instead of silently producing a misshapen tensor. - Align the image processor's best-resize search to the MiniCPM-V 4.6 downsample factor so the chosen grid is always compatible with the two-stage visual compression. Verified with cargo fmt, cargo clippy (metal,accelerate, all-targets, -D warnings), and 22 unit tests covering per-image feature sizes, placeholder span computation, the grid divisibility guards, and patch and downsample aligned resizing.
sjswerdloff
added a commit
to sjswerdloff/mlxcel
that referenced
this pull request
Jun 25, 2026
build_msa_unified_mask_asymmetric generalises cycle 64's unified mask to num_query_blocks ≠ num_key_blocks. p_q starts at cache_offset; p_k in [0, num_key_blocks * block_size). The 'p_k > p_q ⇒ invalid' rule from cycle 64 still subsumes within-block causality, future-block leakage, divisibility padding — AND now cached-prefix causality. 7 unit tests at small asymmetric fixtures (b=1, num_kv_heads=2, n_rep=2, num_query_blocks=2, num_key_blocks=4, cache_offset=4, block_size=2, top_k=2). Including an exhaustive 64-position hand-computed reference check. The 7 symmetric tests from cycle 65 still pass — no regression. Cycle 65's HF reference comment at line 267 cited num_key_blocks vs k_len; the implementation read l (q_len) from x.shape[1] without honouring the distinction. The latent comment 'Unreachable under default prefill_chunk_size=512, hence latent until now' from cycle 65 was the flag that should have driven this work then. It does now. First piece of the 6-task proper-fix sequence (lablup#78-lablup#83). No call sites updated yet — the new function is dead code until lablup#79 wires it into sparse_sdpa.
sjswerdloff
added a commit
to sjswerdloff/mlxcel
that referenced
this pull request
Jun 25, 2026
The architectural completion: SparseAttention::forward() now correctly handles chunked-prefill / cached cases. Key changes: - Compute kv_len = cache_offset + l BEFORE update_and_fetch, so the asymmetric block counts are derived from the FULL cached length, not just the current chunk's length. - num_query_blocks vs num_key_blocks throughout: Q padded to num_query_blocks*block_size, K/V padded to num_key_blocks*block_size, reshape sites updated accordingly. - cache.m3_idx_k_update_and_fetch(&idx_k) (from lablup#80) swaps the current-chunk-only idx_k for the FULL cached idx_k. This closes the architectural gap behind the cycle-65 latent comment: top-k block selection now scores ALL num_key_blocks blocks, including the cached prefix that pre-lablup#81 was invisible to the indexer. - New apply_causal_block_mask_asymmetric: per-query-block max attendable absolute key block = floor((cache_offset + (i+1)*block_size - 1) / block_size). Over-permissive at block level; sparse_sdpa's unified mask trims within-block future positions. - New ensure_local_block_score_asymmetric: forces top-k to include the cached-prefix's last few absolute blocks (the query's local neighbourhood), which sit BEFORE the current chunk in absolute coords. - Dispatch dense when num_key_blocks <= top_k (top-k saturates → no sparsity benefit, dense is at least as good). - selected has shape [b, num_kv_heads, num_query_blocks, top_k] with ABSOLUTE key block indices in [0, num_key_blocks). sparse_sdpa's asymmetric path consumes them correctly. Symmetric apply_causal_block_mask + ensure_local_block_score marked #[allow(dead_code)] for regression value; the asymmetric forms subsume them at cache_offset=0. Deletion planned after lablup#78-lablup#83 lands and the asymmetric forms have lived without regressions. Cycle 65's "Unreachable under default prefill_chunk_size=512, hence latent until now" comment in cycle 65's code is now obsolete — the cached-prefill path is exercised on every forward with non-empty cache. 14 mask tests pass (7 symmetric regression + 7 asymmetric). Integration test for the actual four-chunk forward-attention path is task lablup#82; this commit wires the path, the test in lablup#82 verifies correctness against dense single-shot.
sjswerdloff
added a commit
to sjswerdloff/mlxcel
that referenced
this pull request
Jun 25, 2026
Reproduces the cycle 79 crash scenario at the server boundary: - Long single-shot prompt (request 1, triggers MSA, cache_offset=0) - Follow-up sharing the prefix (request 2, exercises cached MSA path that was crashing) - Third turn extending cache (request 3, verifies no accumulation corruption across multi-turn) Each request asserts finish_reason is set (clean completion). The script eyeball-prints the first 200 chars of each response for manual coherence check. Prereq: release build of mlxcel-server (~10-15 min from clean target). Model path is sjswerdloff's MiniMax-M3-NVFP4-mlx on T7 Shield.
sjswerdloff
added a commit
to sjswerdloff/mlxcel
that referenced
this pull request
Jun 25, 2026
HANDOFF_cycle79_msa_chunked_prefill.md captures the state of the six-task proper-fix arc (lablup#78-lablup#83) so the smoke test can be completed by anyone with the branch checked out — pass criteria, debug paths if it fails, manual run command. Smoke script: replaced `yes ... | head -50` with a deterministic seq-driven loop. The pipe form triggered SIGPIPE on yes when head closed, pipefail picked it up, and `set -e` aborted the script after LONG_PROMPT was assigned but before any chat request was sent. Trace revealed the issue on the second attempt.
be-free-snowboy
pushed a commit
to freestylejs/snowbrain-mlxcel
that referenced
this pull request
Oct 27, 2026
Harden MiniCPM-V 4.6 dynamic image grid preprocessing and prompt placeholder spans so multi-image and non-square inputs produce correct per-image visual-token counts. Previously the MiniCPM-V 4.6 path assumed a single fixed `image_feature_size` for every image when building prompt placeholders, and the encoder did not validate that the spatial grid was divisible by the merge and window group sizes. With dynamic-resolution inputs (multiple images, or aspect ratios that resize to different grids) this produced placeholder spans that did not match the number of visual tokens each image actually yields, and could feed a non-divisible grid into the VitMerger and Merger. Changes: - Build prompt placeholders from a per-image feature size derived from each preprocessed image. `prepare_minicpmo_prompt_tokens_with_image_feature_sizes` takes a slice of per-image feature sizes instead of one shared size times the image count, and the MiniCPM-V 4.6 runtime arm now preprocesses images first, derives each image's feature size via `image_feature_size_for_processed`, and threads the slice through. - Add a divisibility guard in the encoder: the Merger and VitMerger reject a spatial grid that is not a multiple of their merge and window group sizes, instead of silently producing a misshapen tensor. - Align the image processor's best-resize search to the MiniCPM-V 4.6 downsample factor so the chosen grid is always compatible with the two-stage visual compression. Verified with cargo fmt, cargo clippy (metal,accelerate, all-targets, -D warnings), and 22 unit tests covering per-image feature sizes, placeholder span computation, the grid divisibility guards, and patch and downsample aligned resizing.
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.
Hardens MiniCPM-V 4.6 dynamic image grid preprocessing and prompt placeholder spans so multi-image and non-square inputs produce correct per-image visual-token counts.
Problem
The MiniCPM-V 4.6 path assumed a single fixed
image_feature_sizefor every image when building prompt placeholders, and the encoder did not validate that the spatial grid was divisible by the merge and window group sizes. With dynamic-resolution inputs (multiple images, or aspect ratios that resize to different grids) this produced placeholder spans that did not match the number of visual tokens each image actually yields, and could feed a non-divisible grid into the VitMerger and Merger.Changes
prepare_minicpmo_prompt_tokens_with_image_feature_sizestakes a slice of per-image feature sizes instead of one shared size times the image count; the MiniCPM-V 4.6 runtime arm preprocesses images first, derives each image's feature size viaimage_feature_size_for_processed, and threads the slice through.Verification
cargo fmt --checkclean.cargo clippy --features metal,accelerate --all-targets -- -D warningsclean.