Spaces:
Running
MaxSim kernel for Apple Silicon (Metal)
Hi all!
I previously contributed the MPS speedup for community_detection in sentence-transformers (#4265), and lately I've been playing with the late-interaction kernels that landed there (#4344). I noticed they're CUDA-only, so on a Mac use_kernels=True just quietly falls back to the plain PyTorch path.
So I wrote a Metal version of MaxSim that follows the late-interaction-kernels layout: a torch-metal noarch kernel, with the shader compiled at runtime, so users don't need Xcode. On M5 it uses the Metal 4 tensor ops, and on older Macs it falls back to a regular shader. It also has a backward pass, so it works for training too.
It builds fine with kernel-builder, passes the get_kernel check, and works end to end with sentence-transformers.
Some numbers on an M5 Max (fp16, query length 32, dim 128), compared with sentence_transformers.util.maxsim on MPS:
| queries | docs | doc len | inference | training (fwd+bwd) |
|---|---|---|---|---|
| 16 | 1,000 | 180 | 11.0 โ 1.0 ms | 27.4 โ 8.8 ms |
| 16 | 10,000 | 180 | 105 โ 8.0 ms | 306 โ 82 ms |
| 16 | 5,000 | 512 | 133 โ 10.5 ms | 354 โ 57 ms |
| 64 | 1,000 | 180 | 41.6 โ 3.4 ms | 83.0 โ 29.9 ms |
I've requested kernel publishing access so I can put it on the Hub. Then I'll check with the sentence-transformers team whether they want it in the official repo.
Hello!
Tom Aarsen here, Sentence Transformers maintainer. First of all, I want to share that the original https://huggingface.co/kernels/sentence-transformers/late-interaction-kernels work wasn't done by me, so I'd have a hard time reviewing an updated variant. Having said that, I do think it's valuable for better hardware support. I'm not quite sure what would work best there:
- Mention your metal version in the ST Documentation, i.e. show users they can pass
kernels_config={...}pointing to your Metal version, or - Automatically select your revision-pinned kernel when
use_kernels=Trueif the user is will be using the "mps" device
Either way, I'd be glad to recommend you to get kernel publishing access, and I think overall that would be valuable!
- Tom Aarsen
Thanks @sayakpaul for the publishing access, and @tomaarsen for the recommendation and the integration suggestion!
The kernel is now published at m4zar/maxsim-metal, and I've opened sentence-transformers#4432 to select it automatically on mps with a pinned revision.