Skip to content

Add model-defined pooling fallback for embedding models - #156

Merged
davidkoski merged 2 commits into
ml-explore:mainfrom
sxy-trans-n:codex/fix-embedding-pooling
Mar 27, 2026
Merged

davidkoski merged 2 commits into
ml-explore:mainfrom
sxy-trans-n:codex/fix-embedding-pooling

Conversation

@sxy-trans-n

Copy link
Copy Markdown
Contributor

Proposed changes

This PR fixes embedding pooling for models that do not include sentence-transformers pooling metadata such as 1_Pooling/config.json.

In MLXEmbedders, pooling previously fell back to .none when 1_Pooling/config.json was missing. For Qwen3 embedding models, that meant returning raw hidden states instead of a fixed-size sentence embedding.

This PR adds a model-defined pooling fallback and uses it for Qwen3 embedding models. It also fixes .last pooling so it selects the last non-padding token instead of always taking the final sequence position.

Concretely, this change:

  • adds poolingStrategy to EmbeddingModel
  • makes loadPooling(...) prefer 1_Pooling/config.json, then fall back to the model-defined pooling strategy
  • declares Qwen3 embedding pooling as .last
  • makes .last pooling respect the attention mask

This fixes cases where converted embedding repos are missing 1_Pooling/config.json and would otherwise produce variable-length embeddings depending on token count.

Validated end-to-end in swama with mlx-community/Qwen3-Embedding-0.6B-4bit-DWQ:

  • "" returns 1024 dims
  • "hello world" returns 1024 dims
  • mixed-length batches also return stable 1024-dim embeddings

Checklist

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

Comment thread Libraries/MLXEmbedders/Pooling.swift Outdated
tokenCounts.enumerated().map { batchIndex, count in
let tokenIndex = max(Int(count) - 1, 0)
return hiddenStates[batchIndex, tokenIndex, 0...]
})

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 requires a read back from the GPU (the asArray) which may not be desired here.

Maybe something like this, but check my math:

// shape: [batch]
let tokenCounts = sum(_mask.asType(.int32), axis: -1)

// shape: [batch]
let tokenIndices = maximum(tokenCounts - 1, 0)

// shape: [batch, 1, 1]
let indices = expandedDimensions(tokenIndices, axes: [1, 2])

// hidden states shape: [batch, sequence, hidden]
// gathered shape: [batch, 1, hidden]
let gathered = takeAlong(hiddenStates, indices, axis: 1)

// squeeze down to [batch, hidden]
pooled = squeezed(gathered, axis: 1)

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 catch. I updated this to use pure MLX tensor ops with takeAlong instead of reading indices back with asArray, so .last pooling now stays on-device and still selects the last non-padding token.

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

  • don't eval in pooling if we can avoid it

@sxy-trans-n
sxy-trans-n requested a review from davidkoski March 24, 2026 01:56

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

Changes look good, thank you for this!

@davidkoski
davidkoski merged commit af777ae into ml-explore:main Mar 27, 2026
2 checks passed
TheTom referenced this pull request in TheTom/mlx-swift-lm Apr 5, 2026
* Add model-defined pooling fallback for embedding models

* Use takeAlong for last-token pooling
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants