Repository navigation
Description
Summary
Add Granite Vision support to mlxcel. Granite Vision is IBM's document-understanding VLM: a SigLIP vision tower with multi-layer feature taps, a 2-layer GELU projector, a learned image_newline embedding, AnyRes multi-tile image preprocessing, and a dense Granite text backbone with the four Granite scalar multipliers (embedding, attention, residual, logits).
Checkpoint routing is two-headed and both heads must work:
- The original checkpoint
ibm-granite/granite-vision-3.2-2bshipsconfig.jsonwithmodel_type: "llava_next"(architectures: ["LlavaNextForConditionalGeneration"]) andtext_config.model_type: "granite". - MLX conversions such as
mlx-community/granite-vision-3.2-2b-bf16shipconfig.jsonwithmodel_type: "granite_vision".
Sibling issue: #541 (Granite 4 Vision, granite4_vision). Shared vs distinct is spelled out at the end of the implementation plan so the two issues can be implemented by different agents without collision.
Effort: medium-high (new AnyRes tiling machinery; the text backbone and most of the vision tower already exist in-tree).
Current state in mlxcel
Verified against the current tree:
src/models/detection.rshas nogranite_visionarm, so agranite_visioncheckpoint fails with "Unsupported model type".src/models/detection.rsmaps"llava" | "llava_next"toModelType::LlavaVLM, andsrc/loading/vlm_llava.rs::llava_text_backendonly acceptsllama/mistral/qwen2text backends. Loadingibm-granite/granite-vision-3.2-2btoday fails withUnsupported LLaVA text backend: granite.src/models/granite.rs(GraniteModel, tests insrc/models/granite_tests.rs) already implements the dense Granite backbone withembedding_multiplier,attention_multiplieras the SDPA scale,residual_multiplier,logits_scaling, and tied embeddings. It only has a token-idforward(input_ids, caches, mask); there is no embeddings-input entry point yet.src/vision/encoders/siglip.rs(SigLipVisionModel) implements the SigLIP tower, including the load-time patch-embedding weight permutation and single-layer feature selection viawith_feature_selection(layer, strategy). It cannot return several intermediate layers in one pass, which this model needs.src/vision/connectors/mlp.rs(MLPProjector) is exactly the needed projector:linear_1then GELU thenlinear_2, loaded from amulti_modal_projectorkey prefix.src/vision/merge.rs::merge_llavascatters a flat(total_image_tokens, hidden)feature tensor into the positions ofinput_idsequal toimage_token_index.- No AnyRes tiling exists anywhere under
src/vision/processors/(noimage_grid_pinpointshandling in the tree).src/vision/processors/siglip.rsonly does a fixed square resize. src/multimodal/vlm_prompt.rsandsrc/multimodal/vlm_runtime.rshold the shared image-token expansion and VLM prefill plumbing; per-model expansion helpers live there or in model-specificsrc/multimodal/*_prompt.rsfiles.
Architecture
config.json (values from ibm-granite/granite-vision-3.2-2b)
Top level:
| key | value |
|---|---|
model_type |
"llava_next" (original) or "granite_vision" (MLX conversions) |
image_token_index |
49155 |
vision_feature_layer |
[-24, -20, -12, -1] (a list; a plain int must also be accepted) |
vision_feature_select_strategy |
"full" |
image_grid_pinpoints |
27 pairs [h, w], from [384, 384] up to [3840, 384] / [384, 3840] |
use_image_newline_parameter |
true |
tie_word_embeddings |
true |
text_config (model_type: "granite"): hidden_size 2048, num_hidden_layers 40, intermediate_size 8192, num_attention_heads 32 (head_dim 64), num_key_value_heads 8, rms_norm_eps 1e-5, vocab_size 49156, rope_theta 300000, max_position_embeddings 131072, tie_word_embeddings true, attention_bias false, mlp_bias false, embedding_multiplier 12.0, attention_multiplier 0.015625, residual_multiplier 0.22, logits_scaling 8.0, bos_token_id 0, eos_token_id 0.
vision_config (model_type: "siglip_vision_model"): num_hidden_layers 27, hidden_size 1152, intermediate_size 4304, num_attention_heads 16 (head_dim 72), image_size 384, patch_size 14, num_channels 3. layer_norm_eps is absent and defaults to 1e-6; hidden_act defaults to tanh-approximated GELU.
preprocessor_config.json: image_processor_type: "LlavaNextImageProcessor", size {384, 384}, crop_size {384, 384}, image_mean [0.5, 0.5, 0.5], image_std [0.5, 0.5, 0.5], rescale_factor 1/255, resample 3 (bicubic), plus the same image_grid_pinpoints. processor_config.json: patch_size 14, vision_feature_select_strategy "full" (num_additional_image_tokens defaults to 0; image token string "<image>", id 49155).
Processor: AnyRes tiling
Per image with original size (orig_h, orig_w):
select_best_resolution((orig_h, orig_w), image_grid_pinpoints): for each candidate(cand_h, cand_w)computescale = min(cand_w / orig_w, cand_h / orig_h),down_w = int(orig_w * scale),down_h = int(orig_h * scale)(int = truncation),effective = min(down_w * down_h, orig_w * orig_h),wasted = cand_h * cand_w - effective. Pick the candidate maximizingeffective; break ties by minimalwasted, first candidate wins on a full tie. Result(best_h, best_w); grid shape(n_tiles_h, n_tiles_w) = (best_h / 384, best_w / 384).- Resize the image aspect-preserving so it fits inside
(best_h, best_w)(bicubic), then zero-pad symmetrically to exactly(best_h, best_w)(pad split astotal // 2before, remainder after, per axis). - Divide into
n_tiles_h * n_tiles_wtiles of 384x384, row-major (all tiles of the first tile-row left to right, then the next tile-row). - Prepend the base tile: the full image resized (not aspect-preserving) to exactly 384x384.
- Per tile: scale pixels by 1/255, then normalize
(x - 0.5) / 0.5per channel.
The checkpoint's processor emits pixel batches with a leading channel axis per tile, i.e. (num_tiles, channels=3, height=384, width=384). mlxcel's conv path consumes channels-last input, so the processor must produce (num_tiles, height=384, width=384, channels=3) directly from the decoded image (equivalent to a transpose with axis order (0, 2, 3, 1) of the channel-first layout). num_tiles = 1 + n_tiles_h * n_tiles_w, with tile index 0 = base tile.
The processor must also report (orig_h, orig_w) and (n_tiles_h, n_tiles_w) to the model wrapper; feature packing and prompt expansion both depend on them.
Vision tower and feature taps
SigLIP tower over all tiles in one batch:
- Patch embedding: conv with kernel 14, stride 14, no padding over
(num_tiles, 384, 384, 3)gives(num_tiles, 27, 27, 1152); flatten axes 1-2 to(num_tiles, 729, 1152); add the learned absolute position embedding (table shape(729, 1152), ids 0..728). No CLS token. - 27 pre-norm encoder layers:
x = x + attn(layer_norm1(x)),x = x + mlp(layer_norm2(x)); attention has 16 heads, head_dim 72, scale72^-0.5, bias on q/k/v/out projections; MLP is fc1 (1152 to 4304), tanh-approximated GELU, fc2 (4304 to 1152). - Hidden-state tap list
Lhas 28 entries:L[0]= embeddings output,L[j]= output of encoder layerjforjin 1..=27, all beforepost_layernorm. A negative tap indexvresolves toL[28 + v]. So[-24, -20, -12, -1]resolves toL[4], L[8], L[16], L[27](outputs of encoder layers 4, 8, 16, 27). - The four taps, each
(num_tiles, 729, 1152), are concatenated along axis 2 into(num_tiles, 729, 4608).vision_feature_select_strategyis"full": no token is dropped ("default"would drop the token at sequence index 0 and only applies to towers with a class token; support it but do not exercise it here). post_layernormand the attention-pooling head (head.*weights) are not on the generation path.
Projector and feature packing
multi_modal_projector:linear_1(4608 to 2048) + exact (erf) GELU +linear_2(2048 to 2048), both with bias. Output(num_tiles, 729, 2048). Note the projector activation is exact GELU while the tower MLP uses the tanh approximation.- Packing per image, with
p = 27tokens per tile side andD = 2048:- Base features = tile 0:
(729, 2048). - Grid tiles: features at tile indices 1.., shape
(n_tiles_h * n_tiles_w, 729, 2048). Reshape to(n_tiles_h, n_tiles_w, 27, 27, 2048), transpose with axis order(4, 0, 2, 1, 3)to(2048, n_tiles_h, 27, n_tiles_w, 27), reshape to(2048, gh, gw)withgh = 27 * n_tiles_h,gw = 27 * n_tiles_w. - Unpad in token space to undo the pixel-space padding of step 2 of the processor. If
orig_w / orig_h > gw / gh:new_h = int(round(orig_h * (gw / orig_w), 7)),pad = (gh - new_h) // 2, keep rowspad .. gh - pad(axis 1). Else:new_w = int(round(orig_w * (gh / orig_h), 7)),pad = (gw - new_w) // 2, keep colspad .. gw - pad(axis 2). Result(2048, H, W). The round-to-7-decimals-then-truncate rule is part of the checkpoint contract; use one shared helper for this so packing and token counting can never disagree. - Append the newline column: broadcast
image_newline(2048,)to(2048, H, 1)and concatenate on axis 2, giving(2048, H, W + 1). Reshape to(2048, H * (W + 1))and transpose axes(1, 0)to(H * (W + 1), 2048). - Concatenate base + packed on axis 0: final
(N_img, 2048)withN_img = 729 + H * (W + 1).
- Degenerate no-grid case (a features tensor with a single tile): use that tile's
(729, 2048)and appendimage_newlineonce as a trailing row,N_img = 730.
- Base features = tile 0:
- Token expansion: each
"<image>"occurrence (token id 49155) in the templated prompt is replaced byN_imgcopies of id 49155.N_imgmust be computed with exactly the same integer math as packing step 3.
Text backbone merge
inputs_embeds = embed_tokens(input_ids)shape(1, seq, 2048); scatter the packed features into positions whereinput_ids == 49155(this ismerge_llavasemantics; feature count must equal the number of image-token positions).- The backbone then computes
h = inputs_embeds * embedding_multiplier(12.0). The multiplier applies to the merged stream, so image features are scaled by 12.0 too; do not pre-scale them. - Everything downstream is the existing Granite math in
src/models/granite.rs: SDPA scale =attention_multiplier0.015625 (not1/sqrt(64)), per-block residuals scaled by 0.22, finallogits = tied_head(norm(h)) / 8.0. - Decode steps carry no pixel input and run the plain token forward. Standard per-layer
KVCache(k/v shapes(1, 8, seq, 64)as(batch, kv_heads, seq, head_dim)); no recurrent state in this model.
Implementation plan
File by file (all paths exist today unless marked new):
src/models/detection.rs- Add a
"granite_vision"arm returning the newModelType::GraniteVisionVLM. - In the
"llava" | "llava_next"arm, inspecttext_config.model_typein the parsed config and returnModelType::GraniteVisionVLMwhen it is"granite"(precedent for config-dependent arms: the"mistral3"arm'sdetect_text_or_vlm). Add cases tosrc/models/detection_tests.rs.
- Add a
src/models/mod.rs: newModelType::GraniteVisionVLMvariant,ALL_MODEL_TYPESentry, display-name arm (e.g.("Granite Vision (SigLIP + Granite)", "Granite VLM")), and the exhaustivevariants!list in the test at the bottom of the file.src/models/granite.rs: addinput_embeddings(&self, input_ids) -> UniquePtr<MlxArray>(raw table lookup, no multiplier) andforward_embeds(&self, inputs_embeds, caches, mask)that starts ath = inputs_embeds * embedding_multiplierand reuses the existing layer/norm/head/logits-scaling code. ImplementLanguageModel::forward_with_embeddingsandLanguageModel::embed_tokensonGraniteModelin terms of these. Co-located tests insrc/models/granite_tests.rs(token path vs embeds path must agree bit-for-bit when embeds = lookup).src/vision/encoders/siglip.rs: add a multi-tap forward, e.g.forward_collect_layers(&self, pixel_values, taps: &[i32]) -> Vec<UniquePtr<MlxArray>>, returning the requested entries of the 28-entry hidden-state list defined above (nopost_layernorm). Keep the existing single-tap path untouched.src/vision/processors/anyres.rs(new, shared with feat(models): port Granite 4 Vision (ViT + Granite-4 hybrid text) #541):select_best_resolution, aspect-preserving resize + symmetric pad + row-major tile split + base tile, normalization, and the token-count/unpad integer math helper (grid side and downsample ratio as parameters: this issue uses side 27, ratio 1; feat(models): port Granite 4 Vision (ViT + Granite-4 hybrid text) #541 uses side 24, ratio 1/2). Register insrc/vision/processors/mod.rs. Unit tests co-located or in a siblinganyres_tests.rsfollowingsrc/vision/processors/internvl_tests.rs.src/vision/granite_vision.rs(new):GraniteVisionVLModelwrapper holdingSigLipVisionModel,MLPProjector, theimage_newlinearray, config fields (image_token_index,vision_feature_layerlist, strategy, pinpoints), and theGraniteModelbackbone. Implementsget_input_embeddings(input_ids, images)= tower taps + concat + projector + packing +merge_llava, andLanguageModelby delegation (prefill viaforward_with_embeddings, decode via token forward). Register insrc/vision/mod.rs(module + re-export).src/vision/connectors/mlp.rs: reuseMLPProjectoras-is with prefixmulti_modal_projector.src/loading/vlm_granite_vision.rs(new):load_granite_vision_vlm(model_path) -> Result<LoadedModel>; wire the module and thepub(crate) useinsrc/loading/vlm.rs, the dispatch arm insrc/loading/mod.rs::try_load_vlm_model_from_dir, and aLoadedModel::GraniteVisionVLM(...)variant insrc/loaded_model.rswith all its match arms.src/multimodal/: image-token expansion for prompt preparation, following the existing per-model expansion helpers insrc/multimodal/vlm_runtime.rs(seeexpand_nemotron_h_nano_omni_image_tokens_for_server) or a model-specificgranite_vision_prompt.rs; must be wired into both the CLI generate path and the server path soN_imgexpansion happens wherever prompts are built.docs/supported-models.md: entry under "Vision-language and multimodal variants" documenting both acceptedmodel_typespellings and thellava_next+granite routing rule.
Shared vs distinct with #541
- Shared modules (land with whichever issue merges first; the other rebases and reuses, no duplicate implementations):
src/vision/processors/anyres.rs(tiling + token-count/unpad math) and the multi-tap addition tosrc/vision/encoders/siglip.rs. - Exclusive to this issue:
ModelType::GraniteVisionVLM,src/vision/granite_vision.rs,src/loading/vlm_granite_vision.rs, theGraniteModelembeds entry point, thellava_nextrouting rule. - Exclusive to feat(models): port Granite 4 Vision (ViT + Granite-4 hybrid text) #541: window QFormer connector, per-layer feature injection, the hybrid-backbone state plumbing.
Weight loading and sanitize
Checkpoint layout (verified from the safetensors index of ibm-granite/granite-vision-3.2-2b, 815 tensors). All linear weights are stored (out_features, in_features) and are consumed unchanged by UnifiedLinear (no permutation). Required handling:
| checkpoint key (pattern) | stored shape | handling |
|---|---|---|
vision_tower.vision_model.embeddings.patch_embedding.weight |
(1152, 3, 14, 14) = (out_ch, in_ch, kH, kW) |
permute axes (0, 2, 3, 1) to (1152, 14, 14, 3) = (out_ch, kH, kW, in_ch) for the channels-last conv. src/vision/encoders/siglip.rs already does this at load, with a shape heuristic (skip when axes 1 and 2 are equal and no larger than axis 0) so pre-permuted exports load unchanged |
vision_tower.vision_model.embeddings.patch_embedding.bias |
(1152,) |
as-is |
vision_tower.vision_model.embeddings.position_embedding.weight |
(729, 1152) |
as-is |
vision_tower.vision_model.encoder.layers.{0..26}.self_attn.{q,k,v,out}_proj.{weight,bias} |
(1152, 1152) / (1152,) |
as-is |
vision_tower.vision_model.encoder.layers.{0..26}.mlp.fc1.{weight,bias} |
(4304, 1152) / (4304,) |
as-is |
vision_tower.vision_model.encoder.layers.{0..26}.mlp.fc2.{weight,bias} |
(1152, 4304) / (1152,) |
as-is |
vision_tower.vision_model.encoder.layers.{0..26}.layer_norm{1,2}.{weight,bias} |
(1152,) |
as-is |
vision_tower.vision_model.post_layernorm.{weight,bias} |
(1152,) |
present but off the generation path; skip without error |
vision_tower.vision_model.head.* (probe (1, 1, 1152), attention.in_proj_weight (3456, 1152), attention.in_proj_bias (3456,), attention.out_proj.*, layernorm.*, mlp.fc{1,2}.*) |
various | attention-pooling head, unused for generation; skip without error |
multi_modal_projector.linear_1.{weight,bias} |
(2048, 4608) / (2048,) |
as-is |
multi_modal_projector.linear_2.{weight,bias} |
(2048, 2048) / (2048,) |
as-is |
image_newline |
(2048,) |
load into the wrapper |
language_model.model.embed_tokens.weight |
(49156, 2048) |
strip the language_model. prefix (existing strip_language_model_prefix in src/loading/vlm.rs), yielding the model.* layout GraniteModel::from_weights expects |
language_model.model.layers.{0..39}.self_attn.{q,o}_proj.weight |
(2048, 2048) |
prefix-strip, then as-is |
language_model.model.layers.{0..39}.self_attn.{k,v}_proj.weight |
(512, 2048) |
prefix-strip, then as-is |
language_model.model.layers.{0..39}.mlp.{gate,up}_proj.weight |
(8192, 2048) |
prefix-strip, then as-is |
language_model.model.layers.{0..39}.mlp.down_proj.weight |
(2048, 8192) |
prefix-strip, then as-is |
language_model.model.layers.{0..39}.{input_layernorm,post_attention_layernorm}.weight, language_model.model.norm.weight |
(2048,) |
prefix-strip, then as-is |
Additional rules:
- There is no
lm_head.weightanywhere in the checkpoint;tie_word_embeddingsis true andGraniteModelalready falls back toembed_tokens.as_linear. Some conversions materialize a head;src/models/sanitize.rs::sanitize_tied_embeddingscovers that, keep it in the load path. - Drop any
*.position_idsbuffers if an export carries them. - Quantized MLX conversions ship
weight/scales/biasestriples;UnifiedLinear/UnifiedEmbeddingconsume them givengroup_size/bitsfrom the configquantizationblock (see the group-size/bits plumbing insrc/loading/vlm_llava.rsfor the precedent).
Validation and acceptance criteria
- Co-located unit tests:
src/models/granite_tests.rs: embeds-path vs token-path equivalence; multiplier applied exactly once.- AnyRes tests:
select_best_resolutionexpectations computed by hand from the algorithm above (e.g. an image with(orig_h, orig_w) = (500, 1000)resolves to(best_h, best_w) = (768, 1152), grid(2, 3)), row-major tile order, base tile first, and a token-count property sweep: for a few hundred(orig_h, orig_w)pairs (tall, wide, square, exact multiples of 384, extreme aspect ratios), the packed feature length from the packing helper equals the count from the expansion helper, and both equal729 + H * (W + 1). - Multi-tap SigLIP test: tap
-1equals the existing single-tap path output; four taps return four tensors of shape(num_tiles, 729, 1152).
- Synthetic parity test
tests/granite_vision_parity.rs(follow the structure oftests/paddleocr_vl_parity.rs: no real checkpoint required): build tower + projector + backbone from synthetic weights at reduced dims, run an image through processor, taps, concat (axis 2 width = 4 x tower hidden), packing, merge, prefill, and one decode step; assert every intermediate shape listed in the Architecture section (scaled to the synthetic dims) and that logits differ when the image content changes but prompt does not. - Real-checkpoint smoke test (the completion bar): load
ibm-granite/granite-vision-3.2-2b(and, if available,mlx-community/granite-vision-3.2-2b-bf16) and generate a sensible answer to an image question through the actual runtime, bothmlxcel generateCLI and the OpenAI-compatible server image path. Known failure mode from previous VLM ports: synthetic parity can pass while real checkpoints break on weight-key layout, config defaults (absent keys such asvision_config.layer_norm_eps), tokenizer/chat-template details, and fused-weight handling. Real-checkpoint load + generate is therefore required before closing; standalone modules that compile and pass synthetic tests do not complete this issue. Bothmodel_typespellings (granite_vision, andllava_nextwith a granite text config) must route and load. - Integration means integration: detection, loader dispatch,
LoadedModelvariant, prompt expansion in CLI and server, and the docs entry all land in this issue, not as follow-ups.
Out of scope
- Granite 4 Vision (
granite4_vision): feat(models): port Granite 4 Vision (ViT + Granite-4 hybrid text) #541 (window-QFormer projectors, per-layer injection, hybrid backbone). - Video input.
- The SigLIP attention-pooling head (not on the generation path; its weights are skipped).
- Performance work (tile batching strategy, vision feature caching beyond what
src/vision/feature_cache.rsalready provides).
Activity
feat(models): port Granite Vision (SigLIP multi-tap + Granite text, A…
feat(models): port Granite Vision (SigLIP multi-tap + Granite text, A…