Skip to content

feat(models): port Granite Vision (ViT + Granite text) #539

Closed

Description

@inureyes

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-2b ships config.json with model_type: "llava_next" (architectures: ["LlavaNextForConditionalGeneration"]) and text_config.model_type: "granite".
  • MLX conversions such as mlx-community/granite-vision-3.2-2b-bf16 ship config.json with model_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.rs has no granite_vision arm, so a granite_vision checkpoint fails with "Unsupported model type".
  • src/models/detection.rs maps "llava" | "llava_next" to ModelType::LlavaVLM, and src/loading/vlm_llava.rs::llava_text_backend only accepts llama/mistral/qwen2 text backends. Loading ibm-granite/granite-vision-3.2-2b today fails with Unsupported LLaVA text backend: granite.
  • src/models/granite.rs (GraniteModel, tests in src/models/granite_tests.rs) already implements the dense Granite backbone with embedding_multiplier, attention_multiplier as the SDPA scale, residual_multiplier, logits_scaling, and tied embeddings. It only has a token-id forward(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 via with_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_1 then GELU then linear_2, loaded from a multi_modal_projector key prefix.
  • src/vision/merge.rs::merge_llava scatters a flat (total_image_tokens, hidden) feature tensor into the positions of input_ids equal to image_token_index.
  • No AnyRes tiling exists anywhere under src/vision/processors/ (no image_grid_pinpoints handling in the tree). src/vision/processors/siglip.rs only does a fixed square resize.
  • src/multimodal/vlm_prompt.rs and src/multimodal/vlm_runtime.rs hold the shared image-token expansion and VLM prefill plumbing; per-model expansion helpers live there or in model-specific src/multimodal/*_prompt.rs files.

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

  1. select_best_resolution((orig_h, orig_w), image_grid_pinpoints): for each candidate (cand_h, cand_w) compute scale = 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 maximizing effective; break ties by minimal wasted, 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).
  2. 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 as total // 2 before, remainder after, per axis).
  3. Divide into n_tiles_h * n_tiles_w tiles of 384x384, row-major (all tiles of the first tile-row left to right, then the next tile-row).
  4. Prepend the base tile: the full image resized (not aspect-preserving) to exactly 384x384.
  5. Per tile: scale pixels by 1/255, then normalize (x - 0.5) / 0.5 per 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, scale 72^-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 L has 28 entries: L[0] = embeddings output, L[j] = output of encoder layer j for j in 1..=27, all before post_layernorm. A negative tap index v resolves to L[28 + v]. So [-24, -20, -12, -1] resolves to L[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_strategy is "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_layernorm and 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 = 27 tokens per tile side and D = 2048:
    1. Base features = tile 0: (729, 2048).
    2. 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) with gh = 27 * n_tiles_h, gw = 27 * n_tiles_w.
    3. 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 rows pad .. gh - pad (axis 1). Else: new_w = int(round(orig_w * (gh / orig_h), 7)), pad = (gw - new_w) // 2, keep cols pad .. 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.
    4. 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).
    5. Concatenate base + packed on axis 0: final (N_img, 2048) with N_img = 729 + H * (W + 1).
    • Degenerate no-grid case (a features tensor with a single tile): use that tile's (729, 2048) and append image_newline once as a trailing row, N_img = 730.
  • Token expansion: each "<image>" occurrence (token id 49155) in the templated prompt is replaced by N_img copies of id 49155. N_img must 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 where input_ids == 49155 (this is merge_llava semantics; 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_multiplier 0.015625 (not 1/sqrt(64)), per-block residuals scaled by 0.22, final logits = 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):

  1. src/models/detection.rs
    • Add a "granite_vision" arm returning the new ModelType::GraniteVisionVLM.
    • In the "llava" | "llava_next" arm, inspect text_config.model_type in the parsed config and return ModelType::GraniteVisionVLM when it is "granite" (precedent for config-dependent arms: the "mistral3" arm's detect_text_or_vlm). Add cases to src/models/detection_tests.rs.
  2. src/models/mod.rs: new ModelType::GraniteVisionVLM variant, ALL_MODEL_TYPES entry, display-name arm (e.g. ("Granite Vision (SigLIP + Granite)", "Granite VLM")), and the exhaustive variants! list in the test at the bottom of the file.
  3. src/models/granite.rs: add input_embeddings(&self, input_ids) -> UniquePtr<MlxArray> (raw table lookup, no multiplier) and forward_embeds(&self, inputs_embeds, caches, mask) that starts at h = inputs_embeds * embedding_multiplier and reuses the existing layer/norm/head/logits-scaling code. Implement LanguageModel::forward_with_embeddings and LanguageModel::embed_tokens on GraniteModel in terms of these. Co-located tests in src/models/granite_tests.rs (token path vs embeds path must agree bit-for-bit when embeds = lookup).
  4. 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 (no post_layernorm). Keep the existing single-tap path untouched.
  5. 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 in src/vision/processors/mod.rs. Unit tests co-located or in a sibling anyres_tests.rs following src/vision/processors/internvl_tests.rs.
  6. src/vision/granite_vision.rs (new): GraniteVisionVLModel wrapper holding SigLipVisionModel, MLPProjector, the image_newline array, config fields (image_token_index, vision_feature_layer list, strategy, pinpoints), and the GraniteModel backbone. Implements get_input_embeddings(input_ids, images) = tower taps + concat + projector + packing + merge_llava, and LanguageModel by delegation (prefill via forward_with_embeddings, decode via token forward). Register in src/vision/mod.rs (module + re-export).
  7. src/vision/connectors/mlp.rs: reuse MLPProjector as-is with prefix multi_modal_projector.
  8. src/loading/vlm_granite_vision.rs (new): load_granite_vision_vlm(model_path) -> Result<LoadedModel>; wire the module and the pub(crate) use in src/loading/vlm.rs, the dispatch arm in src/loading/mod.rs::try_load_vlm_model_from_dir, and a LoadedModel::GraniteVisionVLM(...) variant in src/loaded_model.rs with all its match arms.
  9. src/multimodal/: image-token expansion for prompt preparation, following the existing per-model expansion helpers in src/multimodal/vlm_runtime.rs (see expand_nemotron_h_nano_omni_image_tokens_for_server) or a model-specific granite_vision_prompt.rs; must be wired into both the CLI generate path and the server path so N_img expansion happens wherever prompts are built.
  10. docs/supported-models.md: entry under "Vision-language and multimodal variants" documenting both accepted model_type spellings and the llava_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 to src/vision/encoders/siglip.rs.
  • Exclusive to this issue: ModelType::GraniteVisionVLM, src/vision/granite_vision.rs, src/loading/vlm_granite_vision.rs, the GraniteModel embeds entry point, the llava_next routing 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.weight anywhere in the checkpoint; tie_word_embeddings is true and GraniteModel already falls back to embed_tokens.as_linear. Some conversions materialize a head; src/models/sanitize.rs::sanitize_tied_embeddings covers that, keep it in the load path.
  • Drop any *.position_ids buffers if an export carries them.
  • Quantized MLX conversions ship weight/scales/biases triples; UnifiedLinear/UnifiedEmbedding consume them given group_size/bits from the config quantization block (see the group-size/bits plumbing in src/loading/vlm_llava.rs for the precedent).

Validation and acceptance criteria

  1. Co-located unit tests:
    • src/models/granite_tests.rs: embeds-path vs token-path equivalence; multiplier applied exactly once.
    • AnyRes tests: select_best_resolution expectations 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 equal 729 + H * (W + 1).
    • Multi-tap SigLIP test: tap -1 equals the existing single-tap path output; four taps return four tensors of shape (num_tiles, 729, 1152).
  2. Synthetic parity test tests/granite_vision_parity.rs (follow the structure of tests/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.
  3. 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, both mlxcel generate CLI 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 as vision_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. Both model_type spellings (granite_vision, and llava_next with a granite text config) must route and load.
  4. Integration means integration: detection, loader dispatch, LoadedModel variant, 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.rs already provides).

Activity

  1. added
    status:ready
    type:enhancement
    priority:low
    area:models
    on Jul 1, 2026
  2. added a commit that references this issue on Jul 3, 2026
    f81eec6
  3. self-assigned this
    on Jul 4, 2026
  4. added
    status:done
    and removed
    status:ready
    on Sep 6, 2026
  5. added a commit that references this issue on Oct 27, 2026
    2b921db
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area:modelspriority:lowstatus:donetype:enhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions