feat(vlm): add Granite for Docling (granite_docling) support

Abierto
#3,229 0 comentarios 0 reacciones 0 asignados Ver en GitHub

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

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

arch:dense area:models modelsize:small modeltype:vlm priority:low status:blocked type:enhancement

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

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

  1. ln_in LayerNorm (default eps 1e-5) on the final vision states.
  2. 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].
  3. projection Linear 768*16 -> 1024 (no bias); add a fixed 2D sine-cosine embedding for the 8x8 token 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.
  4. ln_mid, GELU, mlp_fc2 Linear (no bias), ln_out; output 64 tokens per tile, flattened over tiles.
  5. 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 ConnectorPath with scale_factor // 2 = 2 (256 tokens per tile, 4x the coarse count), sharing ln_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 in 1..min(16, max_patches) and min_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 when 2*w*h > rows*cols*512*512. No crop when crop_to_patches is false or max_patches <= 1. The optional dense_max_patches / dense_max_scale / dense_min_aspect / dense_max_aspect rule re-picks with dense_max_patches as 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; when rows*cols > 1, append the whole page resized to 512x512 as a global tile. Rescale by 1/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] with pixel_attention_mask marking real tiles, plus rows and cols per 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_docling arm in src/models/detection.rs; idefics3 / smolvlm route to ModelType::SmolVLM (line 1169).
  • Granite decoder: src/models/granite.rs (ModelArgs with logits_scaling, attention_multiplier, embedding_multiplier, residual_multiplier at lines 38-52; TransformerBlock applies residual_multiplier, line 325).
  • Tiling and prompt peers: src/vision/processors/smolvlm.rs (TileLayout line 47, tile_layout line 172, preprocess_with_tiles line 269) and src/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 in src/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.rs already stores DeepStackFeatures (line 212) for Qwen3-VL (src/vision/qwen3_vl.rs:75).
  • SigLIP encoder: src/vision/encoders/siglip.rs.

Proposed solution

  1. Detection and registry. "granite_docling" => Ok(ModelType::GraniteDoclingVLM), ModelType variant, src/models/registry.rs names, src/model_metadata.rs entry (kind: Vlm, directory: Vlm, adapters refused).
  2. Text. Extend src/models/granite.rs with a DeepStack-aware forward (forward_with_embeddings_and_deepstack) that adds per-layer features after layers 0..num_taps at image positions, reusing DeepStackState for 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.
  3. Vision and connector. Reuse the SigLIP layer code for the encoder (adding tap capture), and add src/vision/connectors/granite_docling.rs with pixel_shuffle, the float64-derived sine-cosine table (cached per (dim, grid)), ConnectorPath, DeepStackMerger and Connector. Refuse a config with scale_factor not dividing the token grid.
  4. 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) and src/multimodal/granite_docling_prompt.rs producing the framing above, reusing SmolVLM's token-id resolution for <fake_token_around_image>, <row_r_col_c>, <global-img> and <image>.
  5. Loader and wrapper. src/loading/vlm_granite_docling.rs (config parse with the defaults above, sanitize, quantization inheritance) and src/vision/granite_docling_vl.rs (GraniteDoclingVlModel) implementing LanguageModel by delegation plus the merge and DeepStack setup; LoadedModel::GraniteDoclingVLM, delegate_language_model! and VlmRuntimeRef arms. Register the directory entry point in try_load_vlm_model_from_dir() (src/loading/mod.rs:337) and the family route in src/loading/vlm.rs, per docs/adding-models.md (VLM checklist item 5).
  6. Feature cache. Cache (image tokens, stacked DeepStack features) per image key through VisionFeatureCache<DeepStackFeatures> as Qwen3-VL does, with the key including the connector route so a future fine path cannot reuse a coarse entry (upstream processed_image_key includes tile_fine_mask).
  7. Docs. docs/supported-models.md row, with the note that granite-docling-258M is 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 through vision::weights::load_dense_param (whole-tensor use: add, slice, reshape, interpolate, concatenate) or UnifiedEmbedding (row lookup), thread the checkpoint's group_size / bits into 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 with rows*cols == 1 has 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 NOTICE entries per the "Third-party attribution" rule in the repository development guidelines.

Acceptance criteria

  • mlxcel arch lists granite_docling; detection test on a config with the upstream defaults; out_hidden_size != text hidden_size is 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 upstream GraniteDoclingImageProcessor.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_prompt tokenized.
  • Connector tests: pixel_shuffle index order and the sine-cosine table equal upstream fixtures; a tiny random-weight model matching the upstream TestModels.granite_docling case (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_embedding and 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 0 matches mlx_vlm.generate greedy output on the first page of a technical report, as upstream validated; the same through mlxcel-server with an image_url part.
  • Integrated in mlxcel generate --image, mlxcel-server chat completions with images and mlxcel 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-258M is routed.
Lenguaje dominante
Rust
Estrellas
505
Forks
81
Merge medio
14 h 2 min
PR fusionados (30 d)
448

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de lablup/mlxcel

Todos los issues de lablup/mlxcel

Issues similares

Más issues de Rust

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.