Skip to content

Fix EmbeddingGemma 2 image orientation and batch text embeddings - #692

Merged
davidkoski merged 7 commits into
ml-explore:mainfrom
aleroot:embedding_gemma2_optimisation
Nov 3, 2026
Merged

davidkoski merged 7 commits into
ml-explore:mainfrom
aleroot:embedding_gemma2_optimisation

Conversation

@aleroot

@aleroot aleroot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Proposed changes

Just noticed some issues when integrating #684 into my app, so below the proposed fixes:

  • Fix image orientation. EmbeddingGemma2ImageProcessor.prepared set applyOrientationProperty with settingProperties, which does not rotate the image. Photos with an EXIF orientation (most phone photos) were embedded sideways. It now reads the EXIF orientation and applies it with oriented(_:). Video frames go through the same path. An image that was already oriented on decode carries no orientation, so it is never rotated twice.
  • Batch text embeddings. EmbeddingGemma2Embedding.embed(_:task:dimensions:) embedded every item alone. Text-only items now run in padded, masked batches sorted by length, at most 1,024 tokens each; a longer item runs alone. Items with media still run one at a time.
    • Add a shared contract for multimodal embedders. MultimodalEmbedding (with EmbeddingInput, EmbeddingTask, EmbeddingModality) gives every model that maps text and media into one space the same API; each model renders the task as its own prompt. MultimodalEmbeddingFactory loads a supported checkpoint by model_type, so apps need no model-specific code. EmbeddingGemma2Embedding conforms; its Input, Task and Modality names are now typealiases to the shared types, so the existing API does not change.

Benchmarks (MacBook Pro M2 16GB, embeddinggemma-2-bf16, 64 document chunks)

Tokens per batch Time
One at a time 4.20 s
1,024 2.45 s
8,192 2.81 s

Batches larger than 1,024 tokens use more memory and are not faster.

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:

@aleroot

aleroot commented Oct 13, 2026

Copy link
Copy Markdown
Contributor Author

If the design is accepted(see MultimodalEmbedding.swift), then Qwen3VLEmbedding (#665) will be adapted to conform and registers in the factory as well.

@spokvulcan spokvulcan mentioned this pull request Oct 13, 2026
4 of 5 tasks
davidkoski pushed a commit that referenced this pull request Oct 14, 2026
targetLoaderExcludesConvertedMTPComponent(vision: true) has failed on main
since #545 made the Qwen 3.5 VLM load its vision tower on first use: the
test counted parameters before the vision tower loads. It now loads with
componentLoading: .immediate and compares key sets, as #692 does.

testActiveSpeculativeDecodingReusesAlignedStorageAcrossTurns fails about one
run in a hundred. When the last speculative round accepts every draft, the
iterator leaves the last draft for the next round to feed, so the draft cache
ends one token behind the main cache and the next ChatSession turn rebuilds
both caches. finalizeGeneration now feeds that draft when it was returned,
unless the task is cancelled. Two tests that recorded the lag now expect both
caches at the same offset, and the Harmony tool-call restart now resumes on
both caches.
case codeRetrieval
case sentenceSimilarity
/// The input is embedded as given, without a task instruction.
case none

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.

Just a caution on none -- this can conflict with Optional's none. It doesn't look like that is a problem here because it is never optional.

/// The task an embedding is prepared for. Each model renders it as its own instruction.
/// Use `.searchQuery` for queries and `.document` for corpus items; compared items must
/// share a task's space.
public enum EmbeddingTask: Hashable, Sendable {

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.

Does this belong in MLXLMCommon? Everything else in this file is specific to VLMs, so perhaps not.

/// let vectors = try await embedding.embed(
/// [.init(text: "Aurora over Balestrino", images: [.url(photo)])], task: .document)
/// ```
public enum MultimodalEmbeddingFactory {

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.

Should this implement GenericModelFactory?

public final class EmbedderModelFactory: GenericModelFactory {

    public typealias ContextType = EmbedderModelContext
    public typealias ContainerType = EmbedderModelContainer

then it would be the same as all the others. The hard coded registry at the end could use the same pattern like EmbedderTypeRegistry.

@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.

Change looks good overall. I think my only real question is on the MultimodalEmbeddingFactory -- should this be a custom type like this or use the (more complicated) GenericModelFactory machinery?

A benefit of the latter is that it comes with registries that can be updated outside the library.

@aleroot

aleroot commented Oct 16, 2026

Copy link
Copy Markdown
Contributor Author

Change looks good overall. I think my only real question is on the MultimodalEmbeddingFactory -- should this be a custom type like this or use the (more complicated) GenericModelFactory machinery?

A benefit of the latter is that it comes with registries that can be updated outside the library.

Ah yes, sorry I should have followed the standard already in the lib, my mistake. I have corrected updating to GenericModelFactory with extensible type and model registries, following the existing factory pattern.

Let me know if now works. Thanks

Comment on lines +123 to +126
private static let resizeAxis = MLXFast.metalKernel(
name: "embedding_gemma2_resize_axis",
inputNames: ["pixels", "weights", "parameters"], outputNames: ["output"],
source: """

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.

I think this could be called with different pixel dtypes -- I wonder if this needs:

        template: [("T", pixels.dtype)],

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good question. I checked this: MLX generates the input pointer type from pixels.dtype and includes the dtype in the kernel cache key, so T isn’t needed here. I also added a test alternating float16 and float32 inputs on CPU and GPU.

@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.

Question on the custom kernel, otherwise this looks ready to go. Thanks!

@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.

Looks good, thank you!

@davidkoski
davidkoski merged commit eccf774 into ml-explore:main Nov 3, 2026
4 checks passed
djandrewgibbons pushed a commit to djandrewgibbons/mlx-swift-lm that referenced this pull request Nov 3, 2026
…explore#692)

* Fix EmbeddingGemma 2 image orientation and batch text embeddings
* Add MultimodalEmbedding contract and factory for media embedding models
* ⚡ Embeddings: Reduce EmbeddingGemma 2 image preprocessing memory

Keep source pixels in half precision and cast samples during the antialiased
resize. This removes full-resolution float32 staging while preserving JPEG's
extended range and the CPU path.

Add pixel comparisons for PNG/JPEG, CPU/GPU execution, and resize shapes.

AI assistance: Codex implemented the code and tests.
ximyro pushed a commit to ximyro/mlx-swift-lm that referenced this pull request Nov 4, 2026
Upstream commits: ml-explore#637 MiniCPM5 tool call parser, ml-explore#743 integration tests on Xcode 27,
ml-explore#729 and ml-explore#692 EmbeddingGemma 2, ml-explore#715 guided-generation schema, ml-explore#747 RotatingKVCache
pinned prefix in multi-token masks, ml-explore#581 resumable Qwen MTP speculative decoding.

Conflicts: Libraries/MLXVLM/EmbeddingGemma2.swift (took the upstream bodies, kept the
fork's _Concurrency.Task spelling), .github/workflows/pull_request.yml (kept the fork's),
.github/workflows/integration_tests.yml (kept deleted, as in the fork).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
wballard added a commit to swissarmyhammer/mlx-swift-lm-old that referenced this pull request Nov 5, 2026
Apply the upstream commits efcedcd..c8dabc6 (the 25 after 991266a) as
cherry-picks. CLAUDE.md is untouched. Where a conflict was only a fork
refactor, upstream's code is taken; the fork's MTP speed and prompt-cache
behavior is kept.

- efcedcd Gemma 4 VLM: expose hidden states for a prepared input (ml-explore#730)
- 3d066d3 mlx-swift 0.33.0 (ml-explore#720)
- 39b92df Read Gemma 3 RoPE scaling from rope_parameters (ml-explore#723)
- c358cea Throw when Bert id2label keys share an integer id (ml-explore#736)
- c3d3afe FastVLM: Keep image sentinels out of the repetition-penalty history (ml-explore#735)
- 72a4673 Fix attention masks sized from the absolute cache offset (ml-explore#728)
- cf9b7e9 Prefill over a quantized KV cache through the fused SDPA kernel (ml-explore#703)
- ef36109 Add reasoning streaming events and support Gemma 4 channels (ml-explore#563)
- 691a19a Support Nemotron 3.5 (Lightning, Bolt, Super) text models (ml-explore#712)
- f5b0677 Expose Qwen 3.5 text geometry read-only (ml-explore#737)
- c2f1073 Add GrammarConstraint.freshMatcher() (ml-explore#732)
- 411d8e7 Feed the sampled token before its fast-forward tokens (ml-explore#731)
- 71cc028 MLXFoundationModels: let MLXLanguageModel set the prefill step size (ml-explore#745)
- 52e6001 Report model tensor buffer memory (ml-explore#746)
- 128f49f Use the MLXFast gated delta kernel where mlx core supports it (ml-explore#740)
- 35bd2c9 Add MiniCPM5 Tool Call Parser (ml-explore#637)
- c611a3f integration tests to run using xcode 27 (now that it is released) (ml-explore#743)
- bb36fc3 EmbeddingGemma 2: soft tokens for every row of a batch (ml-explore#729)
- b8d4935 Show the response schema to the model during guided generation (ml-explore#715)
- 2775ddd RotatingKVCache: keep the pinned prefix visible in multi-token masks (ml-explore#747)
- eccf774 Fix EmbeddingGemma 2 image orientation and batch text embeddings (ml-explore#692)
- ffe7647 Add resumable Qwen MTP speculative decoding to ChatSession (ml-explore#581)
- 327d92d Put images before text in GLM-OCR prompts (ml-explore#765)
- 2fdad9e Keep Nemotron-H Mamba activations in the input dtype (ml-explore#754)
- c8dabc6 Fix the x86_64 build of the EmbeddingGemma 2 image processor (ml-explore#763)

mlx-swift 0.33.0 (MLX core 0.32.4 line):
- MultiRowQuantizedMatvec: widen each input before the 4-bit pack sum, as
  qmv_fast now does, so verify rows keep the bits of a decode step.
- GatedDeltaDecodeKernel and the DeepSeek-V4 Sinkhorn kernel: the sigmoid
  reads metal::precise::exp, as MLX Sigmoid now does (mlx#4461).

Conflicts and choices:
- ml-explore#563: Generation.reasoning carries thinking apart from .chunk on every
  path (textToolHandler takes reasoningPrimedInside, read before the
  prefill). ChatSession records the content with the finished reasoning
  beside it, and prefilledReasoningStartDelimiter, as upstream does;
  ReasoningHistory keeps one fork rule: a protocol that replays reasoning
  also replays a turn cut off inside it, so the next render extends the
  cache. Upstream's Qwen3VL generator replaces separatingImportedReasoning;
  the fork's whole-text helpers (separating, staysInsidePrimedReasoning,
  the duplicate prompt probe) are gone. FM ports the thinking gate fix,
  routed reasoning on allowed-tool turns, and ReasoningTokenCollector.
  Benchmark transcripts count .reasoning.
- ml-explore#581: the fork already holds the port of the PR and the MTP work on it.
  The later transcript rebuild after a target-only turn is not taken: the
  fork cold-starts the drafter at the cached position and keeps the target
  cache. Recorded as an empty pick.
- ml-explore#740: MLXFast gated delta for prefill and fallbacks; decode and MTP
  verify keep the fork kernels.
- ml-explore#745: same public API; the executor reads the step size from a
  task-local, as drainCoordinator, and makeParameters defaults to it.
- ml-explore#715: the schema prompt is built after the fork's history replay. A
  session that changes schema between turns changes its system prompt.
- ml-explore#703: quantizedCacheAttention carries the fork's attention sinks.
- ml-explore#728, ml-explore#747, ml-explore#731, ml-explore#735: applied to the split files; ml-explore#747 and ml-explore#731 were
  already fixed in the fork.
- ml-explore#732: the fork's xgrammar v0.1.34 keeps Fork(); the clone tests stay on.

Tests: MLXLMTests 964 XCTest and 2278 Swift Testing tests pass.
MLXGuidedGenerationTests 76, MLXFoundationModelsTests 493, CXGrammarTests 7,
MLXHuggingFaceMacrosTests 7 pass. HybridRecurrentCacheOffsetTests pass;
nemotron_h_puzzle reuses NemotronHModel. Release, M5 Ultra:
Qwen35SessionPromptCacheTests, Qwen35AgenticPromptCacheAssessmentTests,
PromptCacheSpoolCostAssessmentTests, qwen38FourBitMTPGeneration and
qwen38FourBitMTPSystemPromptCache pass (each run alone). Default MTP
math/code ~94-100 / 85 tok/s against plain ~57; edit turn reuses 2169 and
prefills 123.

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.

3 participants