Repository navigation
feat(models): support Granite Embedding Vision R2 text and image embeddings - #3753
Conversation
…point Loads a tiny random-weight checkpoint through load_embedding_model and the EmbeddingEngine: detection, cls pooling with include_prompt false, unit text and image vectors, padded micro-batch parity, the reserved <image> InvalidRow, rectangular image token counts, and the gather of extra-vocabulary and image rows. Refs lablup#3752
…g-vision-r2 # Conflicts: # src/models/mod.rs
The tokenizers WordLevel model ignores an added token's id when the vocabulary does not hold it and assigns the next free id, so <image> encoded as 6 instead of the configured image_token_id 17 and the load-time tokenizer check rejected the fixture. Refs lablup#3752
Hardening reviewReviewed against #3752. The family plugs into the existing embeddings path rather than a parallel stack: detection arm and Gap found: no test ran the model's forward pass. The connector, the vision tower wiring, the extra-vocabulary/image gather and the engine path were only covered by the real-checkpoint gate, which skips when the checkpoint is absent. Added (commits 8dc7ed0, bb2631c):
Both take Validation (GB10, CUDA, under gpu-lock): focused lib tests Not run here: real-checkpoint parity. Minor note, not changed: token-id inputs are bounded by |
Summary
Closes #3752.
Adds Granite Embedding Vision R2 (
ibm-granite/granite-embedding-748m-vision-r2,model_type: modernvbertr2_granite_naflex_qformer) as an embedding family.mlxcel embedand/v1/embeddingsnow accept text and image inputs for it and return the checkpoint's 768-dimension single vector: the CLS token of the final ModernBERT hidden state, L2-normalized. This is what the Sentence Transformers1_Pooling(cls) and5_Normalizemodules compute, and what mlx-vlm serves on its/v1/embeddings.What changed
modernvbertr2_granite_naflex_qformeris an encoder-only embeddingmodel_typeand maps to the newModelType::GraniteEmbeddingVision. The variant is registered in every table that lists the embedding families: registry, metadata,mlxcel arch, modalities (text + image), memory estimate and the tensor-parallel placeholder.src/models/granite_embedding_vision.rs. Parses the config and loads the model, then implementsEmbeddingModel.text_config.rope_parametersis lifted onto ModernBERT'sglobal_rope_theta/local_rope_theta(150000 / 160000), as upstream's config does. Without the lift ModernBERT would fall back to 160000 / 10000.text_config(classifier_activation: silu) are dropped, so they do not trip ModernBERT's classifier validation.layer_typesmust agree withglobal_attn_every_n_layers.additional_embeddingtable, which holds<image>and the row/column markers. The upstream key (text_model.embeddings.tok_embeddings.additional_embedding) and the mlx-vlm converted key (additional_embedding) both load.<image>positions through one gather over[token rows; additional table; image rows]. A placeholder/feature count mismatch is an error, and so is an<image>token in a text-only input (upstream raises in both cases).image_tokenasconfig.image_token_id.use_image_newlinedefaults tofalsewhen the key is absent, as in upstream's config class and processor (mlx-vlm defaults totrue). The released checkpoint sets it totruein bothconfig.jsonandprocessor_config.json, so it is unaffected.src/vision/connectors/granite_embedding_vision.rs. The rectangular window Q-Former connector:w x wkey windows plusimage_positions;q x qwindows of the block-mean-pooled grid plusquery(downsample_rateq/w=2/4). The block mean is taken in float32 and rounded to the activation dtype once, as upstream'sF.interpolate(mode="area")and mlx-vlm'smean(axis=(1, 3))express it. On random bf16 input it equals MLX'smean(axis=(1, 3))on the CPU backend in every element; MLX's CUDA backend rounds after the first reduced axis and agrees in 68% of elements. Rounding after each axis instead (column pairs, then row pairs) agrees in 60% and lowers the minimum image cosine in the parity set below from 0.999872 / 0.999883 / 0.999507 to 0.999865 / 0.999858 / 0.999491 (mlx-vlm bf16 / mlx-vlm float32 / upstream float32).qformer_config.layer_norm_eps(1e-12).out_linear.pos_embedgrid, resized with antialiased bilinear in float32.newlinerow after every grid row (whenuse_image_newlineis set).src/vision/processors/granite_embedding_vision.rs. Upstream's aspect-preserving patch-grid search: float64, Python's round-half-to-even, the same candidate order and tie-breaking. Images are resized with Pillow's fixed-point bilinear (resize_pillow_rgb8), as mlx-vlm does (upstream resizes with torchvision), normalized to [-1, 1] and packed in(row, column, channel)patch order.processor_config.jsonoverrides the patch budget, mean, std and rescale factor. Settings the port does not implement (resampleother than 2,do_*: false) are rejected.WindowQFormerLayer) is nowpub(crate)and takes its LayerNorm epsilon as an argument. Granite 4 Vision passes its existing 1e-5 constant, so its behaviour is unchanged.ModernBertEncoder::encodeis split intoembed_tokensandencode_embeddings.encodecalls both in sequence, so it computes exactly what it did before.src/embeddings/pooling.rs). The released1_Pooling/config.jsonis{"pooling_mode": "cls", "include_prompt": false}, whichmainrefuses to load.include_prompt: falseis now accepted withclspooling only: CLS reads token 0 whatever the prompt mask says, so the flag changes nothing there (the checkpoint's prompts are empty strings anyway).mean,maxandlasttokenwithinclude_prompt: falsestill fail to load, and the error now names the mode.PoolingConfig::read/parsehave no other callers thanresolve_pooling_modeand the tests.EmbeddingModel::reserved_text_tokens()(default empty). A literal<image>in a text item tokenizes to the image placeholder id, and the forward pass has no image to put there. The engine now rejects such a text or token-id row with400 input[i] contains token id 262191, ...(the existingInvalidRowpath) instead of failing inside the forward pass with a500. Only this family returns a non-empty list.docs/embeddings.md,docs/supported-models.md), NOTICE and theUsed by:notes of the reused helpers (LFM2-VL tower,Learnable2DInterpPosEmb,load_dense_param, the Q-Former layer, the new ModernBERT methods) are updated.Deviations and scope
2_Dense, MaxSim). Serving them would make the family multi-vector, which changes the response shape for every caller of this model. mlx-vlm's endpoint does not serve them either. This can be a follow-up behind an option.task="query"short-query expansion (one- or two-word queries become"pages about {q}") has no equivalent in the OpenAI request and is not applied.qformer_spatial_offset(strided query downsampling) is rejected. The released checkpoint uses mean pooling (null).Verification
All runs are on an NVIDIA GB10 (sm_121), CUDA 13, aarch64 Linux, with
--profile test-fast --features cuda. The commit tree tested equals the PR tree (cb22294c).Before (main
9402cf893):After,
mlxcel embed(2 texts and 2 images): each query's highest cosine is its matching page.After,
mlxcel-server -m <checkpoint>/v1/embeddings, parity against the references./propsreports{"dim":768,"pooling":"cls","embd_normalize":2,"multi_vector":false}. The fixed set:data:URLs.ce13e795, bf16ce13e795, float32<bos>+nh * (nw + 1), identical to both reference processors. For example,banner.pnggives 269 andrevenue.pnggives 625.preprocess_device = "auto", which resizes on CUDA when a GPU is present; its source notes that the GPU resize rounds slightly differently from the CPU path (and the CPU path is torchvision's antialiased resize, not Pillow). mlx-vlm and mlxcel resize with Pillow. The per-image pattern matches: mlx-vlm float32 vs upstream float32 is 1.000000 (six decimals) forastronaut.png(512x512, already on its 32x32 grid, so the resize is the identity) and for the three rendered pages and the banner (text on flat backgrounds), and lower only where the resize resamples photographic content:chelsea.png0.999976,coffee.png0.99999 and the 16x-upscaled 40x24 crop 0.999555.Retrieval ranking (7 queries x 9 documents: the 7 non-tiny images and 2 text documents; cosine):
The smallest top-1 margin in the references is 0.053. The two float32 references order every query identically, so the discordant pairs of mlxcel and of mlx-vlm's own bf16 run are bf16-precision swaps of near-tied documents.
Errors:
<image>returns400 input[0] contains token id 262191, an image placeholder this model only accepts through an image input.dimensions: 769returns400.dimensions: 1returns[1.0].Tests:
cargo test --profile test-fast --features cuda --lib -- --test-threads=1 granite_embedding_vision modernbert granite4_vision lfm2_vl kimi_vl embeddings:: detection_tests: 355 passed, 0 failed. These include the new tests:rope_parameterslift;processor_config.jsonoverrides and rejections;use_image_newlinefrom the config, and its upstream default (false) when the key is absent;include_promptfor every pooling mode;InvalidRow;The new tests that evaluate MLX arrays take
mlx_test_guard()(fix(test): MLX unit tests abort under parallel test threads, plus example clippy lint #3660).Real checkpoint test
real_checkpoint_tests::granite_embedding_vision_image_usage_counts_bos_and_connector_rows, with the checkpoint in the model store: 512x512 gives 273 tokens and 640x480 gives 451. Passed.cargo fmt --all -- --check: clean.cargo clippy --locked --workspace --all-targets --features cuda -- -D warnings: clean.python3 scripts/ci/check_used_by.py: OK.bash scripts/ci/check_used_by_test.sh: OK.python3 scripts/insert_apache_header.py --check: OK.make verify-test-cuda: 18,911 passed, 2 failed, 578 ignored, 207 test binaries. Both failures reproduce on unmodifiedmain(9402cf893), the base of this branch, and neither touches this change; currentmainfixes both (feat(speculative): add DeepSeek-V4.1 bundled DSpark drafter (#3262) #3686, test: restore MLX guard scan and no-GPU catalog test gates #3765):tests/mlx_test_guard_coverage.rsnames onlysrc/vision/encoders/nemotron_h_nano_omni_tests.rs:276 pos_embed_resample_runs_in_f32. Onmainit fails with the same single entry.tests/step3p7_parity.rs:519text_decode_delegates_sequence_local_native_batchingfails withassertion failed: !wrapper.supports_padded_prefill(). Onmainit fails with the same assertion (7 passed, 1 failed).git merge-tree --write-tree origin/main HEADagainst currentmain(5bf7b8628): clean. On the merged tree, the Python tooling tests (python3 -m unittest discover -s tests -p 'test_*.py'), thescripts/cichecks CI runs andcargo fmt --all -- --checkpass.Maintainer checklist:
dimensions1 and 769; empty gather; unit downsample rate1/1;layer_typeslength mismatch.attentionhelper (MLX scaled-dot-product attention), so its cost grows with the square of that patch count.ModernBertEncoder::encode(ModernBERT embedder, reranker, Laya) still runs the same two steps in the same order.WindowQFormerLayer::from_weightsis called only by the Granite 4 Vision projector, which passes its previous constant.PoolingConfig::parseis reached only throughresolve_pooling_mode. Every family that loaded before still loads, and onlycls+include_prompt: falsechanges from an error to a load.cargo fmt --checkpasses on the final tree.Checkpoints
ibm-granite/granite-embedding-748m-vision-r2revision7998c8b63ecc66aa266005eff1bba8b920c1b2d5(bf16, 1.5 GB).Reference implementations
modeling_modernvbert_granite_naflex_qformer.py/processing_...py(trust_remote_code), torch 2.11.0+cu130, transformers 5.20.2, float32, TF32 off.ce13e795(mlx_vlm/models/granite_embedding_vision), MLX 0.32.5 CUDA backend, bf16 and float32.Limits
MultiVectorEncoder(similarity_fn_name: maxsim) whose primary output is the 128-dimension late-interaction token vectors, averaging 0.721 nDCG over eight visual document retrieval benchmarks; the single vector averages 0.601 there and is described as the first-stage (shortlist) search vector. The multi-vector output is not served.task="query"short-query expansion is not applied.UnifiedLinear/UnifiedEmbeddingpath, but no converted checkpoint was run.