feat(vlm): add Unlimited-OCR-2 (page2d RoPE and DASH sparse attention)

Aperta
#3,253 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

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

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

arch:moe area:models modelsize:small modeltype:vlm priority:medium status:blocked type:enhancement

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):

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-layer idx_scale = dash_scale_per_layer[slot] / sqrt(index_dim) (11.3137 here) and floor = dash_floor_per_layer[slot], where slot counts sparse layers before this one per sparse_attention_freq. Any dash_stage0 other than head_cls is a load error.
  • page2d RoPE (page2d_inv_freq, DashRope.page2d): rotate-half (non-traditional) RoPE with explicit cos/sin over two coordinates. With half = head_dim/2 = 64 and 1 page pair, 63 token frequencies 1/10000^(i/63) (resample mode) and 1 page frequency 1/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, with cos/sin multiplied by attention_factor taken from the config (1.0). When the key is absent upstream uses 0.1 * ln(factor) + 1.
  • PromptPages (built once from the full prompt ids): cum = cumsum(ids == <PAGE>); prefill tokens up to the last image get page cum, later tokens get cum - prompt_pages, clamped at 0; tok is the running index inside each page; pf_cnt[page] is the prefill count per page. Per 32-token block, blk_min/blk_max of 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_context decode branch): a generated <PAGE> increments markers and moves page = min(page + 1, n_pages - 1) with tok = pf_cnt[page]; otherwise tok += 1. Decode candidates are blocks whose image pages contain markers - 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 when block <= q_pos // 32 - 4; candidates are remote & page_candidates (fallback remote); 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)) / sigma on 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; scale head_dim ** -0.5; prefill processes queries in chunks of 2048. Decode gathers exactly 12 * 32 + 128 = 512 keys 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 from config.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 with max_crops = 16 (v1 uses 32 upstream). Base mode (cropping=False) pads each page into one 1024 global view, (16 + 1) * 16 + 1 = 273 image tokens per page, which equals per_page_image_tokens.
  • Weights: self_attn.dash_router.{q_proj,k_proj}.weight, {q_norm,k_norm}.weight, head_cls per layer, kept dense when quantizing (the mlx-community 4-bit pack ships them without .scales); self_attn.indexer.* (warmup stage, present in baidu/Unlimited-OCR-2, absent in the MLX packs) is dropped. Batch size 1 only.

Current mlxcel behavior

  • src/models/detection.rs:1181 maps unlimited-ocr to ModelType::UnlimitedOcrVLM, so v2 reaches load_unlimited_ocr_vlm (src/loading/vlm_deepseekocr.rs:221). Nothing in src/ reads sparse_attention_config, dash_router or <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) with RingSlidingKVCache per layer, and ring_attention (:134-187) applies fast_rope(.., rope_base, 1.0, offset) at absolute positions. deepseek::ModelArgs has no rope_scaling handling (src/models/deepseek.rs), so v2's YaRN is also ignored. The dash_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_prefill and supports_batching are all false (src/vision/unlimited_ocr.rs:296-316); keep that for v2.

Required changes

  1. 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 a DashLayerCache { keys, values, pending_index_keys, summaries, num_summaries } plus one shared per-sequence DashState { prompt: PromptPages, page, tok, markers }. Do not reuse minimax_m3_indexer.rs: its block selection (decode_selected_blocks, build_block_drop_mask, :329-470) is plain top-k over lightning-indexer scores with no head_cls summaries, entmax prior, page candidates or local-window union, so sharing it would mean flags on a MiniMax hot path.
  2. src/vision/unlimited_ocr.rs: make the attention mode an enum, Ring { window } (v1, unchanged) or Dash(DashRuntime); the DASH path owns its caches through ModelOwnedSequenceState like the ring path does, builds PromptPages from 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).
  3. src/loading/vlm_deepseekocr.rs load_unlimited_ocr_vlm: read the top-level sparse_attention_config (fall back to language_config.sparse_attention_config); when is_dash_config, load the router tensors per layer as dense f32-capable arrays, drop self_attn.indexer.*, construct the DASH mode, and set the processor to max_tiles: 16. A dash_stage0 other than head_cls, or a missing router tensor, is a load error naming the key. v1 checkpoints keep their current path and max_tiles.
  4. 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 from rope_scaling.attention_factor (1.0). Its returned factor is yarn_get_mscale(4, 1) / yarn_get_mscale(4, 0) = 1.1386, which is wrong here. Update that function's // Used by: comment.
  5. Prompt: add insert_unlimited_ocr2_page_tokens in src/multimodal/deepseekocr_prompt.rs that emits <PAGE> (128827) before each page's image run, following page_prompt's three cases (no placeholder: prepend all pages; one placeholder: expand to every page; one per page: mark each). Read the id from sparse_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 the VlmRuntimeRef::UnlimitedOcr arm when the model is in DASH mode.
  6. docs/supported-models.md: add the v2 row and note batch size 1.

Acceptance criteria

  • src/vision/unlimited_ocr_dash_tests.rs entmax15_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], and p[1] == 0.25 each.
  • 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_tokens 6 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], last tok == 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), the top_k * block + local_window key 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.rs unlimited_ocr2_config_selects_dash_and_16_tiles and dash_stage0_other_than_head_cls_is_rejected; a v1 config still selects the ring mode with max_tiles == 9.
  • src/multimodal/deepseekocr_prompt.rs tests for the three placeholder layouts of insert_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 0 produces the <PAGE> / <BLOCK>...<FORK> output format, and a two-page request returns both pages before EOS. Greedy output on one page matches mlx_vlm.generate --temperature 0 for the first 128 tokens, measured with the logit trace in docs/benchmarks.md.
  • Served through mlxcel-server (/v1/chat/completions with two image_url parts); mlxcel arch still 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

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di lablup/mlxcel

Tutte le issue di lablup/mlxcel

Issue simili

Altre issue su Rust

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.