feat(vlm): add Granite for Docling (granite_docling) support
Los mantenedores suelen responder en 1 día
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Aptitud para principiantes
- 12/100
- Tipo de issue
- Nueva funcionalidad
- Claridad
- Bastante claro
- Estado de actividad
- Activo
- Stack tecnológico
- rust
- Área
- backend, machine-learning
Línea de trabajo
Start by reading the detection arm near src/models/detection.rs:1169 and the Granite decoder in src/models/granite.rs, then the DeepStack pieces in src/models/deepstack_state.rs and src/models/qwen3_vl.rs. The work spans the connector, processor, prompt, loader and wrapper, so it is not a single-file change. The issue is labelled status:blocked until IBM publishes a checkpoint, so the real-checkpoint gate cannot be met yet.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
Summary
Add IBM Granite for Docling (model_type: granite_docling, GraniteDoclingForConditionalGeneration), a page-to-DocLang conversion VLM: a SigLIP-style encoder on 512x512 tiles, a pixel-shuffle connector with fixed 2D sine-cosine positions and DeepStack mergers, and a Granite dense decoder whose first layers receive the DeepStack features at image positions. Every building block has an mlxcel counterpart (Granite decoder with its four multipliers, SigLIP, Idefics3/SmolVLM-style tile framing, Qwen3-VL DeepStack injection, the vision feature cache), so the work is the connector, a new tile-grid rule, the DeepStack wiring for a Granite backbone, and the loader.
This is not the existing ibm-granite/granite-docling-258M, which is an Idefics3 checkpoint (model_type: idefics3, Idefics3ForConditionalGeneration) that mlxcel's detection routes to the SmolVLM/Idefics3 runtime (src/models/detection.rs:1169).
Blocked on checkpoint availability
Upstream names ibm-granite/granite-for-docling-2b and ibm-granite/granite-for-docling-500m, and the upstream PR reports validation against the 2B. Neither id resolves on the HuggingFace API today (both return 401, the response a nonexistent or private repo gives), an ibm-granite org search for "docling" lists only the 258M Idefics3 family, and the upstream PR says the native GraniteDoclingProcessor ships in transformers 5.23.0 and later. The ids are therefore "named upstream, not resolvable". The port can be written and unit-tested now, but the real-checkpoint gate cannot be met until IBM publishes a checkpoint; labelled status:blocked until then. When unblocking, record the actual id, revision and size here and confirm the config fields below against it.
Upstream reference
- Port: Blaizzy/mlx-vlm#2770 (merged 2026-11-20; commits e5fea63f "add Granite for Docling", b561d0a4 "dense DeepStack features for batched generation", f0e74652 "support the vision feature cache", bea7610f "Use a model-local PIL processor for Granite Docling"; d1099785 was reverted by e22cb59f).
- Code: https://github.com/Blaizzy/mlx-vlm/tree/main/mlx_vlm/models/granite_docling (
config.py,vision.py,language.py,granite_docling.py,processing_granite_docling.py). Tests:TestGraniteDoclingin https://github.com/Blaizzy/mlx-vlm/blob/main/mlx_vlm/tests/test_models.py, thegranite_doclingprocessor tests in https://github.com/Blaizzy/mlx-vlm/blob/main/mlx_vlm/tests/test_processors.py (checked against the Transformers PIL reference),test_processed_key_separates_granite_docling_routesintest_cache.py, and theTestModels.granite_doclingcase inmodel_cases.json. - Upstream validation (PR body): 2B greedy tokens 48/48 equal to Transformers in fp32 and bf16; full page in bf16 and 8-bit identical to Transformers fp32 (569 tokens); 4-bit 99.7% similar.
Architecture (from the upstream code; defaults from config.py)
Config. text_config: hidden_size 1024, intermediate_size 2048, num_hidden_layers 28, num_attention_heads 16, num_key_value_heads 4, rms_norm_eps 1e-5, vocab_size 133800, max_position_embeddings 32768, embedding_multiplier 12.0, logits_scaling 4.0, residual_multiplier 0.263, attention_multiplier 0.015625, rope_theta 1e4 (Transformers 5 rope_parameters override rope_theta and, for a non-default rope_type, become rope_scaling), tie_word_embeddings true, no biases. vision_config: hidden_size 768, intermediate_size 3072, 12 layers, 12 heads, image_size 512, patch_size 16, layer_norm_eps 1e-6, out_hidden_size 1024 (must equal text hidden, else a config error), scale_factor 4, deepstack_visual_indexes [3, 7, 10], use_fine_route true. Top level: image_token_id 100337, density_router_hidden_size (absent: no router), density_router_threshold 0.4; a router without use_fine_route is a config error. The real checkpoints may override any of these.
Vision encoder (VisionModel.encode): Conv2d patch embedding 16x16 stride 16 (PyTorch [out, in, kh, kw] transposed to MLX [out, kh, kw, in] in sanitize when not already in MLX layout), plus a learned position_embedding of (512/16)^2 = 1024 rows added directly (fixed 512 tiles, no interpolation); 12 pre-LN layers (h = x + attn(LN1(x)), h + mlp(LN2(h)), biased attention, GELU MLP); the outputs of layers 3, 7 and 10 (0-based, before post_layernorm) are kept as DeepStack taps; post_layernorm on the final output.
Connector (Connector, coarse path):
ln_inLayerNorm (default eps 1e-5) on the final vision states.pixel_shuffle(x, s)with the Idefics3 index order:[B, seq, D] -> [B, H, W/s, D*s] -> transpose -> [B, W/s, H/s, D*s^2] -> transpose -> [B, seq/s^2, D*s^2].projectionLinear768*16 -> 1024(no bias); add a fixed 2D sine-cosine embedding for the8x8token grid (grid = (512/16)/4): per row[sin_w | cos_w | sin_h | cos_h],pos_dim = 1024/4,omega = 1/10000^(arange(pos_dim)/pos_dim), computed in float64 and cast to float32, row-major.ln_mid, GELU,mlp_fc2Linear (no bias),ln_out; output 64 tokens per tile, flattened over tiles.- DeepStack: for each tap,
DeepStackMerger:pixel_shuffle(tap, 4), LayerNorm(768*16),linear_1(-> 1024), GELU,linear_2; flattened to[tiles*64, 1024]. Each tap's merger is independent.
- Fine path (500M only, opt-in): the same
ConnectorPathwithscale_factor // 2 = 2(256 tokens per tile, 4x the coarse count), sharingln_in,ln_mid,mlp_fc2,ln_out. Out of scope here (see Scope).
Language model (language.py): a Granite decoder. h = embed_tokens(ids) * embedding_multiplier, applied to image positions too, because the image features replace token embeddings before the multiplier; RoPE (non-traditional) on q and k; SDPA with scale = attention_multiplier; h = x + attn * residual_multiplier, h + mlp * residual_multiplier (SwiGLU, no bias); after decoder layer i < num_deepstack (layers 0, 1, 2), add deepstack[:, :, i] (zeros at text positions); final RMSNorm; tied logits divided by logits_scaling.
DeepStack batching and chunking (b561d0a4): DeepStack is one dense [B, L, num_taps, hidden] array with zeros at text positions so batched prefill pads and slices it like inputs_embeds; in single-sequence chunked prefill, the full-prompt array is sliced at the cache offset for the current chunk and zero-padded if short; decode steps carry none.
Merge (get_input_embeddings): text embeddings from embed_tokens; positions where input_ids == image_token_id receive the image features in order; a count mismatch is an error naming both numbers.
Image processor (processing_granite_docling.py, PIL backend):
- RGB conversion composites RGBA (or a transparency key) onto white; float RGBA must be in
[0, 1]. - Grid: candidate grids are all
(rows, cols)with both sides in1..min(16, max_patches)andmin_patches <= rows*cols <= max_patches(defaults 1 and 32), sorted by tile count; pick the smallest|w/h - cols/rows|, breaking ties in favour of the larger grid when2*w*h > rows*cols*512*512. No crop whencrop_to_patchesis false ormax_patches <= 1. The optionaldense_max_patches/dense_max_scale/dense_min_aspect/dense_max_aspectrule re-picks withdense_max_patchesas the maximum (all default 0, disabled). - Tiles: resize the whole page to exactly
(rows*512, cols*512)with BICUBIC (aspect not preserved), cut row-major tiles; whenrows*cols > 1, append the whole page resized to512x512as a global tile. Rescale by1/255, normalize with the OpenAI CLIP mean[0.48145466, 0.4578275, 0.40821073]and std[0.26862954, 0.26130258, 0.27577711]. - Batch output:
pixel_values [B, max_tiles, 3, 512, 512]withpixel_attention_maskmarking real tiles, plusrowsandcolsper page.
Prompt (GraniteDoclingProcessor._page_prompt, image_seq_len 64): for each row r and column c, <fake_token_around_image><row_{r+1}_col_{c+1}> followed by 64 <image> tokens, with \n after each row; when rows*cols > 1, then \n<fake_token_around_image><global-img> + 64 <image> + <fake_token_around_image>. A single-tile page therefore reads <fake_token_around_image><row_1_col_1><image>x64\n with no global tile, which differs from mlxcel's SmolVLM single-tile framing. Each prompt must have one image placeholder per page. Task prompts: <doclang> converts the full page; tasks may be selected as <doclang> [<table>, <layout>]. The chat template has no tool format.
Weights and sanitize: model.text_model.* -> language_model.model.*, model.vision_model.* -> vision_model.*, model.density_router.* -> density_router.*, lm_head.* -> language_model.lm_head.* (dropped when tied), mtp.* dropped (serving-engine MTP heads), position_ids dropped, patch conv transposed when in PyTorch layout. Idempotent.
Current mlxcel state
- No
granite_doclingarm insrc/models/detection.rs;idefics3/smolvlmroute toModelType::SmolVLM(line 1169). - Granite decoder:
src/models/granite.rs(ModelArgswithlogits_scaling,attention_multiplier,embedding_multiplier,residual_multiplierat lines 38-52;TransformerBlockappliesresidual_multiplier, line 325). - Tiling and prompt peers:
src/vision/processors/smolvlm.rs(TileLayoutline 47,tile_layoutline 172,preprocess_with_tilesline 269) andsrc/multimodal/smolvlm_prompt.rs(insert_smolvlm_image_tokens, line 125). Their grid rule (resize longest edge, round up to tile multiples) and single-tile framing differ from Granite Docling's. - DeepStack:
src/models/deepstack_state.rs(DeepStackState) and its use insrc/models/qwen3_vl.rs(set_deepstack_state, line 883); Granite 4 Vision (src/loading/vlm_granite4_vision.rs,src/vision/granite4_vision.rs) injects multi-depth visual features into a Granite 4 hybrid backbone and is the nearest Granite-side peer. - Vision feature cache:
src/vision/feature_cache.rsalready storesDeepStackFeatures(line 212) for Qwen3-VL (src/vision/qwen3_vl.rs:75). - SigLIP encoder:
src/vision/encoders/siglip.rs.
Proposed solution
- Detection and registry.
"granite_docling" => Ok(ModelType::GraniteDoclingVLM),ModelTypevariant,src/models/registry.rsnames,src/model_metadata.rsentry (kind: Vlm, directory: Vlm, adapters refused). - Text. Extend
src/models/granite.rswith a DeepStack-aware forward (forward_with_embeddings_and_deepstack) that adds per-layer features after layers0..num_tapsat image positions, reusingDeepStackStatefor per-sequence storage and the chunk-offset slicing rule above. No change for existing Granite checkpoints (no taps, bit-identical output). Update the// Used by:comments on any shared function touched. - Vision and connector. Reuse the SigLIP layer code for the encoder (adding tap capture), and add
src/vision/connectors/granite_docling.rswithpixel_shuffle, the float64-derived sine-cosine table (cached per(dim, grid)),ConnectorPath,DeepStackMergerandConnector. Refuse a config withscale_factornot dividing the token grid. - Processor and prompt.
src/vision/processors/granite_docling.rs(grid rule, exact-size BICUBIC resize, row-major tiles plus global tile, white compositing, CLIP normalization, EXIF orientation via the shared helper) andsrc/multimodal/granite_docling_prompt.rsproducing the framing above, reusing SmolVLM's token-id resolution for<fake_token_around_image>,<row_r_col_c>,<global-img>and<image>. - Loader and wrapper.
src/loading/vlm_granite_docling.rs(config parse with the defaults above, sanitize, quantization inheritance) andsrc/vision/granite_docling_vl.rs(GraniteDoclingVlModel) implementingLanguageModelby delegation plus the merge and DeepStack setup;LoadedModel::GraniteDoclingVLM,delegate_language_model!andVlmRuntimeRefarms. Register the directory entry point intry_load_vlm_model_from_dir()(src/loading/mod.rs:337) and the family route insrc/loading/vlm.rs, perdocs/adding-models.md(VLM checklist item 5). - Feature cache. Cache
(image tokens, stacked DeepStack features)per image key throughVisionFeatureCache<DeepStackFeatures>as Qwen3-VL does, with the key including the connector route so a future fine path cannot reuse a coarse entry (upstreamprocessed_image_keyincludestile_fine_mask). - Docs.
docs/supported-models.mdrow, with the note thatgranite-docling-258Mis the separate Idefics3 family.
Scope
In scope: coarse connector path; one or more pages per request; CLI and server; vision feature cache; docs.
Out of scope: the fine connector path and the density router (500M only, and selecting them needs a per-request processor option that mlxcel's request path does not carry; a follow-up issue once the 500M checkpoint exists), the mtp.* heads, the dense_* grid rule unless a published preprocessor_config.json enables it, tool calling (the template has none).
Implementation notes
- Precision rule.
load_vlm_weights()does bf16 -> f16 for non-quantized weights on Apple Silicon; no family exception is needed. Quantized checkpoints keep bf16 scales and biases. The sine-cosine table is computed in f64 and stored as f32 then cast to the activation dtype, as upstream. - Quantized vision parameters (
docs/adding-models.md, VLM checklist item 8). Audit every learned vision parameter for MLX quantization sidecars:embeddings.position_embedding(added whole to the patch embeddings) and the patch-embedding conv are raw arrays or embedding tables that an mlx-vlm conversion may store packed. Load them throughvision::weights::load_dense_param(whole-tensor use: add, slice, reshape, interpolate, concatenate) orUnifiedEmbedding(row lookup), thread the checkpoint'sgroup_size/bitsinto every tower linear, and validate packed dtype, shape and sidecars before any quantized FFI call, then the logical shape after dequantization, taking widths from config rather than a packed last dimension. This matters for this family in particular: the upstream README converts with-q --q-bits 8, and the upstream model defines no quant predicate that keeps the vision side dense, so converted checkpoints likely ship a quantized tower and connector. - Edge cases. Grids are capped at 16 per side because the tokenizer only has
<row_r_col_c>markers up to 16; a page withrows*cols == 1has no global tile; DeepStack must be absent (not zero arrays of wrong length) for text-only requests; a chunked prefill boundary inside an image span must slice DeepStack at the right offset. - Attribution. Derived from mlx-vlm (MIT) and the Transformers Granite Docling processor (Apache-2.0). Add per-file derivation lines and
NOTICEentries per the "Third-party attribution" rule in the repository development guidelines.
Acceptance criteria
-
mlxcel archlistsgranite_docling; detection test on a config with the upstream defaults;out_hidden_size != text hidden_sizeis a load error. - Processor tests in
src/vision/processors/granite_docling_tests.rs: the chosen grid for (612x792, US Letter at 72 dpi), (1700x2200), (2200x1700), (512x512) and (300x4000) equals upstreamGraniteDoclingImageProcessor.get_tile_grid(fixtures committed with the upstream commit noted); tiles and the global tile match upstream pixel fixtures to 1e-5; RGBA composites onto white. - Prompt test: the token sequence for a 2x3 grid and for a 1x1 grid equals upstream
_page_prompttokenized. - Connector tests:
pixel_shuffleindex order and the sine-cosine table equal upstream fixtures; a tiny random-weight model matching the upstreamTestModels.granite_doclingcase (text hidden 32, 2 layers, vision hidden 16, 2 layers, image 16, patch 2,deepstack_visual_indexes [0, 1]) runs with chunked prefill[1, 3, 5]equal to a single prefill, and the output with DeepStack zeroed differs at image positions. - Regression: existing Granite text tests pass, and a Granite checkpoint without taps gives bit-identical logits before and after the change.
- Quantized-vision tests: a synthetic checkpoint with
position_embeddingand the tower linears stored affine-quantized loads and matches the dense forward within quantization tolerance, a dense checkpoint still loads, and a malformed sidecar layout (wrong scales shape) is a load error naming the tensor. - Feature cache test: a second request with the same image hits the cache and produces identical logits to a cold request.
- Real checkpoint, once published:
mlxcel generate -m models/<granite-for-docling id> --image page.png -p "<doclang>" -n 4096 --temp 0matchesmlx_vlm.generategreedy output on the first page of a technical report, as upstream validated; the same throughmlxcel-serverwith animage_urlpart. - Integrated in
mlxcel generate --image,mlxcel-serverchat completions with images andmlxcel arch;docs/supported-models.md,NOTICE, derivation lines.
Verification
cargo build --release --features metal,accelerate
cargo test --profile test-fast --features metal,accelerate granite
make verify-test
cargo clippy --workspace --all-targets -- -D warnings
cargo fmt --check
curl -s https://huggingface.co/api/models/ibm-granite/granite-for-docling-2b # unblock check: must return model metadata, not an error
Related
- Granite Vision ports: #539 (Granite Vision), Granite 4 Vision (
src/loading/vlm_granite4_vision.rs). - SmolVLM/Idefics3 runtime, to which
ibm-granite/granite-docling-258Mis routed.
- Lenguaje dominante
- Rust
- Estrellas
- 505
- Forks
- 81
- Merge medio
- 14 h 2 min
- PR fusionados (30 d)
- 448
Preparar el entorno
- Sin Dockerfile ni archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de lablup/mlxcel
-
area:core priority:high status:ready type:security
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
Los mantenedores suelen responder en 1 día
-
priority:medium status:ready type:security
Dificultad 4/5 3-5 días Aptitud para principiantes 45/100
Los mantenedores suelen responder en 1 día
-
area:models modeltype:text priority:medium status:in-progress type:bug
Dificultad 4/5 3-5 días Aptitud para principiantes 57/100
Los mantenedores suelen responder en 1 día
-
area:models priority:low status:ready type:test
Dificultad 4/5 3-5 días Aptitud para principiantes 48/100
Los mantenedores suelen responder en 1 día
-
area:models modeltype:omni priority:medium status:ready type:bug
Dificultad 4/5 3-5 días Aptitud para principiantes 48/100
Los mantenedores suelen responder en 1 día
Todos los issues de lablup/mlxcel
Issues similares
-
TypeScript BM25 drops supplementary characters at the token length limitPosiblemente ocupada @ErenAta16 la tomó hoy. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
chroma-core/chroma#8038 ·
Los mantenedores suelen responder en 1 día
-
p3 ready
Dificultad 2/5 1-3 horas Aptitud para principiantes 71/100
Los mantenedores suelen responder en 1 día
-
area:ui effort:medium enhancement P7 source:agent
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 1 día
-
marketing
Dificultad 2/5 1-3 horas Aptitud para principiantes 85/100
Los mantenedores suelen responder en 1 día
-
machine rename accepts a label already used by another machine, making --machine <label> ambiguousAbiertomaintainer-needed p2 remote triaged
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
Los mantenedores suelen responder en 1 día