Skip to content

Add EmbeddingGemma 2 full support - #684

Merged
davidkoski merged 1 commit into
ml-explore:mainfrom
aleroot:alessio/public-gemma4-vision-encoder
Oct 12, 2026
Merged

davidkoski merged 1 commit into
ml-explore:mainfrom
aleroot:alessio/public-gemma4-vision-encoder

Conversation

@aleroot

@aleroot aleroot commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

Proposed changes

EmbeddingGemma 2 maps text, images, video and audio into one embedding space, and one input can interleave them. It is a bidirectional encoder, not a chat model, so the VLM factory cannot load it.

From my personal point of view: the best embedding model I have tried in general!

Checked against the Transformers default SDPA path, the one Sentence Transformers uses: cosine 0.9999 for audio, video and interleaved inputs, and 0.99995 at 2,880 and 7,490 tokens.

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

AI usage

  • I have read this PR description in full and approve it as my own, and it
    accurately describes the code changes.
  • AI usage disclosure: used several models to develop the features with my Lampo app in coding agent mode, and verified with grok 4.7 code review.

@CodebyCR

CodebyCR commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Thanks for this, the results look great!
I plan to build on it instead of writing my own port.

One request:
The Gemma 4 encoders in MLXLMCommon/Models/Gemma4Encoders.swift are now public (Gemma4VisionModel, Gemma4AudioModel, Gemma4MultimodalEmbedder, and the configurations). Could you make them package instead? MLXVLM and MLXEmbedders can still use them, but they don't become new public API of MLXLMCommon. davidkoski suggested package for this in #682.
In #682 I'm also proposing a MLXMediaEncoders target for these encoders. If that gets the go-ahead, they would move there, either in this PR or right after it, whatever you prefer.

@aleroot

aleroot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for this, the results look great! I plan to build on it instead of writing my own port.

One request: The Gemma 4 encoders in MLXLMCommon/Models/Gemma4Encoders.swift are now public (Gemma4VisionModel, Gemma4AudioModel, Gemma4MultimodalEmbedder, and the configurations). Could you make them package instead? MLXVLM and MLXEmbedders can still use them, but they don't become new public API of MLXLMCommon. davidkoski suggested package for this in #682. In #682 I'm also proposing a MLXMediaEncoders target for these encoders. If that gets the go-ahead, they would move there, either in this PR or right after it, whatever you prefer.

I can change them to package, but there is a reason why I opened them public: if in the future someone wants to built its own let's say embedding Gemma 3 or whatever on the architecture and have it closed in its own app without sharing it here, he would be able to do it...

@davidkoski let me know if you want them package, or if we want to leave more freedom for the clients of the library to use them...

@davidkoski

Copy link
Copy Markdown
Member

Re: package vs public -- I think it can be an individual call per model. If they might be useful to code outside of mlx-swift-lm then public makes sense. I originally suggested package to avoid filling the public API with implementation details. I guess another option is to use _spi to make it a little more clear that you are adopting internals.

Right now you have the model name as part of each of the types, e.g. EmbeddingGemma2XXX. Another option would be to put them in a namespace, maybe an enum. It nicely nests the types, but has the drawback that it also indents the code :-) Probably worth a thought to see if it would make it better or not.

One last thought: I think it is ok to try some things out. We can make them package and expose them later if people want them to be public (that is probably the safer route in terms of API). It is ok to make them public and see if people make use of them.

My inclination would be to make them package, but I don't think it is a hard requirement. Since this is open source we can be a little more malleable than yearly binary releases. There isn't a clear winner in the approach, just some potential tradeoffs each way.

@rurza

rurza commented Oct 11, 2026

Copy link
Copy Markdown

Thanks for this — we've been evaluating EmbeddingGemma 2 for on-device search in an iOS/macOS app and ran your branch as a text-only user, in case the data helps.

Setup: text tower only — mlx-community/embeddinggemma-2-4bit with every vision/audio tensor removed (~176 MB), plain tokenizer, no processor.

Parity (macOS): against transformers running on the same dequantized weights, cosine min 0.9998 / mean 0.9999 on short queries and 512-token documents; 0.99997 on 1k/2k/4k-token inputs (beyond the sliding window); a right-padded batch (3 / 15 / 512 / 4000 tokens) matches one-by-one runs at ≥ 0.99994.

iPhone 14 Pro (6 GB): load 0.59 s, ~208 s per 1,000 documents at 512 tokens, peak footprint ~391 MB. On a small Polish/English retrieval set (31 docs, 32 queries), MRR 0.94, cross-language 0.90 — identical to the full-precision model in sentence-transformers.

Three things a text-only user runs into:

  1. If config.json still has vision_config / audio_config but the weights are absent, loading fails (keyNotFound vision_tower.patch_embedder…). Removing the keys fixes it; skipping a tower whose weights are missing, or a clearer error, would help.
  2. hiddenStates is always nil, so code that pools or post-processes per token crashes on a force-unwrap; only pooledOutput is usable. Worth a doc note.
  3. Input is cut at a fixed 8,192 tokens rather than a value from the config.

AI disclosure: the measurements and this summary were prepared with an AI coding assistant (Claude); I reviewed the method and the results before posting.

@aleroot

aleroot commented Oct 12, 2026

Copy link
Copy Markdown
Contributor Author

@davidkoski, regarding the text-only loading issue @rurza reported, would it make sense to merge #580 first, then adopt its component-loading infrastructure for EmbeddingGemma 2’s vision and audio towers?
That would let text-only users load the model without modifying config.json, while loading the media encoders on first use.
Thanks!

@aleroot
aleroot force-pushed the alessio/public-gemma4-vision-encoder branch 2 times, most recently from 3b5f26c to 7cd9b8b Compare October 12, 2026 05:29
@aleroot

aleroot commented Oct 12, 2026

Copy link
Copy Markdown
Contributor Author

Re: package vs public -- I think it can be an individual call per model. If they might be useful to code outside of mlx-swift-lm then public makes sense. I originally suggested package to avoid filling the public API with implementation details. I guess another option is to use _spi to make it a little more clear that you are adopting internals.

Right now you have the model name as part of each of the types, e.g. EmbeddingGemma2XXX. Another option would be to put them in a namespace, maybe an enum. It nicely nests the types, but has the drawback that it also indents the code :-) Probably worth a thought to see if it would make it better or not.

One last thought: I think it is ok to try some things out. We can make them package and expose them later if people want them to be public (that is probably the safer route in terms of API). It is ok to make them public and see if people make use of them.

My inclination would be to make them package, but I don't think it is a hard requirement. Since this is open source we can be a little more malleable than yearly binary releases. There isn't a clear winner in the approach, just some potential tradeoffs each way.

Adopted the suggested approach. Rebased on latest main as well.

@davidkoski

Copy link
Copy Markdown
Member

Yeah, I will review 580 next.

@davidkoski

Copy link
Copy Markdown
Member

#580 is merged

Support text, images, video, audio, and interleaved embeddings. Load vision
and audio on first use through the shared component loader, preserving an
immutable model tree and keeping text-only checkpoints usable without
processor files. Keep shared encoder implementations package-scoped.

Add reference, component lifecycle, and real-checkpoint integration tests.
@aleroot

aleroot commented Oct 12, 2026

Copy link
Copy Markdown
Contributor Author

#580 is merged

Rebased on latest main and tested with mlx-community/embeddinggemma-2-8bit. Initial live MLX memory measured 288 MB versus 1.23 GB . Vision and audio load independently on first use through #580’s component infrastructure, so text-only use avoids loading either encoder.

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks great, thank you!

@davidkoski
davidkoski merged commit 028a828 into ml-explore:main Oct 12, 2026
5 checks passed
kpmmmurphy added a commit to Round-Tower/M1K3 that referenced this pull request Nov 15, 2026
…e space as text (part of #836) (#846)

* test(embedder): mlx-vlm reference vectors for twelve generated images and their captions (#836)

The reference generator renders twelve drawings (Pillow, deterministic, ours to commit), runs them through
mlx-vlm 3d87e884's vision tower and stores the 768 and 512 vectors, a query and a caption text case per image,
and text-to-image ranking checks. The text rows are byte-identical to the committed ones (mlx pinned to 0.32.3
in the uv command; 0.32.4 shifts them by 1e-3). The weight-key fixture gains the 211 vision keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TDD-Skip: fixture-generator script (Pillow drawings); its output is pinned by EmbeddingGemma2ReferenceTests

* feat(embedder): EmbeddingGemma 2 vision encoder, image path and embedImage (#836)

Ports the Gemma 4 vision tower, the multimodal projection and the image processor's sizing and bicubic
resampling from ml-explore/mlx-swift-lm#684 (credited in the headers; the pin stays on 3.32.x). An image is
<bos><boi><image>xn<eoi><eos> with no prompt text (the model card: prefixes are for text), under its own
image-prompt-v1 in imageFingerprint. The tower loads lazily on the first image and drops on a memory warning.
The text core is split into scaledEmbeddings + forward so soft tokens can be substituted between them; the
text fingerprint is pinned as a literal. Numeric parity is the in-app stage's, next.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(selftest): EG2REF checks image vectors against mlx-vlm and measures RAM, time and the floor inputs (#836)

The stage now runs the fixture's twelve images through embedImage: cosine >= 0.999 at 768 and 512, the relevance
order and top-1, per-image time and memory, drop-and-reload, the text-to-image cosine distributions against
text-to-text, the mixed text+image crowding check and what the text floors would admit. A SHA-256 over the text
vectors proves the text path is bit-identical across builds. The vision encoder evaluates one layer at a time:
MLX peak 1,309 MB -> 832 MB for ~30 ms an image. Parity measured in-app: min cosine 0.99993, top-1 12/12.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TDD-Skip: in-app SelfTest stage (metallib wall keeps it out of swift test); verified by running it, output in docs/evals/2026-11-15-eg2-vision

* docs(evals): EmbeddingGemma 2 vision parity, RAM, time and the text-to-image floor inputs; a proposed floor, unsigned (#836)

Measurements from the in-app reference stage on an M1 Max: image cosine 0.99993 vs mlx-vlm, top-1 12/12, +320 MB
resident for the tower, ~270 ms an image, text digest bit-identical to master. The text-to-image dead zone is
0.681 to 0.707 on twelve drawings; 0.69 is PROPOSED for challenger and is not signed. EmbedderFloors untouched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(embedder): vision path review fold: guarded MLX reads, Pillow resample order, one resample, image-v2 (#836)

Guarded loads and forward pass (an MLX error throws visionFailed), distinct vision errors, a weak latest-target
memory-pressure watcher registered before the throwing steps and cancelled on deinit, Pillow's horizontal-then-vertical
rounded resample with a full-size decode (8,192 px cap, no thumbnail filter), a cap on the weight allocation for
extreme aspect ratios, image-v2 covering preprocessing, decode tests (alpha, gray, 1x1, tiny, EXIF, corrupt), a
photo-sized noisy fixture checked in-app at 0.99995, a NOTICE line for the ported MIT code, README divergences.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(embedder): log a refused vision tower under the catalogued mlx-load category (#836)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(evals): EG2REF output from the final tree (image-v2, noisy frame) (#836)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants