Feature Extraction
sentence-transformers
Safetensors
slideon
sparse
sentence-similarity
custom-code
multilingual
code-search
sparse-retrieval
matryoshka
custom_code
🇪🇺 Region: EU
Run this model with HF Jobs
Run lightonai/mSlideOn on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/lightonai/mSlideOn. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/lightonai/mSlideOn on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use lightonai/mSlideOn with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- sentence-transformers
How to use lightonai/mSlideOn with sentence-transformers:
from sentence_transformers import SentenceTransformer model = SentenceTransformer("lightonai/mSlideOn", trust_remote_code=True) sentences = [ "The weather is lovely today.", "It's so sunny outside!", "He drove to the stadium." ] embeddings = model.encode(sentences) similarities = model.similarity(embeddings, embeddings) print(similarities.shape) # [3, 3] - Notebooks
- Google Colab
- Kaggle
Commit ·
e0a39b0
0
Parent(s):
Initial release
Browse filesFiles changed (10)
- .gitattributesAdded+36
- README.mdAdded+307
- config.jsonAdded+143
- config_sentence_transformers.jsonAdded+12
- model.safetensorsAdded+3
- modeling_slideon.pyAdded+216
- modules.jsonAdded+8
- slideon.pyAdded+96
- tokenizer.jsonAdded+3
- tokenizer_config.jsonAdded+26
123456789101112131415161718192021222324252627282930313233343536*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -texttokenizer.json filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307---library_name: sentence-transformerspipeline_tag: feature-extractionbase_model: lightonai/mLateOnbase_model_relation: finetunelanguage:- en- fr- de- it- es- pt- sv- "no"- ar- codedatasets:- lightonai/embeddings-fine-tuning-filtered-en- lightonai/embeddings-fine-tuning-filtered-fr- lightonai/embeddings-fine-tuning-filtered-de- lightonai/embeddings-fine-tuning-filtered-it- lightonai/embeddings-fine-tuning-filtered-es- lightonai/embeddings-fine-tuning-filtered-pt- lightonai/embeddings-fine-tuning-filtered-sv- lightonai/embeddings-fine-tuning-filtered-no- lightonai/embeddings-fine-tuning-filtered-ar- lightonai/embeddings-fine-tuning-filtered-code- lightonai/embeddings-fine-tuning-filtered-code-edittags:- sentence-transformers- sentence-similarity- custom-code- multilingual- code-search- sparse-retrieval- matryoshka---<div align="center"><img src="https://cdn-uploads.huggingface.co/production/uploads/67e184d667350657a7d68aac/5PySy2cTawrkFWwaqNtDA.png" alt="SlideOn and mSlideOn: a puppy sliding through a library with a bag of glowing stars" width="512" style="max-width: 100%; height: auto;">
[](https://lighton.ai)[](https://www.linkedin.com/company/lighton/)[](https://x.com/LightOnIO)
📚 [Collection](https://huggingface.co/collections/lightonai/slideon-and-mslideon) | 📝 [Blogpost](https://huggingface.co/blog/lightonai/slideon-mslideon) | 🛠️ [Training and Evaluation](https://github.com/lightonai/slideon-mslideon/)
</div>
<h1 align="center">mSlideOn</h1><h3 align="center">Multilingual Sparse Retrieval Model by LightOn</h3>
<p align="center"><a href="https://huggingface.co/lightonai/SlideOn">SlideOn</a> |<a href="https://huggingface.co/lightonai/mSlideOn">mSlideOn</a> |<a href="https://huggingface.co/lightonai/SlideOn-SAE">SlideOn-SAE</a> |<a href="https://huggingface.co/lightonai/mSlideOn-SAE">mSlideOn-SAE</a></p>
> 🎯 **TL;DR**: A **339M-parameter multilingual sparse retrieval model** built from mLateOn through sparse autoencoder (SAE) pretraining and supervised retrieval fine-tuning. mSlideOn improves on mDenseOn by **4.76 points on MIRACL** and **10.19 points on MLDR**, and reaches **74.78 on MTEB Code**, surpassing both mDenseOn and mLateOn. It brings multilingual, long-context, and code retrieval to sparse representations compatible with inverted-index search, with **Matryoshka training** for adjustable query and document sparsity.
## About the SlideOn / mSlideOn Family
With [DenseOn and LateOn](https://huggingface.co/blog/lightonai/denseon-lateon), then [mDenseOn and mLateOn](https://huggingface.co/blog/lightonai/mdenseon-mlateon), we explored dense and late-interaction retrieval using our open data recipe. SlideOn and mSlideOn reuse these models' retrieval knowledge to learn sparse representations through SAE pretraining followed by supervised fine-tuning.
**SlideOn** starts from [DenseOn](https://huggingface.co/lightonai/DenseOn) for English retrieval. **[mSlideOn](https://huggingface.co/lightonai/mSlideOn)** starts from [mLateOn](https://huggingface.co/lightonai/mLateOn) for multilingual, long-context, and code retrieval. We release both the pretrained SAE initializations and the final retrieval models.
See our [blog post](https://huggingface.co/blog/lightonai/slideon-mslideon) for the full method, results, and ablations.
## mSlideOn
mSlideOn encodes queries and documents into **32,768-dimensional nonnegative sparse vectors**. Its sparse encoder lifts mLateOn's normalized 128-dimensional token representations to 768 dimensions and applies a residual MLP before selecting the top-32 latent activations and applying ReLU. Max pooling across tokens produces one vector per query or document, and retrieval uses the **dot product** between these vectors.
The dimensions are learned features, independent of the tokenizer vocabulary. Active latents can be stored in an inverted index, where query latents select posting lists and their weights contribute to document scores.
mSlideOn notably:
- Reaches **56.00 on BEIR-15**, the highest score among the multilingual sparse models in our comparison.- Reaches **63.21 on MIRACL target languages** and **62.78 across all 18 languages**, improving on mDenseOn by **4.76 points** on the full benchmark.- Reaches **75.79 on MLDR target languages** and **61.68 across all 13 languages**, outperforming every dense baseline in our comparison.- Reaches **74.78 on MTEB Code**, ahead of mDenseOn (**71.53**) and mLateOn (**73.48**).- Supports inputs of up to **8,192 tokens** and independently adjustable query and document sparsity.
## Results
### Headline Results (nDCG@10)
Scores are average nDCG@10 on a 0–100 scale. Sparse models use dot-product scoring and exact search over each full evaluation corpus. All rows use **unpruned query and document vectors**. Dense and late-interaction comparisons follow our [mDenseOn and mLateOn blog post](https://huggingface.co/blog/lightonai/mdenseon-mlateon).
**MIRACL tgt** covers Arabic, English, French, German, and Spanish; **MLDR tgt** covers Arabic, English, French, German, Italian, Portuguese, and Spanish. These are benchmark languages included in retrieval training. Full **MIRACL** covers 18 languages, full **MLDR** covers 13, and **MTEB Code** averages 12 retrieval tasks.
We evaluate **MIRACL** using the dev split of [mteb/miracl-hard-negatives](https://huggingface.co/datasets/mteb/miracl-hard-negatives) and **MLDR** using the test split of [mteb/MultiLongDocRetrieval](https://huggingface.co/datasets/mteb/MultiLongDocRetrieval).
<div style="width: fit-content; max-width: 100%; margin: 0 auto;"> <div style="overflow-x: auto;"> <table cellpadding="6" style="margin: 0 auto; border-collapse: collapse; color: inherit; text-align: right; font-size: 0.85em; line-height: 1.6; font-variant-numeric: tabular-nums;"> <thead> <tr style="border-bottom: 1px solid rgba(128, 128, 128, 0.35);"> <th scope="col" style="text-align: left;">Model</th> <th scope="col">Params.</th> <th scope="col">BEIR-15 ↑</th> <th scope="col">MIRACL tgt ↑</th> <th scope="col">MIRACL ↑</th> <th scope="col">MLDR tgt ↑</th> <th scope="col">MLDR ↑</th> <th scope="col">MTEB Code ↑</th> <th scope="col">FLOPS ↓</th> </tr> </thead> <tbody> <tr> <th colspan="9" scope="rowgroup" style="padding: 16px 6px 6px; text-align: left; font-size: 0.8em; letter-spacing: 0.08em; text-transform: uppercase;">Sparse</th> </tr> <tr> <td style="text-align: left; white-space: nowrap;"><strong style="color: #3b82f6;">mSlideOn</strong></td> <td style="color: #3b82f6;">339M</td> <td><strong style="color: #3b82f6;">56.00</strong></td> <td style="color: #3b82f6;">63.21</td> <td style="color: #3b82f6;">62.78</td> <td style="color: #3b82f6;">75.79</td> <td style="color: #3b82f6;">61.68</td> <td><strong style="color: #3b82f6;">74.78</strong></td> <td style="color: #3b82f6;">44.88</td> </tr> <tr><td style="text-align: left; white-space: nowrap;">BGE-M3</td><td>568M</td><td>40.20</td><td>46.55</td><td>55.48</td><td>71.82</td><td>62.13</td><td>42.03</td><td><strong>1.69</strong></td></tr> <tr><td style="text-align: left; white-space: nowrap;">gte-multilingual-base</td><td>305M</td><td>40.27</td><td>48.74</td><td>57.49</td><td><strong>80.19</strong></td><td><strong>70.75</strong></td><td>51.09</td><td>1.70</td></tr> <tr><td style="text-align: left; white-space: nowrap;">MILCO-300M</td><td>330M</td><td>53.33</td><td>64.11</td><td><strong>70.05</strong></td><td>62.74</td><td>51.78</td><td>41.25</td><td>17.43</td></tr> <tr><td style="text-align: left; white-space: nowrap;">MILCO-650M</td><td>593M</td><td>52.12</td><td><strong>64.14</strong></td><td>70.02</td><td>68.63</td><td>58.30</td><td>33.06</td><td>13.96</td></tr> <tr><td style="text-align: left; white-space: nowrap;">OpenSearch multilingual</td><td>168M</td><td>48.26</td><td>57.87</td><td>59.41</td><td>36.47</td><td>27.52</td><td>41.28</td><td>1.77</td></tr> </tbody> <tbody style="border-top: 1px solid rgba(128, 128, 128, 0.25);"> <tr> <th colspan="9" scope="rowgroup" style="padding: 16px 6px 6px; text-align: left; font-size: 0.8em; letter-spacing: 0.08em; text-transform: uppercase;">Dense</th> </tr> <tr> <td style="text-align: left; white-space: nowrap;"><strong style="color: #3b82f6;">mDenseOn</strong></td> <td style="color: #3b82f6;">307M</td> <td><strong style="color: #3b82f6;">56.70</strong></td> <td style="color: #3b82f6;">59.61</td> <td style="color: #3b82f6;">58.02</td> <td style="color: #3b82f6;">65.62</td> <td style="color: #3b82f6;">51.50</td> <td style="color: #3b82f6;">71.53</td> <td style="color: #3b82f6;">—</td> </tr> <tr><td style="text-align: left; white-space: nowrap;">pplx-embed-v1-0.6b</td><td>596M</td><td><strong>56.70</strong></td><td><strong>63.18</strong></td><td>68.20</td><td>57.08</td><td>43.98</td><td>75.18</td><td>—</td></tr> <tr><td style="text-align: left; white-space: nowrap;">jina-v5-text-small</td><td>677M</td><td><strong>56.70</strong></td><td>61.03</td><td>66.56</td><td>53.00</td><td>43.83</td><td>73.01</td><td>—</td></tr> <tr><td style="text-align: left; white-space: nowrap;">jina-v5-text-nano</td><td>239M</td><td>56.08</td><td>60.86</td><td>65.84</td><td>56.71</td><td>47.20</td><td>70.75</td><td>—</td></tr> <tr><td style="text-align: left; white-space: nowrap;">arctic-embed-l-v2</td><td>568M</td><td>55.55</td><td>60.78</td><td>66.53</td><td>57.01</td><td>48.03</td><td>53.17</td><td>—</td></tr> <tr><td style="text-align: left; white-space: nowrap;">Qwen3-Embedding-0.6B</td><td>596M</td><td>55.33</td><td>57.64</td><td>60.62</td><td>59.11</td><td>50.06</td><td>73.75</td><td>—</td></tr> <tr><td style="text-align: left; white-space: nowrap;">harrier-oss-v1-0.6b</td><td>596M</td><td>55.04</td><td>57.41</td><td>63.68</td><td>53.84</td><td>44.23</td><td>70.97</td><td>—</td></tr> <tr><td style="text-align: left; white-space: nowrap;">harrier-oss-v1-270m</td><td>268M</td><td>50.82</td><td>48.95</td><td>57.11</td><td>52.31</td><td>42.63</td><td>63.79</td><td>—</td></tr> <tr><td style="text-align: left; white-space: nowrap;">embeddinggemma-300m</td><td>308M</td><td>53.69</td><td>58.72</td><td>64.58</td><td>49.11</td><td>40.89</td><td>68.81</td><td>—</td></tr> <tr><td style="text-align: left; white-space: nowrap;">gte-multilingual-base</td><td>305M</td><td>51.08</td><td>57.39</td><td>64.14</td><td><strong>66.41</strong></td><td><strong>56.65</strong></td><td>57.46</td><td>—</td></tr> <tr><td style="text-align: left; white-space: nowrap;">voyage-4-nano</td><td>346M</td><td>49.96</td><td>49.29</td><td>58.65</td><td>62.10</td><td>51.97</td><td><strong>76.43</strong></td><td>—</td></tr> <tr><td style="text-align: left; white-space: nowrap;">BGE-M3</td><td>568M</td><td>48.78</td><td>62.22</td><td><strong>69.62</strong></td><td>61.16</td><td>52.47</td><td>51.49</td><td>—</td></tr> <tr><td style="text-align: left; white-space: nowrap;">granite-311m-r2</td><td>312M</td><td>49.24</td><td>53.38</td><td>59.74</td><td>50.53</td><td>41.86</td><td>63.50</td><td>—</td></tr> </tbody> <tbody style="border-top: 1px solid rgba(128, 128, 128, 0.25); border-bottom: 1px solid rgba(128, 128, 128, 0.35);"> <tr> <th colspan="9" scope="rowgroup" style="padding: 16px 6px 6px; text-align: left; font-size: 0.8em; letter-spacing: 0.08em; text-transform: uppercase;">Late interaction</th> </tr> <tr> <td style="text-align: left; white-space: nowrap;"><strong style="color: #3b82f6;">mLateOn</strong></td> <td style="color: #3b82f6;">312M</td> <td><strong style="color: #3b82f6;">57.56</strong></td> <td><strong style="color: #3b82f6;">65.61</strong></td> <td style="color: #3b82f6;">67.04</td> <td><strong style="color: #3b82f6;">87.69</strong></td> <td><strong style="color: #3b82f6;">77.92</strong></td> <td><strong style="color: #3b82f6;">73.48</strong></td> <td style="color: #3b82f6;">—</td> </tr> <tr><td style="text-align: left; white-space: nowrap;">pplx-embed-v1-late-0.6b</td><td>596M</td><td>56.11</td><td>63.67</td><td><strong>69.55</strong></td><td>68.69</td><td>55.51</td><td>63.29</td><td>—</td></tr> <tr><td style="text-align: left; white-space: nowrap;">LFM2.5-ColBERT-350M</td><td>353M</td><td>54.50</td><td>57.40</td><td>42.45</td><td>78.39</td><td>61.05</td><td>51.62</td><td>—</td></tr> <tr><td style="text-align: left; white-space: nowrap;">jina-colbert-v2</td><td>559M</td><td>52.96</td><td>62.19</td><td>65.65</td><td>13.97</td><td>11.54</td><td>49.88</td><td>—</td></tr> <tr><td style="text-align: left; white-space: nowrap;">GTE-ModernColBERT</td><td>149M</td><td>54.23</td><td>43.96</td><td>36.35</td><td>67.68</td><td>45.95</td><td>54.37</td><td>—</td></tr> <tr><td style="text-align: left; white-space: nowrap;">ColBERT-Zero</td><td>149M</td><td>55.82</td><td>43.89</td><td>39.36</td><td>71.32</td><td>49.50</td><td>53.59</td><td>—</td></tr> </tbody> </table> </div>
<p style="max-width: 750px; margin: 14px auto 0; font-size: 0.85em; line-height: 1.5; text-align: center;"> <em>Retrieval results on BEIR-15, MIRACL, MLDR, and MTEB Code (↑ higher is better), with retrieval FLOPS (↓ lower is better). <span style="color: #3b82f6;">Blue</span> denotes our models; <strong>bold</strong> values mark the best result within each family for each metric. OpenSearch multilingual corresponds to opensearch-neural-sparse-encoding-multilingual-v1.</em> </p></div>
**Retrieval FLOPS** estimates the expected number of shared active features per query–document pair. It is a search-cost proxy, not measured latency or encoder FLOPs. Measurements use the fixed sample of **6,000 documents and 1,271 queries** from SciFact, NFCorpus, and FiQA.
### Key Findings
**Multilingual and long-document retrieval.** mSlideOn improves over mDenseOn on full MIRACL and MLDR by **4.76** and **10.19 points**, respectively, while remaining behind mLateOn. The per-language results show gains beyond the languages included in retrieval training.
**Code retrieval.** mSlideOn outperforms every sparse and late-interaction baseline in this comparison on MTEB Code.
**English retrieval.** mSlideOn reaches 56.00 on BEIR-15, compared with 56.70 for mDenseOn and 57.56 for mLateOn. The gains on multilingual, long-document, and code tasks therefore come with a modest reduction in English benchmark performance.
<div style="margin: 0 auto; text-align: center;"> <img src="https://cdn-uploads.huggingface.co/production/uploads/67e184d667350657a7d68aac/fGrj4Ki_9AM0f7FjMJqyl.png" alt="Per-dataset and per-language performance differences between mSlideOn and mDenseOn on BEIR-15, MIRACL, MLDR, and MTEB Code." style="display: block; max-width: 100%; height: auto; margin: 0 auto;" /> <p style="max-width: 750px; margin: 12px auto 0; font-size: 0.85em; line-height: 1.5;"> <em>Per-dataset and per-language differences in nDCG@10 points for mSlideOn versus mDenseOn. <span style="color: #46a59b;">Teal</span> bars indicate gains and <span style="color: #ff4b57;">red</span> bars indicate declines relative to mDenseOn. <span style="color: #3b82f6;">Blue labels</span> mark languages included in retrieval training.</em> </p></div>
## Related Checkpoints
| Model | Description || --- | --- || **[mSlideOn](https://huggingface.co/lightonai/mSlideOn)** *(this model)* | Multilingual sparse retrieval model for natural language, long documents, and code || [mSlideOn-SAE](https://huggingface.co/lightonai/mSlideOn-SAE) | mLateOn-based SAE initialization before retrieval fine-tuning || [SlideOn](https://huggingface.co/lightonai/SlideOn) | English sparse retrieval model, after SAE pretraining and retrieval fine-tuning || [SlideOn-SAE](https://huggingface.co/lightonai/SlideOn-SAE) | DenseOn-based SAE initialization before retrieval fine-tuning || [mLateOn](https://huggingface.co/lightonai/mLateOn) | Multilingual late-interaction retriever used to initialize mSlideOn's backbone |
The SAE checkpoints are starting points for training. Use SlideOn or mSlideOn for the retrieval results reported in the blog.
## Training Data and Recipe
See our blog post for [training data](https://huggingface.co/blog/lightonai/slideon-mslideon#training-data), [SAE pretraining](https://huggingface.co/blog/lightonai/slideon-mslideon#sparse-autoencoder-pretraining), and [supervised retrieval fine-tuning](https://huggingface.co/blog/lightonai/slideon-mslideon#supervised-fine-tuning-for-sparse-retrieval).
## Model Details
### Model Description
| Property | Value || --- | --- || Model type | Learned sparse retriever; Sentence Transformers `SparseEncoder` || Backbone | mLateOn / mmBERT-base || Total parameters | 339M || Maximum sequence length | 8,192 tokens, including special tokens and markers || Output dimensionality | 32,768 learned latent features || Token representation | 128 dimensions, L2-normalized before sparse encoding || Sparse encoder | Lift to 768 dimensions, residual MLP, and latent projection || Token sparsity | Top-32 latent selection followed by ReLU || Sequence pooling | Maximum over token activations || Similarity function | Dot product || Prompts | `[Q]` marker for queries; `[D]` marker for documents, inserted automatically after the beginning-of-sequence token. No `query:` / `document:` text prefixes. || Retrieval training languages | English, French, German, Italian, Spanish, Portuguese, Swedish, Norwegian, Arabic, plus code |
## Usage
### Direct Usage (Sentence Transformers)
Install the supported library versions:
```bashpip install -U "sentence-transformers>=6.1,<6.2" "transformers>=5.3,<6"```
Load the model and encode multilingual queries and documents:
```pythonfrom sentence_transformers import SparseEncoder
model = SparseEncoder("lightonai/mSlideOn", trust_remote_code=True)
queries = [ "Qu'est-ce qui provoque une éclipse solaire ?", "Was verursacht eine Sonnenfinsternis?",]documents = [ "A solar eclipse occurs when the Moon passes between the Sun and Earth.", "Um eclipse solar ocorre quando a Lua passa entre o Sol e a Terra.", "Wind turbines convert the kinetic energy of wind into electricity.",]
query_embeddings = model.encode_query(queries)document_embeddings = model.encode_document(documents)
print(query_embeddings.shape, document_embeddings.shape)# torch.Size([2, 32768]) torch.Size([3, 32768])
scores = model.similarity(query_embeddings, document_embeddings)print(scores)```
`encode_query()` inserts the `[Q]` query marker, and `encode_document()` inserts the `[D]` document marker, immediately after the beginning-of-sequence token. Pass raw text; the model adds these special tokens automatically and does not use `query:` or `document:` text prefixes. The returned embeddings are PyTorch sparse COO tensors. The model and custom inference code are included in this repository; loading does not require the training package or PyLate.
### Choosing Query and Document Budgets
Use `top_k` independently on each encoding call to cap the number of nonzero features **after pooling**. This is separate from the per-token top-32 operation and does not change the vector dimensionality. For example, to use **q-128 / d-1024**:
```pythonquery_embeddings = model.encode_query(queries, top_k=128)document_embeddings = model.encode_document(documents, top_k=1024)```
Omitting `top_k`, or setting it to `0`, uses unpruned vectors, matching the headline results.
Dimensions represent **learned latents**, so they do not map directly to tokenizer vocabulary entries. Inspect the sparse indices and weights; `SparseEncoder.decode()` cannot label them as vocabulary tokens. Retrieval uses raw dot products, so leave final vector normalization disabled.
## Citation
If you find this work useful for your research, please consider citing us:
```bibtex@misc{moura2026slideon, author = {Moura Junior, Paulo Roberto and Sourty, Raphaël}, title = {{SlideOn} \& {mSlideOn}: Sparsified late-interaction and dense retrievers}, year = {2026}, howpublished = {Hugging Face Blog}, url = {https://huggingface.co/blog/lightonai/slideon-mslideon}}```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143{ "architectures": [ "SlideOnModel" ], "auto_map": { "AutoConfig": "modeling_slideon.SlideOnConfig", "AutoModel": "modeling_slideon.SlideOnModel" }, "backbone_config": { "architectures": [ "ModernBertModel" ], "attention_bias": false, "attention_dropout": 0.0, "bos_token_id": 2, "classifier_activation": "gelu", "classifier_bias": false, "classifier_dropout": 0.0, "classifier_pooling": "mean", "cls_token_id": 1, "decoder_bias": true, "deterministic_flash_attn": false, "dtype": "float32", "embedding_dropout": 0.0, "eos_token_id": 1, "global_attn_every_n_layers": 3, "gradient_checkpointing": false, "hidden_activation": "gelu", "hidden_size": 768, "initializer_cutoff_factor": 2.0, "initializer_range": 0.02, "intermediate_size": 1152, "layer_norm_eps": 1e-05, "layer_types": [ "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention" ], "local_attention": 128, "mask_token_id": 4, "max_position_embeddings": 8192, "mlp_bias": false, "mlp_dropout": 0.0, "model_type": "modernbert", "norm_bias": false, "norm_eps": 1e-05, "num_attention_heads": 12, "num_hidden_layers": 22, "pad_token_id": 0, "position_embedding_type": "sans_pos", "repad_logits_with_grad": false, "rope_parameters": { "full_attention": { "rope_theta": 160000, "rope_type": "default" }, "sliding_attention": { "rope_theta": 160000, "rope_type": "default" } }, "sep_token_id": 1, "sparse_pred_ignore_index": -100, "sparse_prediction": false, "tie_word_embeddings": true, "vocab_size": 256002 }, "base_model": "lightonai/mLateOn", "base_model_revision": "edd378f99593c0ac8a15518b97ad89786b02685e", "checkpoint_type": "retrieval", "head_config": { "d_lift": 768, "d_model": 128, "has_decoder": false, "hidden_dim": 1536, "n_latents": 32768 }, "inference": { "document_length": 8192, "document_top_k": 0, "head_chunk_size": 2048, "pooling": "max_relu", "prompts": { "document": "", "query": "" }, "query_length": 8192, "query_top_k": 0, "score": "dot", "token_k": 32 }, "model_type": "slideon", "projection_configs": [ { "activation_function": "torch.nn.modules.linear.Identity", "bias": false, "in_features": 768, "out_features": 1536, "use_residual": true }, { "activation_function": "torch.nn.modules.linear.Identity", "bias": false, "in_features": 1536, "out_features": 768, "use_residual": true }, { "activation_function": "torch.nn.modules.linear.Identity", "bias": false, "in_features": 768, "out_features": 128, "use_residual": false } ], "sae_path": "lightonai/mSlideOn-SAE", "skip_token_ids": [], "tokenizer_settings": { "document_prefix": "[D] ", "query_prefix": "[Q] ", "skiplist_words": [] }, "transformers_version": "5.3.0"}123456789101112{ "model_type": "SparseEncoder", "__version__": { "sentence_transformers": "6.1.0" }, "prompts": { "query": "", "document": "" }, "default_prompt_name": "document", "similarity_fn_name": "dot"}123version https://git-lfs.github.com/spec/v1oid sha256:211a4752e2cf8aaed832ccd52f972f7718377b39730eedaa697bd32184332707size 1357813608123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216"""Complete SlideOn model: Transformer, token projections, and sparse latent head."""from __future__ import annotations
import torchfrom torch.utils.checkpoint import checkpoint as activation_checkpointfrom transformers import AutoConfig, AutoModel, PretrainedConfig, PreTrainedModel
class SlideOnConfig(PretrainedConfig): model_type = "slideon" sub_configs = {"backbone_config": AutoConfig}
def __init__(self, backbone_config=None, projection_configs=None, head_config=None, inference=None, tokenizer_settings=None, skip_token_ids=None, checkpoint_type="retrieval", **kwargs): super().__init__(**kwargs) if isinstance(backbone_config, dict): backbone_config = dict(backbone_config) model_type = backbone_config.pop("model_type", "modernbert") backbone_config = AutoConfig.for_model(model_type, **backbone_config) self.backbone_config = backbone_config or AutoConfig.for_model("modernbert") self.projection_configs = projection_configs or [] self.head_config = head_config or dict(d_model=768, n_latents=32768, d_lift=0) self.inference = inference or dict( token_k=32, query_top_k=0, document_top_k=0, query_length=8192, document_length=8192, head_chunk_size=2048, prompts={"query": "", "document": ""}, pooling="max_relu", score="dot") self.tokenizer_settings = tokenizer_settings or {} self.skip_token_ids = skip_token_ids or [] self.checkpoint_type = checkpoint_type if self.inference.get("pooling") != "max_relu" or self.inference.get("score") != "dot": raise ValueError("SlideOn supports max_relu pooling and dot scoring")
class TokenProjection(torch.nn.Module): """The token-wise residual Dense layers used by mSlideOn."""
def __init__(self, config): super().__init__() self.config = config self.linear = torch.nn.Linear( config["in_features"], config["out_features"], bias=config["bias"] ) self.use_residual = config.get("use_residual", False) self.residual = None if self.use_residual and config["in_features"] != config["out_features"]: self.residual = torch.nn.Linear( config["in_features"], config["out_features"], bias=False ) if config["activation_function"] != "torch.nn.modules.linear.Identity": raise ValueError("Unsupported projection activation")
def forward(self, tokens): projected = self.linear(tokens) if self.use_residual: projected = projected + ( self.residual(tokens) if self.residual is not None else tokens ) return projected
class LatentHead(torch.nn.Module): def __init__(self, config): super().__init__() d_model, n_latents = config["d_model"], config["n_latents"] d_lift = config.get("d_lift") or 0 self.W_enc = torch.nn.Parameter(torch.empty(d_lift or d_model, n_latents)) self.b_enc = torch.nn.Parameter(torch.zeros(n_latents)) self.b_dec = torch.nn.Parameter(torch.zeros(d_model)) self.gate_relu_phi = torch.nn.Parameter(torch.ones(n_latents)) self.lift = None if d_lift: hidden = config["hidden_dim"] self.lift = torch.nn.Linear(d_model, d_lift, bias=False) self.mlp = torch.nn.Sequential( torch.nn.Linear(d_lift, hidden), torch.nn.ReLU(), torch.nn.Linear(hidden, d_lift)) if config.get("has_decoder", False): # Preserve the pretrained SAE decoder without optimizing it in retrieval SFT. self.W_dec = torch.nn.Parameter(torch.empty(n_latents, d_model), requires_grad=False) self.register_buffer("steps_since_fired", torch.zeros(n_latents, dtype=torch.long))
def forward(self, tokens): centered = tokens - self.b_dec if self.lift is not None: lifted = self.lift(centered) centered = lifted + self.mlp(lifted) return centered @ self.W_enc + self.b_enc
class SlideOnModel(PreTrainedModel): config_class = SlideOnConfig base_model_prefix = "backbone" _supports_sdpa = True _supports_flash_attn = True _no_split_modules = ["ModernBertEncoderLayer", "LatentHead", "TokenProjection"] _keep_in_fp32_modules_strict = ["head"]
def __init__(self, config): super().__init__(config) config.backbone_config._attn_implementation = config._attn_implementation self.backbone = AutoModel.from_config(config.backbone_config) self.projections = torch.nn.ModuleList( TokenProjection(item) for item in config.projection_configs) self.head = LatentHead(config.head_config) self.settings = config.inference self.post_init()
def _init_weights(self, module): if isinstance(module, LatentHead): torch.nn.init.normal_(module.W_enc, std=0.02) if hasattr(module, "W_dec"): torch.nn.init.normal_(module.W_dec, std=0.02) else: super()._init_weights(module)
@classmethod def from_pretrained(cls, *args, **kwargs): result = super().from_pretrained(*args, **kwargs) model = result[0] if isinstance(result, tuple) else result # Match the original PyLate encoder's RoPE buffer precision. model.backbone.to(dtype=model.backbone.dtype) return result
def get_embedding_dimension(self): return self.config.head_config["n_latents"]
@staticmethod def _task(task): task = task or "document" if task not in ("query", "document"): raise ValueError("task must be 'query' or 'document'") return task
def forward(self, input_ids, attention_mask, token_type_ids=None, task=None, slideon_task=None, top_k=None, token_k=None, **kwargs): features = {"input_ids": input_ids, "attention_mask": attention_mask} if slideon_task is not None or task is not None: features["slideon_task"] = slideon_task or task if token_type_ids is not None: features["token_type_ids"] = token_type_ids task = self._task(task or features.get("slideon_task")) if features.get("slideon_task", task) != task: raise ValueError("Preprocessing and forward tasks must match") n_latents = self.get_embedding_dimension() cap = self.settings[task + "_top_k"] if top_k is None else top_k k = self.settings["token_k"] if token_k is None else token_k if not isinstance(cap, int) or not 0 <= cap <= n_latents: raise ValueError(f"top_k must be an integer between 0 and {n_latents}") if not isinstance(k, int) or not 1 <= k <= n_latents: raise ValueError(f"token_k must be an integer between 1 and {n_latents}") model_inputs = { key: features[key] for key in ("input_ids", "attention_mask", "token_type_ids") if key in features } tokens = self.backbone(**model_inputs).last_hidden_state for projection in self.projections: tokens = projection(tokens) mask = features["attention_mask"].bool() if task == "document" and self.config.skip_token_ids: skip_ids = torch.tensor(self.config.skip_token_ids, device=input_ids.device) mask = mask & ~torch.isin(input_ids, skip_ids) owners = torch.arange(tokens.shape[0], device=tokens.device)[:, None].expand_as( mask )[mask] tokens = torch.nn.functional.normalize(tokens[mask], p=2, dim=-1) # Match the evaluation loader's FP16 token transfer before head pooling. if not self.training: tokens = tokens.half().float() probability_sum = tokens.new_zeros(n_latents, dtype=torch.float32) usage_sum = tokens.new_zeros(n_latents, dtype=torch.float32) pooled = torch.zeros( mask.shape[0] * n_latents, dtype=torch.float32, device=tokens.device ) for start in range(0, tokens.shape[0], self.settings["head_chunk_size"]): end = start + self.settings["head_chunk_size"] # The reference evaluates the head under BF16 autocast on CUDA. def head_chunk(chunk): with torch.autocast(chunk.device.type, dtype=torch.bfloat16, enabled=chunk.is_cuda): activations = self.head(chunk) values, indices = activations.topk(k, dim=-1) probabilities = activations.float().softmax(-1).sum(0) if self.training else chunk.new_zeros(n_latents) return values, indices, probabilities if self.training and torch.is_grad_enabled(): values, indices, probabilities = activation_checkpoint(head_chunk, tokens[start:end], use_reentrant=False) else: values, indices, probabilities = head_chunk(tokens[start:end]) if self.training: probability_sum = probability_sum + probabilities usage_sum = usage_sum + torch.bincount(indices.flatten(), minlength=n_latents) values = values.float().relu() indices = owners[start:end, None] * n_latents + indices pooled = pooled.scatter_reduce( 0, indices.flatten(), values.flatten(), reduce="amax", include_self=True ) pooled = ( pooled.view(mask.shape[0], n_latents) * self.head.gate_relu_phi.float().relu() ) if cap: values, indices = pooled.topk(cap, dim=-1) pooled = torch.zeros_like(pooled).scatter(1, indices, values) # The reference stores retrieval weights in FP16; retain that rounding. features["sentence_embedding"] = pooled if self.training else pooled.half().float() if self.training: count = max(tokens.shape[0], 1) features["load_balance"] = n_latents * ( probability_sum / count * usage_sum.detach() / (count * k) ).sum() return {key: features[key] for key in ("sentence_embedding", "load_balance") if key in features}
SlideOnConfig.register_for_auto_class()SlideOnModel.register_for_auto_class("AutoModel")12345678[ { "idx": 0, "name": "0", "path": "", "type": "slideon.SlideOn" }]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Sentence Transformers adapter for the complete, flat SlideOn checkpoint."""from pathlib import Path
import torchfrom sentence_transformers.base.modules import InputModulefrom transformers import AutoConfig, AutoModel, AutoTokenizer
class SlideOn(InputModule): config_file_name = "config.json" forward_kwargs = {"task", "top_k", "token_k"} save_in_root = True
def __init__(self, checkpoint, model_kwargs=None, processor_kwargs=None, config_kwargs=None, **hub_kwargs): super().__init__() config = AutoConfig.from_pretrained( checkpoint, trust_remote_code=True, **hub_kwargs, **(config_kwargs or {})) if config.model_type != "slideon": raise ValueError("Expected a flat SlideOn checkpoint; use slideon.export for legacy checkpoints") self.model = AutoModel.from_pretrained( checkpoint, config=config, trust_remote_code=True, **hub_kwargs, **(model_kwargs or {})) self.tokenizer = AutoTokenizer.from_pretrained( checkpoint, trust_remote_code=True, **hub_kwargs, **(processor_kwargs or {})) if self.tokenizer.mask_token_id is not None: self.tokenizer.pad_token_id = self.tokenizer.mask_token_id elif self.tokenizer.eos_token_id is not None: self.tokenizer.pad_token_id = self.tokenizer.eos_token_id self.settings = self.model.config.inference self.encoder_config = self.model.config.tokenizer_settings self.max_seq_length = max(self.settings["query_length"], self.settings["document_length"])
def get_embedding_dimension(self): return self.model.get_embedding_dimension()
@staticmethod def _task(task): task = task or "document" if task not in ("query", "document"): raise ValueError("task must be 'query' or 'document'") return task
def preprocess( self, inputs, prompt=None, task=None, processing_kwargs=None, **kwargs ): task = self._task(task) if not all(isinstance(text, str) for text in inputs): raise TypeError("SlideOn accepts text strings only") if prompt is None: prompt = self.settings["prompts"][task] texts = [(prompt + text).strip() for text in inputs] prefix = self.encoder_config.get(task + "_prefix", "") length = min(self.max_seq_length, self.settings[task + "_length"]) options = dict( padding=True, truncation=True, max_length=length - bool(prefix), return_tensors="pt", ) options.update(processing_kwargs or {}) features = dict(self.tokenizer(texts, **options)) if prefix: prefix_id = self.tokenizer.convert_tokens_to_ids(prefix) for name, value in list(features.items()): fill = ( prefix_id if name == "input_ids" else (1 if name == "attention_mask" else 0) ) marker = torch.full( (value.shape[0], 1), fill, dtype=value.dtype, device=value.device ) features[name] = torch.cat((value[:, :1], marker, value[:, 1:]), dim=1) features["slideon_task"] = task return features
def forward(self, features, task=None, top_k=None, token_k=None, **kwargs): inputs = {key: features[key] for key in ("input_ids", "attention_mask", "token_type_ids", "slideon_task") if key in features} features.update(self.model(**inputs, task=task, top_k=top_k, token_k=token_k)) return features
def save(self, output_path, safe_serialization=True, **kwargs): self.model.save_pretrained(output_path, safe_serialization=safe_serialization) self.tokenizer.save_pretrained(output_path)
@classmethod def load(cls, model_name_or_path, subfolder="", token=None, cache_folder=None, revision=None, local_files_only=False, model_kwargs=None, processor_kwargs=None, config_kwargs=None, backend="torch", **kwargs): if backend != "torch": raise ValueError("SlideOn currently supports the torch backend only") return cls(model_name_or_path, model_kwargs, processor_kwargs, config_kwargs, subfolder=subfolder, token=token, cache_dir=cache_folder, revision=revision, local_files_only=local_files_only)123version https://git-lfs.github.com/spec/v1oid sha256:33b6ce1724e107a3298219a322b4c963fcfcb9c8661bd1f30189bdd0d36c4669size 343638051234567891011121314151617181920212223242526{ "backend": "tokenizers", "bos_token": "<bos>", "clean_up_tokenization_spaces": false, "cls_token": "<bos>", "eos_token": "<eos>", "is_local": true, "mask_token": "<mask>", "max_length": 299, "model_input_names": [ "input_ids", "attention_mask" ], "model_max_length": 8191, "pad_to_multiple_of": null, "pad_token": "<mask>", "pad_token_type_id": 0, "padding_side": "right", "sep_token": "<eos>", "spaces_between_special_tokens": false, "stride": 0, "tokenizer_class": "TokenizersBackend", "truncation_side": "right", "truncation_strategy": "longest_first", "unk_token": "<unk>"}.gitattributesAdded+36
README.mdAdded+307
config.jsonAdded+143
config_sentence_transformers.jsonAdded+12
model.safetensorsAdded+3
modeling_slideon.pyAdded+216
modules.jsonAdded+8
slideon.pyAdded+96
tokenizer.jsonAdded+3
tokenizer_config.jsonAdded+26