Skip to content

feat(models): support Granite Embedding Vision R2 text and image embeddings - #3753

Merged
inureyes merged 4 commits into
lablup:mainfrom
Jaeyeong-CHOI:feat/granite-embedding-vision-r2
Dec 4, 2026
Merged

inureyes merged 4 commits into
lablup:mainfrom
Jaeyeong-CHOI:feat/granite-embedding-vision-r2

Conversation

@Jaeyeong-CHOI

@Jaeyeong-CHOI Jaeyeong-CHOI commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

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 embed and /v1/embeddings now 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 Transformers 1_Pooling (cls) and 5_Normalize modules compute, and what mlx-vlm serves on its /v1/embeddings.

What changed

  • Detection and registration. modernvbertr2_granite_naflex_qformer is an encoder-only embedding model_type and maps to the new ModelType::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 implements EmbeddingModel.
    • text_config.rope_parameters is lifted onto ModernBERT's global_rope_theta / local_rope_theta (150000 / 160000), as upstream's config does. Without the lift ModernBERT would fall back to 160000 / 10000.
    • The unused classifier fields of text_config (classifier_activation: silu) are dropped, so they do not trip ModernBERT's classifier validation.
    • layer_types must agree with global_attn_every_n_layers.
    • Token ids at or above the 262152-row vocabulary read the 40-row additional_embedding table, 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 features replace the <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).
    • At load, the tokenizer must encode the processor's image_token as config.image_token_id.
    • use_image_newline defaults to false when the key is absent, as in upstream's config class and processor (mlx-vlm defaults to true). The released checkpoint sets it to true in both config.json and processor_config.json, so it is unaffected.
  • src/vision/connectors/granite_embedding_vision.rs. The rectangular window Q-Former connector:
    1. LayerNorm over the patch features.
    2. w x w key windows plus image_positions; q x q windows of the block-mean-pooled grid plus query (downsample_rate q/w = 2/4). The block mean is taken in float32 and rounded to the activation dtype once, as upstream's F.interpolate(mode="area") and mlx-vlm's mean(axis=(1, 3)) express it. On random bf16 input it equals MLX's mean(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).
    3. The Q-Former stack with qformer_config.layer_norm_eps (1e-12).
    4. Un-window, then out_linear.
    5. The learned pos_embed grid, resized with antialiased bilinear in float32.
    6. A newline row after every grid row (when use_image_newline is 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.json overrides the patch budget, mean, std and rescale factor. Settings the port does not implement (resample other than 2, do_*: false) are rejected.
  • Reused components:
    • The LFM2-VL SigLIP2 packed-patch tower runs the 27-layer vision model unchanged. Its keys and layout match.
    • The Granite 4 Vision Q-Former layer (WindowQFormerLayer) is now pub(crate) and takes its LayerNorm epsilon as an argument. Granite 4 Vision passes its existing 1e-5 constant, so its behaviour is unchanged.
    • ModernBertEncoder::encode is split into embed_tokens and encode_embeddings. encode calls both in sequence, so it computes exactly what it did before.
  • Shared pooling parser (src/embeddings/pooling.rs). The released 1_Pooling/config.json is {"pooling_mode": "cls", "include_prompt": false}, which main refuses to load. include_prompt: false is now accepted with cls pooling 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, max and lasttoken with include_prompt: false still fail to load, and the error now names the mode. PoolingConfig::read / parse have no other callers than resolve_pooling_mode and the tests.
  • Engine hook 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 with 400 input[i] contains token id 262191, ... (the existing InvalidRow path) instead of failing inside the forward pass with a 500. Only this family returns a non-empty list.
  • Docs (docs/embeddings.md, docs/supported-models.md), NOTICE and the Used 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

  • Only the single-vector output is served. The checkpoint also ships 128-dimension late-interaction token vectors (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.
  • Text is embedded as given, which is upstream's document preprocessing. Upstream's 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).
  • The full order of all nine documents is not identical for every query (see below). The top-ranked document is identical for every query and every reference. The only pairs ordered differently are near-ties in the reference scores, and mlx-vlm's own bf16 run differs from the upstream float32 order in the same way, by more.

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

$ mlxcel embed -m granite-embedding-748m-vision-r2 -p "hotel allowance per night"
Error: failed to load embedding model .../granite-embedding-748m-vision-r2
Caused by:
    .../granite-embedding-748m-vision-r2 is an embedding checkpoint (sentence-transformers pooling layout or embedding architecture), but model_type `modernvbertr2_granite_naflex_qformer` has no embedding family in mlxcel; see docs/embeddings.md for the supported families

After, mlxcel embed (2 texts and 2 images): each query's highest cosine is its matching page.

$ mlxcel embed -m granite-embedding-748m-vision-r2 -p "hotel allowance per night" -p "a cup of coffee" --image hotel_policy.png --image coffee.png
cosine similarity (4 inputs):
  [0]  1.0000  0.7655  0.8427  0.6858
  [1]  0.7655  1.0000  0.7101  0.8561
  [2]  0.8427  0.7101  1.0000  0.6960
  [3]  0.6858  0.8561  0.6960  1.0000
4 input(s), 906 prompt tokens, dim 768, max_length 2048

After, mlxcel-server -m <checkpoint> /v1/embeddings, parity against the references. /props reports {"dim":768,"pooling":"cls","embd_normalize":2,"multi_vector":false}. The fixed set:

  • 13 texts: short queries, two text documents, Korean, Chinese, and 202- and 702-token passages that cross the 128-token local window. Sent as one request, so they run as padded micro-batches.
  • 8 images: three scikit-image photos, three rendered document pages (850x1100 portrait, 1400x700 landscape, 400x1600 tall), a 2000x120 banner (8x132 patch grid) and a 40x24 crop that is upscaled to the minimum budget. Sent as data: URLs.
  • A third request interleaves all 21 items.
Reference min cosine, texts min cosine, images max abs diff (unit vectors) usage tokens (texts / images)
mlx-vlm ce13e795, bf16 0.999899 0.999872 0.0069 1000 / 3092, equal
mlx-vlm ce13e795, float32 0.999901 0.999883 0.0090 1000 / 3092, equal
upstream PyTorch, float32 0.999901 0.999507 (40x24 crop; next lowest 0.999883) 0.0089 1000 / 3092, equal
  • Vector norms deviate from 1 by at most 6.7e-8. The interleaved request matches the separate requests (min cosine 0.9999999999).
  • Image token counts are <bos> + nh * (nw + 1), identical to both reference processors. For example, banner.png gives 269 and revenue.png gives 625.
  • For comparison, the references agree among themselves as follows. mlx-vlm float32 vs upstream float32: texts 1.0, the seven other images ≥ 0.999976, the 40x24 crop 0.999555, with identical token ids and patch grids. mlx-vlm bf16 vs upstream float32: ≥ 0.99951. The two references disagree most on that upscaled crop. mlxcel is at 0.999947 against mlx-vlm float32 there.
  • The reference-to-reference gap is in image preprocessing. The upstream run used its processor's default 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) for astronaut.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.png 0.999976, coffee.png 0.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):

Pair top-1 identical full order identical discordant pairs largest reference gap among discordant pairs
mlxcel vs mlx-vlm bf16 7/7 5/7 2 / 252 0.00052
mlxcel vs mlx-vlm float32 7/7 6/7 1 / 252 0.00004
mlxcel vs upstream float32 7/7 6/7 1 / 252 0.00006
mlx-vlm bf16 vs upstream float32 7/7 4/7 3 / 252 0.0016
mlx-vlm float32 vs upstream float32 (control) 7/7 7/7 0 / 252 -

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:

  • A text item containing <image> returns 400 input[0] contains token id 262191, an image placeholder this model only accepts through an image input.
  • dimensions: 769 returns 400.
  • dimensions: 1 returns [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:

    • config parsing and rejections (each names the field);
    • the rope_parameters lift;
    • the gather plan (text / extra-vocabulary / image rows, out-of-vocabulary ids, empty input);
    • placeholder expansion (count mismatches);
    • both weight layouts;
    • the patch-grid search against 18 reference grids (including 1x1, 1x10000, 10000x1 and 1x16384);
    • processor packing and processor_config.json overrides and rejections;
    • connector windowing on rectangular grids and token counts;
    • use_image_newline from the config, and its upstream default (false) when the key is absent;
    • include_prompt for every pooling mode;
    • the reserved-token InvalidRow;
    • detection with and without the pipeline files.

    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 unmodified main (9402cf893), the base of this branch, and neither touches this change; current main fixes 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.rs names only src/vision/encoders/nemotron_h_nano_omni_tests.rs:276 pos_embed_resample_runs_in_f32. On main it fails with the same single entry.
    • tests/step3p7_parity.rs:519 text_decode_delegates_sequence_local_native_batching fails with assertion failed: !wrapper.supports_padded_prefill(). On main it fails with the same assertion (7 passed, 1 failed).
  • git merge-tree --write-tree origin/main HEAD against current main (5bf7b8628): clean. On the merged tree, the Python tooling tests (python3 -m unittest discover -s tests -p 'test_*.py'), the scripts/ci checks CI runs and cargo fmt --all -- --check pass.

Maintainer checklist:

  1. Boundaries: 1x1, 40x24 (upscaled to the 576-patch minimum), 2000x120 and 1x10000 / 10000x1 (outside the budget, as upstream); dimensions 1 and 769; empty gather; unit downsample rate 1/1; layer_types length mismatch.
  2. Complexity: per row, the gather plan is one host pass over the token ids. Preprocessing is one Pillow resize per image, and the grid search evaluates 16 candidates. Images are embedded one per forward pass, as for every other image embedder. Ordinary images stay within the 576 to 2880 patch budget; as upstream, extreme aspect ratios exceed it because the short side keeps one 4-patch window: a 1x16384 image gets 4x3080 = 12,320 patches (3,083 tokens), checked against upstream's grid search in the unit test. The SigLIP2 tower attends over all patches of an image through the shared attention helper (MLX scaled-dot-product attention), so its cost grows with the square of that patch count.
  3. Other callers:
    • ModernBertEncoder::encode (ModernBERT embedder, reranker, Laya) still runs the same two steps in the same order.
    • WindowQFormerLayer::from_weights is called only by the Granite 4 Vision projector, which passes its previous constant.
    • PoolingConfig::parse is reached only through resolve_pooling_mode. Every family that loaded before still loads, and only cls + include_prompt: false changes from an error to a load.
    • The new trait method defaults to empty.
  4. No explanatory comment was removed; the new error messages name this family.
  5. cargo fmt --check passes on the final tree.

Checkpoints

  • ibm-granite/granite-embedding-748m-vision-r2 revision 7998c8b63ecc66aa266005eff1bba8b920c1b2d5 (bf16, 1.5 GB).

Reference implementations

  • Upstream PyTorch: the checkpoint's own modeling_modernvbert_granite_naflex_qformer.py / processing_...py (trust_remote_code), torch 2.11.0+cu130, transformers 5.20.2, float32, TF32 off.
  • mlx-vlm commit ce13e795 (mlx_vlm/models/granite_embedding_vision), MLX 0.32.5 CUDA backend, bf16 and float32.

Limits

  • Only the 768-dimension single vector (CLS) is served. The model card presents the checkpoint as a Sentence Transformers 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.
  • The task="query" short-query expansion is not applied.
  • Validated with the bf16 checkpoint only. mlx-vlm 4-bit / 8-bit conversions take the existing quantized UnifiedLinear / UnifiedEmbedding path, but no converted checkpoint was run.
  • Not run on Metal.

@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:medium Medium priority area:models Model architectures, weights, loading, metadata modeltype:vlm Vision-language model labels Dec 4, 2026
…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
@inureyes

inureyes commented Dec 4, 2026

Copy link
Copy Markdown
Member

Hardening review

Reviewed against #3752. The family plugs into the existing embeddings path rather than a parallel stack: detection arm and ModelType in every registration table, build_family_model in the shared loader, EmbeddingEngine for /v1/embeddings and mlxcel embed, resolve_pooling_mode for 1_Pooling (cls), and engine-side L2 normalization. Image items reach the processor through the route's shared bounded fetch_labeled_image. It reuses the ModernBERT encoder (split into embed_tokens / encode_embeddings, encode unchanged), the LFM2-VL SigLIP2 tower, the Granite 4 Vision Q-Former layer (eps now a parameter, Granite 4 Vision passes its old constant) and the antialiased position resampler. Text and image vectors both come from the same ModernBERT CLS row, so they share one space.

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

  • synthetic_checkpoint_embeds_text_and_images_through_the_engine: a tiny random-weight checkpoint on disk, loaded through load_embedding_model (detection, cls + include_prompt: false, tokenizer placeholder check). It checks unit text vectors, padded micro-batch vs single-row parity, the <image> InvalidRow on row 1, image token counts on square and rectangular grids (6 and 10), and that different images embed differently.
  • input_embeddings_route_extra_vocabulary_and_image_rows: an extra-vocabulary id reads additional_embedding[0], regular ids read their own rows, expanded image placeholders read exactly the connector rows, and placeholders without images are rejected.

Both take mlx_test_guard(). Merged current main (one conflict in src/models/mod.rs against the new granitemoe module, resolved by keeping both).

Validation (GB10, CUDA, under gpu-lock): focused lib tests granite_embedding_vision modernbert granite4_vision lfm2_vl kimi_vl embeddings:: detection_tests registry metadata_tests 453 passed; --bin mlxcel family_order passed; tests/mlx_test_guard_coverage.rs passed; cargo clippy --all-targets -- -D warnings clean on default features and with --features cuda; cargo fmt --check, check_used_by.py, check_env_var_docs.py and the license header check pass.

Not run here: real-checkpoint parity. ibm-granite/granite-embedding-748m-vision-r2 is not in this host's model store, so the parity figures in the PR body are the author's.

Minor note, not changed: token-id inputs are bounded by text_config.vocab_size (262152), so the 40 extra-vocabulary ids are accepted through text but rejected with a 400 through token-id rows. That is stricter, not unsafe.

@inureyes
inureyes merged commit 73d2da4 into lablup:main Dec 4, 2026
36 checks passed
@inureyes inureyes added status:done Completed and removed status:review Under review labels Dec 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:models Model architectures, weights, loading, metadata modeltype:vlm Vision-language model priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(models): support Granite Embedding Vision R2 (modernvbertr2_granite_naflex_qformer)

2 participants