feat(vlm): add Unlimited-OCR-2 (page2d RoPE and DASH sparse attention)
I maintainer di solito rispondono entro 1 giorno
Nessuno ha ancora preso questa issue.
Valutazione
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Idoneità per principianti
- 12/100
- Tipo di issue
- Funzionalità
- Chiarezza
- Abbastanza chiara
- Stato di attività
- Attiva
- Stack tecnologico
- rust
- Ambito
- machine-learning
Direzione di ricerca
Start with src/loading/vlm_deepseekocr.rs (load_unlimited_ocr_vlm) and src/vision/unlimited_ocr.rs, which currently route v2 into the v1 ring-cache path, then read src/multimodal/deepseekocr_prompt.rs. Done means the acceptance tests in src/vision/unlimited_ocr_dash_tests.rs and src/loading/vlm_deepseekocr_tests.rs pass and v1 checkpoints still take the ring path. The issue is a large new-module design task, so it needs maintainer guidance before a newcomer starts.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Descrizione
Summary
Add Unlimited-OCR-2 (baidu/Unlimited-OCR-2) to the existing Unlimited-OCR family. It keeps the v1 vision stack (SAM + CLIP + projector) and the 12-layer DeepSeek MoE decoder, but replaces v1's ring-sliding decode cache with a trained decoder attention path: page2d RoPE plus DASH block-sparse attention, detected from sparse_attention_config.training_stage == "dash". The model_type is the same unlimited-ocr, so today v2 is routed into the v1 runtime and decodes with the wrong attention, the wrong positions and the wrong prompt layout.
Upstream reference
Neywa-Labs/mlx-vlm#2601, commit 5061bd7f, inside the existing unlimited_ocr module (which subclasses deepseekocr):
- https://github.com/Neywa-Labs/mlx-vlm/blob/main/mlx_vlm/models/unlimited_ocr/dash.py (new; the whole algorithm)
- https://github.com/Neywa-Labs/mlx-vlm/blob/main/mlx_vlm/models/unlimited_ocr/language.py (
DeepseekV2DashModel,DashDecoderLayer,LanguageModel.sanitizedrops.self_attn.indexer.) - https://github.com/Neywa-Labs/mlx-vlm/blob/main/mlx_vlm/models/unlimited_ocr/config.py (top-level
sparse_attention_configcopied intotext_config) - https://github.com/Neywa-Labs/mlx-vlm/blob/main/mlx_vlm/models/unlimited_ocr/processing_unlimitedocr.py (
page_prompt,page_layout,max_crops) - Later commits on the same files:
5d65a184and2be5c136(merge of the #3235 precision fixes with DASH;_match_cache_dtypeapplies to the DASH model too),fb3b4623(Neywa-Labs/mlx-vlm#2646, prompt-cache snapshots of DASH state; out of scope here).
Architecture (from upstream code and the published config)
Config values (mlx-community/Unlimited-OCR-2-4bit/config.json): sparse_block_size 32, sparse_local_block 4 (local window 128 tokens), sparse_index_dim 128, dash_topk_blocks 12, top-m 16 (constant _DEFAULT_TOPM), dash_sigma 1.0, dash_scale_per_layer 128.0 x 12, dash_floor_per_layer 1e-4 x 12, dash_image_only true, image_token_id 128815, page_token_id 128827 (<PAGE>, a non-special added token), per_page_image_tokens 273, sparse_main_rope_mode page2d, sparse_main_rope_tok_freq_mode resample, sparse_rope_tok_theta 10000, sparse_rope_page_theta 256, sparse_rope_page_pairs 1, sparse_rope_page_mod 2, dash_stage0 head_cls. Text config: hidden 1280, 10 heads, 10 KV heads, head_dim 128, rope_theta 500000, rope_scaling {type: yarn, factor 4.0, original_max_position_embeddings 32768, beta_fast 32, beta_slow 1, attention_factor 1.0}.
- DashParams (
DashParams.from_config): per-layeridx_scale = dash_scale_per_layer[slot] / sqrt(index_dim)(11.3137 here) andfloor = dash_floor_per_layer[slot], whereslotcounts sparse layers before this one persparse_attention_freq. Anydash_stage0other thanhead_clsis a load error. - page2d RoPE (
page2d_inv_freq,DashRope.page2d): rotate-half (non-traditional) RoPE with explicit cos/sin over two coordinates. Withhalf = head_dim/2 = 64and 1 page pair, 63 token frequencies1/10000^(i/63)(resample mode) and 1 page frequency1/256^0 = 1. The page coordinate is taken% 2. Angles are[tok * inv_tok, page * inv_page],emb = concat(ang, ang). - 1-D fallback (
yarn_inv_freq,DashRope.linear): used when the prompt has no<PAGE>markers or no image. HF YaRN inverse frequencies over head_dim at base 500000, factor 4, withcos/sinmultiplied byattention_factortaken from the config (1.0). When the key is absent upstream uses0.1 * ln(factor) + 1. - PromptPages (built once from the full prompt ids):
cum = cumsum(ids == <PAGE>); prefill tokens up to the last image get pagecum, later tokens getcum - prompt_pages, clamped at 0;tokis the running index inside each page;pf_cnt[page]is the prefill count per page. Per 32-token block,blk_min/blk_maxof the image pages it holds. A prefill query may route only to image blocks of its own page; a row with no such block is unconstrained. - Decode state (
build_contextdecode branch): a generated<PAGE>incrementsmarkersand movespage = min(page + 1, n_pages - 1)withtok = pf_cnt[page]; otherwisetok += 1. Decode candidates are blocks whose image pages containmarkers - 1 - prompt_pages; open (all blocks) when that is negative or matches nothing. - Router (
DashRouter):q = norm(x @ q_proj.T),k = norm(x @ k_proj.T)with a Gemma-style(1 + weight)RMSNorm in f32,nan_to_num, and clamps at+-1e4; both get the same RoPE as the main attention; outputs f32[L, 128]. - Block summaries (
_summarize_blocks,_DashCache.add_index_keys): for each completed 32-token block,w = softmax(clip(sum(k * head_cls) / sqrt(128)))over the block, summary= sum(w * k). Only completed blocks are ever routed; pending index keys of the open block are kept. - Selection (
block_scores,route_select):z = clip(q . summary / sqrt(128)); a block is remote whenblock <= q_pos // 32 - 4; candidates areremote & page_candidates(fallbackremote);x = where(cand, z * idx_scale, -1e4); take the top 16 by score,prior = entmax15(sorted), keep the first 12;logp = log(max(prior, floor));bias = (logp - mean(logp over valid)) / sigmaon valid entries. - Attention: keys at positions
> q_pos - 128(causal) get mask 0; keys in a selected valid block get that block's bias; all others-inf; scalehead_dim ** -0.5; prefill processes queries in chunks of 2048. Decode gathers exactly12 * 32 + 128 = 512keys by index with the equivalent additive mask (_decode_select); slots of a block that overlap the local window are masked in the block copy and attended in the window copy. - Processor (
page_prompt,process_one): v2 is detected fromconfig.json; the prompt is rewritten so each page image is preceded by<PAGE>(one<image>placeholder becomes<PAGE><image>repeated per page). Gundam tiles are the default for every page withmax_crops = 16(v1 uses 32 upstream). Base mode (cropping=False) pads each page into one 1024 global view,(16 + 1) * 16 + 1 = 273image tokens per page, which equalsper_page_image_tokens. - Weights:
self_attn.dash_router.{q_proj,k_proj}.weight,{q_norm,k_norm}.weight,head_clsper layer, kept dense when quantizing (the mlx-community 4-bit pack ships them without.scales);self_attn.indexer.*(warmup stage, present inbaidu/Unlimited-OCR-2, absent in the MLX packs) is dropped. Batch size 1 only.
Current mlxcel behavior
src/models/detection.rs:1181mapsunlimited-ocrtoModelType::UnlimitedOcrVLM, so v2 reachesload_unlimited_ocr_vlm(src/loading/vlm_deepseekocr.rs:221). Nothing insrc/readssparse_attention_config,dash_routeror<PAGE>(grep returns only MiniMax-M3's unrelated MSA config).- That loader builds the v1 runtime:
UnlimitedOcrVlModel::new(inner, window)(src/vision/unlimited_ocr.rs:60) withRingSlidingKVCacheper layer, andring_attention(:134-187) appliesfast_rope(.., rope_base, 1.0, offset)at absolute positions.deepseek::ModelArgshas norope_scalinghandling (src/models/deepseek.rs), so v2's YaRN is also ignored. Thedash_router.*tensors are never read. - Prompt:
insert_unlimited_ocr_image_tokens(src/multimodal/deepseekocr_prompt.rs:92) expands one<image>to the summed run with no<PAGE>ids;VlmRuntimeRef::UnlimitedOcr(src/multimodal/vlm_runtime.rs:2456) calls it. - Processor: the loader uses
DeepSeekOcrProcessor::default()(src/vision/processors/deepseekocr.rs:84),max_tiles: 9. v2 needs 16. supports_chunked_prefill,supports_padded_prefillandsupports_batchingare allfalse(src/vision/unlimited_ocr.rs:296-316); keep that for v2.
Required changes
- New
src/vision/unlimited_ocr_dash.rs(+unlimited_ocr_dash_tests.rs):DashParams::from_config(&Value, num_layers, head_dim) -> Result<DashParams, String>,is_dash_config(&Value) -> bool,PromptPages::new(&[i32], &DashParams), page2d and YaRN cos/sin builders,entmax15,block_scores,route_select,decode_select, block summarization, and aDashLayerCache { keys, values, pending_index_keys, summaries, num_summaries }plus one shared per-sequenceDashState { prompt: PromptPages, page, tok, markers }. Do not reuseminimax_m3_indexer.rs: its block selection (decode_selected_blocks,build_block_drop_mask,:329-470) is plain top-k over lightning-indexer scores with nohead_clssummaries, entmax prior, page candidates or local-window union, so sharing it would mean flags on a MiniMax hot path. src/vision/unlimited_ocr.rs: make the attention mode an enum,Ring { window }(v1, unchanged) orDash(DashRuntime); the DASH path owns its caches throughModelOwnedSequenceStatelike the ring path does, buildsPromptPagesfrom the full prompt ids at offset 0 (the only prefill, since chunked prefill stays off), applies the RoPE from the context to q, k and the router q/k, and advances decode state in-graph (no host read of the sampled token).src/loading/vlm_deepseekocr.rsload_unlimited_ocr_vlm: read the top-levelsparse_attention_config(fall back tolanguage_config.sparse_attention_config); whenis_dash_config, load the router tensors per layer as dense f32-capable arrays, dropself_attn.indexer.*, construct the DASH mode, and set the processor tomax_tiles: 16. Adash_stage0other thanhead_cls, or a missing router tensor, is a load error naming the key. v1 checkpoints keep their current path andmax_tiles.- Frequencies: for the 1-D fallback reuse
yarn_rope_freqs(src/models/gpt_oss_common.rs:78,truncate: true) for the inverse frequencies only, and take the cos/sin multiplier fromrope_scaling.attention_factor(1.0). Its returned factor isyarn_get_mscale(4, 1) / yarn_get_mscale(4, 0) = 1.1386, which is wrong here. Update that function's// Used by:comment. - Prompt: add
insert_unlimited_ocr2_page_tokensinsrc/multimodal/deepseekocr_prompt.rsthat emits<PAGE>(128827) before each page's image run, followingpage_prompt's three cases (no placeholder: prepend all pages; one placeholder: expand to every page; one per page: mark each). Read the id fromsparse_attention_config.page_token_id(128827 on the published config) rather than hardcoding it, and leave a prompt that already contains it unchanged. Call it from theVlmRuntimeRef::UnlimitedOcrarm when the model is in DASH mode. docs/supported-models.md: add the v2 row and note batch size 1.
Acceptance criteria
-
src/vision/unlimited_ocr_dash_tests.rsentmax15_is_sparse: input rows[3.0, 2.9, 0.5, -1e4]and[1, 1, 1, 1]give rows summing to 1 (1e-5),p[0][3] == 0,p[0][0] > p[0][1] > p[0][2], andp[1] == 0.25each. - Same file,
prompt_pages_coordinates_and_candidates, with block 4, local 2, index_dim 8, top-k 2, image id 9, page id 7,per_page_image_tokens6 and prompt[1, 2, 3] + ([7] + [9] * 6) * 3 + [4, 5, 6, 2, 3]: page coordinates[0]*3 + [1]*7 + [2]*7 + [3]*7 + [0]*5,tok[0..4] == [0, 1, 2, 0], lasttok == 7,n_pages == 4,pf_cnt == [3, 7, 7, 7]; over 8 blocks the candidates for position 12 are[F, F, T, T, T, F, F, F]and the last position's row is all true. - Same file,
decode_gather_matches_dense_mask(same fixture with top-k 3 and local 1): for decode positions 2, 9, 21 and 22 (no remote block, partial blocks), thetop_k * block + local_windowkey gather equals the dense-mask prefill attention for the same query within 1e-5, with candidates all-true and restricted to block 1. - Same file,
yarn_fallback_uses_config_attention_factor: the 1-D cos/sin at position 0 equal 1.0 and 0.0 exactly, which fails if the 1.1386 factor is used. -
src/loading/vlm_deepseekocr_tests.rsunlimited_ocr2_config_selects_dash_and_16_tilesanddash_stage0_other_than_head_cls_is_rejected; a v1 config still selects the ring mode withmax_tiles == 9. -
src/multimodal/deepseekocr_prompt.rstests for the three placeholder layouts ofinsert_unlimited_ocr2_page_tokens, plus the already-marked prompt staying unchanged. - Real checkpoint:
mlxcel generate -m models/Unlimited-OCR-2-4bit --image page.png -p "Multi page parsing." -n 2048 --temp 0produces the<PAGE>/<BLOCK>...<FORK>output format, and a two-page request returns both pages before EOS. Greedy output on one page matchesmlx_vlm.generate --temperature 0for the first 128 tokens, measured with the logit trace indocs/benchmarks.md. - Served through
mlxcel-server(/v1/chat/completionswith twoimage_urlparts);mlxcel archstill lists the family. v1 (mlx-community/Unlimited-OCR-4bit) output is unchanged.
Validation
Checkpoints (Hub API checked 2026-11-23): mlx-community/Unlimited-OCR-2-4bit (2.6 GB), mlx-community/Unlimited-OCR-2-bf16 (6.8 GB), and the original baidu/Unlimited-OCR-2 (6.9 GB, carries the indexer.* tensors to exercise the drop). All fit a 128 GB machine.
make verify-test
cargo test --profile test-fast unlimited_ocr
cargo clippy --workspace --all-targets -- -D warnings
cargo fmt --check
python3 scripts/ci/check_cross_repo_refs.py
./target/release/mlxcel download mlx-community/Unlimited-OCR-2-4bit
./target/release/mlxcel generate -m models/Unlimited-OCR-2-4bit --image page_0001.png --image page_0002.png -p "Multi page parsing." -n 4096 --temp 0
Ordering
Land after #3235 (DeepSeek-OCR CLIP/SAM encoder numerics, which also fixes Unlimited-OCR's CLIP eps). The two touch different files (vision encoders there, decoder attention, cache and prompt here), but this issue's parity check compares against mlx-vlm main, whose encoder already has those fixes; tracing v2 before #3235 lands mixes encoder divergence into the decoder comparison. The issue is marked blocked by #3235 for that reason only.
Related
#771 (Unlimited-OCR v1), #3235 (encoder numerics, prerequisite), #2766 (model-owned cache rules). Out of scope: base mode (cropping=False, one 1024 view per page), since mlxcel exposes no per-request cropping switch for this family and upstream defaults to tiles; upstream's _match_cache_dtype decode cast, which #3235 already ruled a no-op for mlxcel; Neywa-Labs/mlx-vlm#2646 prompt-cache snapshots of DASH state (mlxcel declines prompt-cache reuse for this family today), KV-cache quantization of DASH caches, batch size above 1.
- Lingua principale
- Rust
- Stelle
- 505
- Fork
- 81
- Merge medio
- 14h 2m
- PR unite (30g)
- 448
Preparare l'ambiente
- Nessun Dockerfile né file Docker Compose
- Ha un modello di pull request
- Leggi la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di lablup/mlxcel
-
area:core priority:high status:ready type:security
Difficoltà 2/5 1-3 ore Idoneità per principianti 82/100
I maintainer di solito rispondono entro 1 giorno
-
priority:medium status:ready type:security
Difficoltà 4/5 3-5 giorni Idoneità per principianti 45/100
I maintainer di solito rispondono entro 1 giorno
-
area:models modeltype:text priority:medium status:in-progress type:bug
Difficoltà 4/5 3-5 giorni Idoneità per principianti 57/100
I maintainer di solito rispondono entro 1 giorno
-
area:models priority:low status:ready type:test
Difficoltà 4/5 3-5 giorni Idoneità per principianti 48/100
I maintainer di solito rispondono entro 1 giorno
-
area:models modeltype:omni priority:medium status:ready type:bug
Difficoltà 4/5 3-5 giorni Idoneità per principianti 48/100
I maintainer di solito rispondono entro 1 giorno
Tutte le issue di lablup/mlxcel
Issue simili
-
psmux-resurrect: restoring a session with a numeric name puts its windows into the wrong session (`new-window -t 4` is read as window 4)Forse già presa @ealwanlee l’ha presa oggi. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 88/100
psmux/psmux-plugins#47 ·
-
Link Checker ReportApertaautomated issue report
Difficoltà 1/5 Meno di un'ora Idoneità per principianti 76/100
ratatui/awesome-ratatui#598 ·
I maintainer di solito rispondono entro 1 giorno
-
release
Difficoltà 1/5 Meno di un'ora Idoneità per principianti 75/100
github/gh-aw-mcpg#17603 ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
I maintainer di solito rispondono entro 1 giorno
-
C-Bug S-Needs-Triage
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
bevyengine/bevy#26718 ·
I maintainer di solito rispondono entro 2 giorni