Skip to content

fix MPS errors#3818

Merged
tomaarsen merged 3 commits into
huggingface:mainfrom
omkar-334:mps-fixes
Jun 12, 2026
Merged

fix MPS errors#3818
tomaarsen merged 3 commits into
huggingface:mainfrom
omkar-334:mps-fixes

Conversation

@omkar-334

Copy link
Copy Markdown
Contributor

Three spots in the library still hardcode CUDA, even though MPS is listed as a supported device in get_device_name(). This PR fixes them.

What changes

  1. sparse_encoder/model.py: SparseEncoder.sparsity() calls to_sparse_csr(),
    which has no kernel on SparseMPS. Wrapped in try/except NotImplementedError with a CPU fallback. The result is a Python float so it's bit-identical, and the fallback covers any other backend missing the kernel too.

  2. sentence_transformer/fit_mixin.py and cross_encoder/fit_mixin.py: fit(use_amp=True) was hardcoded to torch.cuda.amp.GradScaler() (and to from torch.cuda.amp import autocast in the SentenceTransformer side). Now both files dispatch on device.type: cuda and npu keep their existing namespaces, everything else (mps, xpu, cpu) goes through torch.amp.*.

Testing

Ran the small examples on Apple Silicon end to end against this branch, without PYTORCH_ENABLE_MPS_FALLBACK. All passed:

  • SparseEncoder smoke (encode, sparsity, similarity, intersection on naver/splade-cocondenser-ensembledistil)
  • computing_embeddings.py
  • clustering/agglomerative.py, clustering/kmeans.py
  • semantic-search/semantic_search.py
  • cross_encoder/applications/cross_encoder_usage.py

I also tried the heavier retrieval examples (Quora 100k with pytorch top-k, HNSWlib, Annoy). Those work too.

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

Overall this looks good! I made a small comment to shrink the new comment a bit. Thanks for verifying that this works on your hardware 🤗

Comment thread sentence_transformers/sparse_encoder/model.py Outdated
@tomaarsen
tomaarsen enabled auto-merge (squash) June 12, 2026 10:04
@tomaarsen
tomaarsen merged commit 77fdbff into huggingface:main Jun 12, 2026
18 checks passed
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