Feature Extraction
sentence-transformers
Safetensors
English
slideon
sparse
sentence-similarity
custom-code
sparse-retrieval
matryoshka
custom_code
🇪🇺 Region: EU
Run this model with HF Jobs
Run lightonai/SlideOn 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/SlideOn. 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/SlideOn 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/SlideOn with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- sentence-transformers
How to use lightonai/SlideOn with sentence-transformers:
from sentence_transformers import SentenceTransformer model = SentenceTransformer("lightonai/SlideOn", 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
Paulo de Moura commited on
Commit ·
450a2c8
1
Parent(s): dbee038
Use max_active_dims for pooled latent pruning
Browse filesFiles changed (4)
- README.md+8-6
- config.json+2-2
- modeling_slideon.py+10-7
- slideon.py+5-3
206 unmodified lines2072082092102112122132146 unmodified lines221222223224225226227228229230231232233234235236206 unmodified lines"Wind turbines convert the kinetic energy of wind into electricity.",]query_embeddings = model.encode_query(queries, top_k=64)document_embeddings = model.encode_document(documents, top_k=512)print(query_embeddings.shape, document_embeddings.shape)# torch.Size([1, 32768]) torch.Size([2, 32768])6 unmodified lines### Choosing Query and Document BudgetsUse `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.To reproduce the unpruned setting:```pythonquery_embeddings = model.encode_query(queries, top_k=0)document_embeddings = model.encode_document(documents, top_k=0)```Omitting `top_k` also uses the saved unpruned defaults. To use the **q-full / d-512** setting, keep the query call at `top_k=0` and set the document call to `top_k=512`.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.206 unmodified lines2072082092102112122132146 unmodified lines221222223224225226227228229230231232233234235236237238206 unmodified lines"Wind turbines convert the kinetic energy of wind into electricity.",]query_embeddings = model.encode_query(queries, max_active_dims=64)document_embeddings = model.encode_document(documents, max_active_dims=512)print(query_embeddings.shape, document_embeddings.shape)# torch.Size([1, 32768]) torch.Size([2, 32768])6 unmodified lines### Choosing Query and Document BudgetsSet `max_active_dims=N` to keep the **top-N latents with the highest weights** in each pooled vector and set the rest to zero. You can choose a different N for queries and documents. This is separate from the per-token top-32 operation and does not change the vector dimensionality.Use a positive integer for a cap, or `None` for the saved unpruned defaults; `0` is invalid.To reproduce the unpruned setting:```pythonquery_embeddings = model.encode_query(queries, max_active_dims=None)document_embeddings = model.encode_document(documents, max_active_dims=None)```Omitting `max_active_dims` also uses the saved unpruned defaults. To use the **q-full / d-512** setting, keep the query call at `max_active_dims=None` and set the document call to `max_active_dims=512`.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.
93 unmodified lines9495969798991001 unmodified line10210310410510610710893 unmodified lines},"inference": {"document_length": 8192,"document_top_k": 0,"head_chunk_size": 2048,"pooling": "max_relu","prompts": {1 unmodified line"query": "query: "},"query_length": 8192,"query_top_k": 0,"score": "dot","token_k": 32},93 unmodified lines9495969798991001 unmodified line10210310410510610710893 unmodified lines},"inference": {"document_length": 8192,"document_max_active_dims": null,"head_chunk_size": 2048,"pooling": "max_relu","prompts": {1 unmodified line"query": "query: "},"query_length": 8192,"query_max_active_dims": null,"score": "dot","token_k": 32},
21 unmodified lines22232425262728105 unmodified lines1341351361371381391403 unmodified lines14414514614714814915015115215345 unmodified lines19920020120220320420520621 unmodified linesself.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 {}105 unmodified linesdef 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 task3 unmodified linesif 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_kk = self.settings["token_k"] if token_k is None else token_kif 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 = {45 unmodified linespooled.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()21 unmodified lines22232425262728105 unmodified lines1341351361371381391401411423 unmodified lines14614714814915015115215315415545 unmodified lines20120220320420520620720820921 unmodified linesself.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_max_active_dims=None, document_max_active_dims=None,query_length=8192, document_length=8192, head_chunk_size=2048,prompts={"query": "", "document": ""}, pooling="max_relu", score="dot")self.tokenizer_settings = tokenizer_settings or {}105 unmodified linesdef forward(self, input_ids, attention_mask, token_type_ids=None, task=None,slideon_task=None, max_active_dims=None, token_k=None, **kwargs):if "top_k" in kwargs:raise TypeError("top_k has been removed; use max_active_dims (None for unpruned)")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 task3 unmodified linesif features.get("slideon_task", task) != task:raise ValueError("Preprocessing and forward tasks must match")n_latents = self.get_embedding_dimension()cap = self.settings.get(task + "_max_active_dims") if max_active_dims is None else max_active_dimsk = self.settings["token_k"] if token_k is None else token_kif cap is not None and (type(cap) is not int or cap <= 0):raise ValueError("max_active_dims must be a positive integer or None")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 = {45 unmodified linespooled.view(mask.shape[0], n_latents)* self.head.gate_relu_phi.float().relu())if cap is not None:# Prune before FP16 roundingvalues, indices = pooled.topk(min(cap, n_latents), 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()
7 unmodified lines89101112131460 unmodified lines757677787980818283847 unmodified linesclass SlideOn(InputModule):config_file_name = "config.json"forward_kwargs = {"task", "top_k", "token_k"}save_in_root = Truedef __init__(self, checkpoint, model_kwargs=None, processor_kwargs=None,60 unmodified linesfeatures["slideon_task"] = taskreturn featuresdef 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 featuresdef save(self, output_path, safe_serialization=True, **kwargs):7 unmodified lines89101112131460 unmodified lines7576777879808182838485867 unmodified linesclass SlideOn(InputModule):config_file_name = "config.json"forward_kwargs = {"task", "max_active_dims", "token_k"}save_in_root = Truedef __init__(self, checkpoint, model_kwargs=None, processor_kwargs=None,60 unmodified linesfeatures["slideon_task"] = taskreturn featuresdef forward(self, features, task=None, max_active_dims=None, token_k=None, **kwargs):if "top_k" in kwargs:raise TypeError("top_k has been removed; use max_active_dims (None for unpruned)")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, max_active_dims=max_active_dims, token_k=token_k))return featuresdef save(self, output_path, safe_serialization=True, **kwargs):
README.md+8-6
config.json+2-2
modeling_slideon.py+10-7
slideon.py+5-3