Repository navigation
Description
Summary
Add Granite 4 Vision support to mlxcel. Checkpoints ship config.json with model_type: "granite4_vision" (architectures: ["Granite4VisionForConditionalGeneration"]); the verified public checkpoint is ibm-granite/granite-4.0-3b-vision. The architecture is a SigLIP vision tower feeding eight window-QFormer projector modules whose outputs are injected additively at eight different depths of a Granite 4 text backbone (text_config.model_type: "granitemoehybrid"), plus AnyRes multi-tile preprocessing, a learned image_newline embedding, and the four Granite scalar multipliers.
Two properties dominate the design:
- Multi-depth injection: image features are not merged once into the input embeddings; four "deepstack" streams and four "spatial" streams are added to the residual stream right before specific decoder layers during prefill.
- Hybrid backbone: the
granitemoehybridfamily mixes per-layer Mamba2 mixers and GQA attention bylayer_types, so the backbone carries recurrent conv/SSM state in addition to KV state. The 3B vision checkpoint happens to be all-attention, but the port must route through the generic hybrid backbone so anylayer_typesmix works.
Sibling issue: #539 (Granite Vision, granite_vision). Shared vs distinct is listed at the end of the implementation plan so the two issues can be implemented by different agents without collision.
Effort: high (new connector family, per-layer injection hook in a state-owning backbone).
Current state in mlxcel
Verified against the current tree:
src/models/detection.rshas nogranite4_visionarm, so the checkpoint fails with "Unsupported model type". ("granitemoehybrid"maps toModelType::GraniteMoeHybrid, text-only.)src/models/granitemoehybrid.rs(tests insrc/models/granitemoehybrid_tests.rs) already implements the full text backbone: per-layer mixer selection bylayer_types("mamba"or"attention"), denseshared_mlp(fused gate+up SwiGLU) and MoE modes, the four multipliers, RoPE or NoPE byposition_embedding_type, and a Mamba2 mixer shared in spirit withsrc/models/mamba2.rs(Mamba2Cache). Its state is model-owned:ModelOwnedSequenceState<GraniteMoeHybridLayerCache>withenum GraniteMoeHybridLayerCache { Attention(KVCache), Mamba(Mamba2Cache) }. TheLanguageModelimpl exposes placeholderKVCaches, declaressupports_batching() == falseandsupports_padded_prefill() == false, supports snapshot/restore (family tag"granitemoehybrid"), andtrim_internal_cachestrims KV but resets Mamba conv/SSM state. It has no embeddings-input entry point today:forward_with_cachesstarts from the token-id embedding lookup.- The in-tree precedent for a VLM wrapper over a state-owning hybrid backbone is
src/vision/nemotron_h_nano_omni_vl.rs(with its backbone'sforward_with_inputs_embedsinsrc/models/nemotron_h.rs): the wrapper passes placeholderKVCaches through and lets the backbone manage internal state. src/vision/encoders/siglip.rsimplements the SigLIP tower but cannot return several intermediate layer outputs in one pass (needed here; also needed by feat(models): port Granite Vision (ViT + Granite text) #539).- No QFormer/BERT-style post-norm attention block exists anywhere under
src/vision/(checked: noqformermatches insrc/). - No AnyRes tiling exists under
src/vision/processors/(noimage_grid_pinpointshandling in the tree); feat(models): port Granite Vision (ViT + Granite text) #539 plans the shared module. src/multimodal/vlm_prompt.rs/src/multimodal/vlm_runtime.rshold shared prompt-expansion and VLM prefill plumbing.
Architecture
config.json (values from ibm-granite/granite-4.0-3b-vision)
Top level:
| key | value |
|---|---|
model_type |
"granite4_vision" |
image_token_index |
100352 |
image_seq_length |
576 |
downsample_rate |
"4/8" (string "q/w": query window side q = 4, key window side w = 8) |
deepstack_layer_map |
[[-19, 9], [-13, 6], [-7, 3], [-1, 0]] (pairs [vision_tap, decoder_layer]) |
use_spatial_sampling |
true |
spatial_stride |
2 |
spatial_vision_layer |
-1 |
spatial_target_layers |
[12, 15, 18, 21] |
use_image_newline_parameter |
true |
vision_feature_select_strategy |
"full" |
projector_hidden_act |
"gelu"; projector_dropout 0.1 (inference no-op) |
image_grid_pinpoints |
27 pairs [h, w], [384, 384] up to [3840, 384] / [384, 3840] |
tie_word_embeddings |
true |
text_config (model_type: "granitemoehybrid"): hidden_size 2560, num_hidden_layers 40, layer_types = 40 x "attention" (no Mamba layer in this checkpoint), intermediate_size 8192, shared_intermediate_size 8192, num_local_experts 0, num_experts_per_tok 0 (dense mode: feed-forward is shared_mlp only), num_attention_heads 40 (head_dim 64), num_key_value_heads 8, position_embedding_type "rope", rope_theta 10000000, rms_norm_eps 1e-5, vocab_size 100353, embedding_multiplier 12, attention_multiplier 0.015625, residual_multiplier 0.22, logits_scaling 10, tie_word_embeddings true, attention_bias false, bos_token_id/eos_token_id 100257, plus the Mamba family keys (mamba_d_state 256, mamba_n_heads 128, mamba_d_head 40, mamba_n_groups 1, mamba_d_conv 4) which stay unused while layer_types contains no "mamba". All of this parses with the existing ModelArgs in src/models/granitemoehybrid.rs.
vision_config (model_type: "siglip_vision_model"): num_hidden_layers 27, hidden_size 1152, intermediate_size 4304, num_attention_heads 16, image_size 384, patch_size 16 (so 24x24 = 576 patch tokens per tile; contrast #539's patch 14 / 729 tokens), num_channels 3, layer_norm_eps 1e-6, tanh-approximated GELU.
preprocessor_config.json: image_processor_type: "LlavaNextImageProcessor", size {384, 384}, mean/std 0.5, rescale_factor 1/255, bicubic, do_pad true, same pinpoints. processor_config.json: patch_size 16, image_token "<image>", num_additional_image_tokens 0, vision_feature_select_strategy "full", and downsample_rate "2/4".
Trap, called out explicitly: processor_config.json says downsample_rate: "2/4" while config.json says "4/8". Both reduce the token grid side by the same ratio 1/2 (all the token-count math needs is the fraction), but the projector geometry (learned query of 16 tokens, image_positions of 64 slots) is only consistent with q = 4, w = 8. Read the projector geometry from config.json downsample_rate, use only the reduced fraction for token counting, and validate q/w against the loaded query/image_positions weight shapes at load time.
Processor: AnyRes tiling
Identical algorithm to #539 (same select_best_resolution, aspect-preserving resize + symmetric zero pad + row-major 384x384 tile split, base tile prepended at index 0, rescale 1/255 then (x - 0.5) / 0.5). Output must be channels-last (num_tiles, height=384, width=384, channels=3); the checkpoint's own processor emits channel-first (num_tiles, 3, 384, 384), so building channels-last directly is equivalent to a transpose with axis order (0, 2, 3, 1). The processor reports (orig_h, orig_w) and (n_tiles_h, n_tiles_w).
Vision tower and taps
Same SigLIP structure as #539, at patch 16: patch conv stride 16 over (num_tiles, 384, 384, 3) gives (num_tiles, 24, 24, 1152), flattened over axes 1-2 to (num_tiles, 576, 1152); position-embedding table (576, 1152); 27 pre-norm layers; no CLS token. Hidden-state tap list L has 28 entries (L[0] = embeddings output, L[j] = output of layer j), all pre-post_layernorm; a negative tap v resolves to L[28 + v]:
- deepstack taps: -19, -13, -7, -1 resolve to
L[9], L[15], L[21], L[27]; - spatial tap:
spatial_vision_layer-1 resolves toL[27].
vision_feature_select_strategy "full": no token dropped. post_layernorm and head.* are off the generation path.
Window-QFormer projector (8 instances)
Each projector maps one tap (num_tiles, 576, 1152) to (num_tiles, 144, 2560). With q = 4, w = 8, tile side s = 24, window grid n = s / w = 3, output side s' = n * q = 12:
- LayerNorm (
norm, eps 1e-6) over the tap:(num_tiles, 576, 1152). - Key/value windowing: reshape to
(num_tiles, 24, 24, 1152), then to(num_tiles, 3, 8, 3, 8, 1152), transpose with axis order(0, 1, 3, 2, 4, 5)to(num_tiles, 3, 3, 8, 8, 1152), reshape to(num_tiles * 9, 64, 1152). Add the learnedimage_positions(1, 64, 1152)(broadcast over axis 0). These are the cross-attention keys/values. - Query construction, per projector kind:
- Deepstack projectors (
layerwise_projectors.{0..3}) use block mean-pool downsampling: reshape the normed tap to(num_tiles, 12, 2, 12, 2, 1152)and take the mean over axes(2, 4), giving(num_tiles, 12, 12, 1152), reshape(num_tiles, 144, 1152). - Spatial projectors (
spatial_projectors.{0..3}) use strided selection withspatial_stride2: from the same(num_tiles, 12, 2, 12, 2, 1152)view select index(row_off, col_off)on axes 2 and 4, where projectoriuses offset[(0,0), (0,1), (1,0), (1,1)][i]; result(num_tiles, 144, 1152).
Window the downsampled grid with side 12 and window 4 (same reshape/transpose pattern as step 2) to(num_tiles * 9, 16, 1152)and add the learnedquery(1, 16, 1152)(broadcast over axis 0).
- Deepstack projectors (
- QFormer (1 layer, hidden 1152, 18 heads = 1152/64, head_dim 64, SDPA scale
64^-0.5= 0.125), post-norm residual style (LayerNorm applied after the residual add, matching the...output.LayerNormweight keys):h = LayerNorm_qformer(queries)(qformer.layernorm), shape(num_tiles * 9, 16, 1152).- Self-attention over the 16 query tokens: q/k/v linear (1152 to 1152, bias), reshape each to
(num_tiles * 9, 16, 18, 64), transpose(0, 2, 1, 3), SDPA without mask, transpose back and reshape to(num_tiles * 9, 16, 1152); thenh = LayerNorm(dense(attn_out) + h). - Cross-attention: queries from
h, keys/values from step 2's(num_tiles * 9, 64, 1152)(k/v linear 1152 to 1152 with bias); same head math with key length 64; thenh = LayerNorm(dense(attn_out) + h). - FFN:
intermediate_query.dense(1152 to 3072) + exact (erf) GELU,output_query.dense(3072 to 1152), thenh = LayerNorm(ffn_out + h).
- Un-window: reshape
(num_tiles * 9, 16, 1152)to(num_tiles, 3, 3, 4, 4, 1152), transpose(0, 1, 3, 2, 4, 5)to(num_tiles, 3, 4, 3, 4, 1152), reshape(num_tiles, 144, 1152). out_linear(1152 to 2560, bias):(num_tiles, 144, 2560).
Feature packing (per stream, identical math to #539 at grid side 12)
Base = tile 0 (144, 2560). Grid tiles (n_tiles_h * n_tiles_w, 144, 2560): reshape (n_tiles_h, n_tiles_w, 12, 12, 2560), transpose (4, 0, 2, 1, 3) to (2560, n_tiles_h, 12, n_tiles_w, 12), reshape (2560, gh, gw) with gh = 12 * n_tiles_h, gw = 12 * n_tiles_w; unpad in token space with the shared round-to-7-decimals-then-truncate rule (see #539 for the exact formula) to (2560, H, W); append image_newline (2560,) broadcast to (2560, H, 1) on axis 2; reshape (2560, H * (W + 1)); transpose (1, 0); concatenate base on axis 0. Final per-stream shape (N_img, 2560) with N_img = 144 + H * (W + 1). All eight streams share N_img (the packing depends only on shapes). Degenerate single-tile case: (144, 2560) plus one trailing image_newline row, N_img = 145.
Prompt expansion: each "<image>" (token id 100352) is replaced by N_img copies of id 100352, computed with the same integer math as packing.
Multi-depth injection into the backbone
Ordering of the eight streams (stream index -> projector -> decoder layer):
| stream | projector weights | vision tap | decoder layer |
|---|---|---|---|
| 0 | layerwise_projectors.0 |
L[9] (-19) |
9 |
| 1 | layerwise_projectors.1 |
L[15] (-13) |
6 |
| 2 | layerwise_projectors.2 |
L[21] (-7) |
3 |
| 3 | layerwise_projectors.3 |
L[27] (-1) |
0 |
| 4 | spatial_projectors.0 (offset (0,0)) |
L[27] |
12 |
| 5 | spatial_projectors.1 (offset (0,1)) |
L[27] |
15 |
| 6 | spatial_projectors.2 (offset (1,0)) |
L[27] |
18 |
| 7 | spatial_projectors.3 (offset (1,1)) |
L[27] |
21 |
Prefill semantics, with image-position mask m of shape (1, seq) (true where input_ids == 100352):
inputs_embeds = embed_tokens(input_ids),(1, seq, 2560); zero it at masked positions (where(m[..., None], 0, inputs_embeds)).- Backbone applies
h = inputs_embeds * embedding_multiplier(12). Because image slots are zero, image content enters the residual stream only through injections, unscaled by the multiplier. - Before running decoder layer
l, for every stream targetingl: add that stream's packed features (cast to the embedding dtype) at the masked positions:h[0, pos_k, :] += stream[k, :]wherepos_kis the k-thtrueposition ofm(k = 0..N_img-1, one image; with multiple images, streams are concatenated per image in prompt order on axis 0). Layer 0's injection happens after step 2, before any layer runs. - Decode steps carry no pixel input: plain token forward, no zeroing, no injection.
Backbone math is the existing src/models/granitemoehybrid.rs code: attention layers are GQA with q (1, seq, 40, 64) / k,v (1, seq, 8, 64) head layouts (as (batch, seq, heads, head_dim) before the transpose to (batch, heads, seq, head_dim)), RoPE theta 1e7, SDPA scale attention_multiplier 0.015625, block residuals scaled by 0.22, feed-forward shared_mlp: input_linear produces (1, seq, 16384), split on axis 2 into gate = slice 0..8192 and up = slice 8192..16384, silu(gate) * up, then output_linear; final logits = tied_head(norm(h)) / 10.
Hybrid state and cache contract (required design, mirror src/vision/nemotron_h_nano_omni_vl.rs)
- The backbone owns per-sequence state:
ModelOwnedSequenceState<GraniteMoeHybridLayerCache>. Attention layers holdKVCache(k/v(1, 8, past_len, 64)as(batch, kv_heads, seq, head_dim)); Mamba layers (none in the 3B checkpoint, possible in the family) holdMamba2Cachewithconv_state(batch, mamba_d_conv - 1, conv_dim)whereconv_dim = mamba_n_heads * mamba_d_head + 2 * mamba_n_groups * mamba_d_state, andssm_state(batch, mamba_n_heads, mamba_d_head, mamba_d_state). - The
LanguageModeltrait impl hands out placeholderKVCaches frommake_caches(); the VLM wrapper must pass them through untouched and delegatemake_caches/prepare_sequence_state/release_sequence_state_by_id/forward_with_sequence_id/snapshot_sequence_state/restore_sequence_state/trim_internal_cachesto the backbone, exactly as the Nemotron wrapper does. - The new embeds+injection entry point must run inside the backbone's own
sequence_state.with_sequence_state(...)(orwith_or_create_sequence_state) closure so recurrent conv/SSM state and KV offsets advance exactly once per prefill; do not add a second state owner in the wrapper. - Propagate
supports_padded_prefill() == falseandsupports_batching() == falsefrom the backbone through the wrapper: padded prefill would corrupt Mamba recurrent state on hybrid checkpoints, and the image-expanded prefill must be fed unpadded.trim_internal_cachesresets (not trims) recurrent state; the wrapper must not assume positional trimming works for the image span.
Implementation plan
File by file (paths exist today unless marked new):
src/models/detection.rs: add"granite4_vision" => Ok(ModelType::Granite4VisionVLM); cases insrc/models/detection_tests.rs.src/models/mod.rs:ModelType::Granite4VisionVLMvariant,ALL_MODEL_TYPESentry, display-name arm (e.g.("Granite 4 Vision (SigLIP + Granite 4 hybrid)", "Granite VLM")), and the exhaustivevariants!list in the test at the bottom of the file.src/models/granitemoehybrid.rs:pub fn input_embeddings(&self, input_ids) -> UniquePtr<MlxArray>: rawembed_tokenslookup, no multiplier.- Refactor
forward_with_cachesso the post-embedding layer stack is a separate function, and add an embeds entry point with optional injection, e.g.forward_embeds_with_injection(&self, inputs_embeds: &MlxArray, injection: Option<&DeepstackInjection>, seq_id: Option<SequenceId>) -> UniquePtr<MlxArray>whereDeepstackInjectioncarriestargets: Vec<(usize /* layer */, MlxArray /* (N_img_total, hidden) */)>and the(1, seq)boolean position mask. Injection = scatter-add at masked positions before the targeted layer, as specified above. Route throughsequence_statelike the existingforward/forward_with_sequence_id. Multiplier semantics: applyembedding_multipliertoinputs_embedsfirst; injected features are added after, unscaled. Token path and embeds path (with embeds = lookup, no injection) must agree bit-for-bit; co-located tests insrc/models/granitemoehybrid_tests.rs.
src/vision/encoders/siglip.rs: multi-tap collection (shared with feat(models): port Granite Vision (ViT + Granite text) #539; see that issue).src/vision/processors/anyres.rs(new, shared with feat(models): port Granite Vision (ViT + Granite text) #539): tiling + token-count/unpad helper, parameterized by grid side and downsample ratio (this issue: side 24, ratio 1/2, giving effective side 12). Registered insrc/vision/processors/mod.rs.src/vision/connectors/granite4_vision.rs(new):WindowQFormerProjectorimplementing steps 1-6 above (norm, windowing, mean-pool and strided-offset downsamplers, 1-layer post-norm QFormer with self+cross attention, un-window,out_linear), constructed 8 times from thelayerwise_projectors.{0..3}/spatial_projectors.{0..3}weight prefixes. Register insrc/vision/connectors/mod.rs. Co-located unit tests (see Validation).src/vision/granite4_vision.rs(new):Granite4VisionVLModelwrapper holdingSigLipVisionModel, the 8 projectors,image_newline, config fields (image_token_index,deepstack_layer_map,spatial_target_layers,spatial_vision_layer,downsample_rate, pinpoints), andGraniteMoeHybridModel. Builds the 8 packed streams + mask, calls the backbone's injection entry point for prefill, delegates everything else (including all the state-contract methods listed above). Register insrc/vision/mod.rs.src/loading/vlm_granite4_vision.rs(new):load_granite4_vision_vlm(model_path) -> Result<LoadedModel>performing the key remap below and constructing the wrapper; wire intosrc/loading/vlm.rs(module +pub(crate) use), the dispatch arm insrc/loading/mod.rs::try_load_vlm_model_from_dir, and aLoadedModel::Granite4VisionVLM(...)variant insrc/loaded_model.rswith all match arms.src/multimodal/:"<image>"toN_imgexpansion helper following the per-model expansion helpers insrc/multimodal/vlm_runtime.rs, wired into both CLI generate and server prompt paths.docs/supported-models.md: entry under "Vision-language and multimodal variants", including the"2/4"vs"4/8"note and the all-attention-backbone status.
Shared vs distinct with #539
- Shared (land with whichever issue merges first; the other rebases and reuses):
src/vision/processors/anyres.rs(tiling + count/unpad math) and the multi-tap addition tosrc/vision/encoders/siglip.rs. If feat(models): port Granite Vision (ViT + Granite text) #539 has not merged when this issue starts, coordinate so exactly one implementation exists. - Exclusive to feat(models): port Granite Vision (ViT + Granite text) #539:
ModelType::GraniteVisionVLM, theMLPProjectorroute,GraniteModelembeds entry,llava_nextrouting. - Exclusive to this issue:
ModelType::Granite4VisionVLM,src/vision/connectors/granite4_vision.rs, the injection entry point insrc/models/granitemoehybrid.rs, the hybrid state contract in the wrapper.
Weight loading and sanitize
Checkpoint layout (verified from the safetensors index of ibm-granite/granite-4.0-3b-vision, 1044 tensors). Three top-level namespaces: vision_tower.*, model.*, lm_head.weight. All linear weights are stored (out_features, in_features) and are consumed unchanged by UnifiedLinear (no permutation). Required remap in the loader:
model.language_model.{X}->model.{X}(soGraniteMoeHybridModel::from_weightsfinds its expectedmodel.embed_tokens/model.layers.{i}...layout).model.image_newline,model.layerwise_projectors.{i}.{X},model.spatial_projectors.{i}.{X}-> strip the leadingmodel..vision_tower.*andlm_head.weightunchanged.
Key table:
| checkpoint key (pattern) | stored shape | handling |
|---|---|---|
vision_tower.vision_model.embeddings.patch_embedding.weight |
(1152, 3, 16, 16) = (out_ch, in_ch, kH, kW) |
permute axes (0, 2, 3, 1) to (1152, 16, 16, 3) = (out_ch, kH, kW, in_ch); src/vision/encoders/siglip.rs already does this at load |
vision_tower.vision_model.embeddings.position_embedding.weight |
(576, 1152) |
as-is |
vision_tower.vision_model.encoder.layers.{0..26}.* |
same family as #539 (q/k/v/out (1152, 1152), fc1 (4304, 1152), fc2 (1152, 4304), norms (1152,)) |
as-is |
vision_tower.vision_model.post_layernorm.*, vision_tower.vision_model.head.* |
various | off the generation path; skip without error |
model.image_newline |
(2560,) |
strip model., load into wrapper |
model.{layerwise,spatial}_projectors.{0..3}.query |
(1, 16, 1152) |
strip model.; validate axis-1 length equals q^2 from config.json downsample_rate |
model.{layerwise,spatial}_projectors.{0..3}.image_positions |
(1, 64, 1152) |
strip model.; validate axis-1 length equals w^2 |
model.{layerwise,spatial}_projectors.{0..3}.norm.{weight,bias} |
(1152,) |
strip model. |
model.{layerwise,spatial}_projectors.{0..3}.out_linear.{weight,bias} |
(2560, 1152) / (2560,) |
strip model. |
...projectors.{i}.qformer.layernorm.{weight,bias} |
(1152,) |
strip model. |
...projectors.{i}.qformer.encoder.layer.0.attention.attention.{query,key,value}.{weight,bias} |
(1152, 1152) / (1152,) |
strip model.; self-attention q/k/v |
...projectors.{i}.qformer.encoder.layer.0.attention.output.dense.{weight,bias} |
(1152, 1152) / (1152,) |
strip model. |
...projectors.{i}.qformer.encoder.layer.0.attention.output.LayerNorm.{weight,bias} |
(1152,) |
strip model.; note the literal capitalized LayerNorm substring in the key |
...projectors.{i}.qformer.encoder.layer.0.crossattention.{attention.{query,key,value},output.dense,output.LayerNorm}.* |
same shapes as the self-attention set | strip model.; cross-attention: query consumes the 1152-dim query stream, key/value consume the 1152-dim window keys |
...projectors.{i}.qformer.encoder.layer.0.intermediate_query.dense.{weight,bias} |
(3072, 1152) / (3072,) |
strip model. |
...projectors.{i}.qformer.encoder.layer.0.output_query.{dense.{weight,bias},LayerNorm.{weight,bias}} |
(1152, 3072) / (1152,) / (1152,) |
strip model. |
model.language_model.embed_tokens.weight |
(100353, 2560) |
remap to model.embed_tokens.weight |
model.language_model.layers.{0..39}.self_attn.{q,o}_proj.weight |
(2560, 2560) |
remap prefix |
model.language_model.layers.{0..39}.self_attn.{k,v}_proj.weight |
(512, 2560) |
remap prefix |
model.language_model.layers.{0..39}.shared_mlp.input_linear.weight |
(16384, 2560) (fused: rows 0..8192 = gate, rows 8192..16384 = up, i.e. a split on axis 0 of the stored weight, axis 2 of the activation) |
remap prefix; the fused split is already implemented in src/models/granitemoehybrid.rs, do not re-split at load |
model.language_model.layers.{0..39}.shared_mlp.output_linear.weight |
(2560, 8192) |
remap prefix |
model.language_model.layers.{0..39}.{input_layernorm,post_attention_layernorm}.weight, model.language_model.norm.weight |
(2560,) |
remap prefix |
lm_head.weight |
(100353, 2560) |
leave key as-is; since text_config.tie_word_embeddings is true the backbone ignores it and uses the tied embedding (existing granitemoehybrid behavior: an explicit head is only loaded when untied). Do not error on the unused key |
Additional rules:
- No LoRA/adapter keys exist in this checkpoint (verified); do not add adapter-merge machinery here.
- Mamba mixer keys (
model.language_model.layers.{i}.mamba.*) are absent becauselayer_typesis all-attention; the loader must not require them, and must load them through the existing backbone when a hybrid checkpoint provides them. For such checkpoints the depthwiseconv1d.weightis stored(channels = conv_dim, 1, kernel = mamba_d_conv); the existing sanitize insrc/models/granitemoehybrid.rsalready swaps the last two axes to(conv_dim, mamba_d_conv, 1)for the channels-last conv, so the remap here only needs to deliver themodel.layers.{i}.mamba.*key layout. - Quantized conversions:
weight/scales/biasestriples throughUnifiedLinear/UnifiedEmbeddingwithgroup_size/bitsfrom the configquantizationblock.
Validation and acceptance criteria
- Co-located unit tests:
src/vision/connectors/granite4_vision.rs: window/un-window round trip is the identity on(num_tiles, 576, C); mean-pool downsampler equals a hand-computed 2x2 block mean; the four spatial offsets select the expected elements of a numbered 24x24 grid; QFormer output shape(num_tiles, 144, 2560);query/image_positionsshape validation rejects a"2/4"-geometry projector against"4/8"weights.src/models/granitemoehybrid_tests.rs: embeds path (no injection) equals token path bit-for-bit; injection at layerlwith a crafted one-hot feature changes exactly the masked positions and only from layerlonward; state advances once per prefill (a following decode step sees the correct KV offset).- AnyRes count property sweep at grid side 12 (shared helper, see feat(models): port Granite Vision (ViT + Granite text) #539): packed length equals expansion count equals
144 + H * (W + 1)across tall/wide/square/extreme sizes.
- Synthetic parity test
tests/granite4_vision_parity.rs(followtests/paddleocr_vl_parity.rs: synthetic weights, no checkpoint): reduced-dim tower + 8 projectors + all-attention hybrid backbone; assert the tap resolution table, every shape in the projector pipeline, stream-to-layer routing order (streams 0..7 hit layers 9, 6, 3, 0, 12, 15, 18, 21), zeroed image slots before injection, and one prefill + decode step end to end. Add one synthetic case with a mixedlayer_types(mamba+attention) backbone to prove the injection entry point coexists with recurrent state. - Real-checkpoint smoke test (the completion bar): load
ibm-granite/granite-4.0-3b-visionand 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 (here: themodel.prefix remap and the capitalizedLayerNormkeys), config defaults, tokenizer/chat-template details, and fused-weight handling (here:shared_mlp.input_linearand the"2/4"vs"4/8"trap). Real-checkpoint load + generate is therefore required before closing; standalone modules that compile and pass synthetic tests do not complete this issue. - Integration means integration: detection, loader dispatch,
LoadedModelvariant, prompt expansion in CLI and server, hybrid state contract methods on the wrapper, and the docs entry all land in this issue, not as follow-ups.
Out of scope
- Granite Vision (
granite_vision): feat(models): port Granite Vision (ViT + Granite text) #539 (single-merge projector, dense Granite backbone). - Real-checkpoint validation of a Mamba-hybrid
granite4_visionbackbone (no such public checkpoint verified; the code path must still stay generic overlayer_types, covered by the synthetic mixed-layer_typestest). - Video input.
- MoE-mode (
num_local_experts > 0) vision checkpoints: same generic-backbone argument, no public checkpoint to validate. - Performance work (projector batching across the 8 streams, vision feature caching beyond
src/vision/feature_cache.rs).
Activity
feat(models): port Granite 4 Vision (window-QFormer + Granite-4 hybri…
feat(models): port Granite 4 Vision (window-QFormer + Granite-4 hybri…