How do you add MatryoshkaLoss to a Sentence Transformers fine-tune, and what must its matryoshka_dims list contain?
answer
- a modifier, not a loss
- wraps the base loss
- the same loss at each prefix
- include the full dimension
- n_dims_per_step and weights
basics
~20 sWrap the real loss: MatryoshkaLoss(model, base_loss, matryoshka_dims=[...]) applies the base loss to each leading slice of the embedding and sums the results. The list should include the model's full dimension, and no entry may exceed it.
solid answer
~40 s`MatryoshkaLoss` is a loss modifier, so I build the loss that fits my data first, say `MultipleNegativesRankingLoss(model)`, and wrap it: `MatryoshkaLoss(model, base_loss, matryoshka_dims=[384, 256, 128, 64])`. On every step it runs the base loss on the embedding truncated to each listed size (the first 384 values, the first 256, and so on) and adds them up, weighted by `matryoshka_weights`, which default to 1 each. Any dimension larger than `model.get_embedding_dimension()` raises an error, and leaving the full dimension out only logs a warning but means the full-size output is never trained. `n_dims_per_step` lets each step train a random subset of the sizes to save compute. Everything else, the dataset shape, `BatchSamplers.NO_DUPLICATES` for an in-batch negatives base loss, stays as it was.
code
python · 15 linesfrom sentence_transformers import SentenceTransformer
from sentence_transformers.sentence_transformer.losses import (
MatryoshkaLoss,
MultipleNegativesRankingLoss,
)
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
full_dim = model.get_embedding_dimension() # 384 for this checkpoint
base_loss = MultipleNegativesRankingLoss(model)
loss = MatryoshkaLoss(
model,
base_loss,
matryoshka_dims=[full_dim, 256, 128, 64], # keep the full size in the list
)go deeper
Recall that MatryoshkaLoss wraps another loss and that matryoshka_dims lists the embedding sizes to train, starting with the full size.
Explain how each step truncates the embedding, applies the base loss per size and sums with weights, and what n_dims_per_step trades.
Wire per-dimension evaluators, keep the base loss's sampler settings, and catch a dims list that silently leaves the full-size output untrained.
Decide whether serving several vector sizes justifies the extra training objective, and which sizes the product will really use before baking them into the run.
## What MatryoshkaLoss is A **Matryoshka embedding model** is trained so that the first `k` values of its embedding are a usable embedding on their own, for several values of `k`. In Sentence Transformers this is done by `MatryoshkaLoss`, which the library files under **loss modifiers**: it does not define a new notion of similarity, it applies an existing loss at several embedding sizes. Whatever loss fits your data, `MultipleNegativesRankingLoss` for pairs or `CoSENTLoss` for scored pairs, is the one it wraps. ## The constructor `MatryoshkaLoss(model, loss, matryoshka_dims, matryoshka_weights=None, n_dims_per_step=-1)`: - **`model`**: the `SentenceTransformer` being trained. - **`loss`**: the base loss instance, already built with the same model. - **`matryoshka_dims`**: the embedding sizes to train, for example `[768, 512, 256, 128, 64]` for a 768-dimension model. The order you give does not matter; the loss sorts them in descending order. - **`matryoshka_weights`**: one weight per dimension; `None` means a weight of 1 for each. - **`n_dims_per_step`**: `-1` (default) trains every listed size on every step; a positive number samples that many sizes at random per step. ## How a training step works 1. The model embeds the batch once at full size. 2. For each selected dimension, the embeddings are **truncated to their first `d` values**; no projection layer is added and no new weights appear. 3. The base loss is computed on the truncated embeddings. 4. The per-dimension losses are multiplied by their weights and summed into one loss value. The forward pass is reused across dimensions, so the extra cost is mainly repeated loss computation, not repeated encoding. With the cached in-batch negatives losses, `MatryoshkaLoss` decorates the base loss's own computation so that the cached embeddings are truncated instead, which keeps the large-batch setup working. ## What the dims list must contain | Rule | What happens if broken | |---|---| | no entry larger than `model.get_embedding_dimension()` | `ValueError` at construction | | at least one entry, all positive | `ValueError` at construction | | the full dimension included | a warning: the full-size output is not trained and may degrade | | `matryoshka_weights` as long as `matryoshka_dims` | `ValueError` at construction | The third row is the quiet one. A list such as `[256, 128, 64]` on a 384-dimension model trains the model for small vectors while nobody checks the full vector you will probably also serve. ## Wiring it into a run - Build the dataset for the **base** loss; `MatryoshkaLoss` accepts any inputs and any labels the base loss accepts. - Keep the training arguments the base loss wants, such as `batch_sampler=BatchSamplers.NO_DUPLICATES` under `MultipleNegativesRankingLoss`. - Evaluate at several sizes: build one evaluator per dimension with its `truncate_dim` argument, and combine them with `SequentialEvaluator`, as the library's Matryoshka training examples do. - `Matryoshka2dLoss` combines `MatryoshkaLoss` with `AdaptiveLayerLoss`, which additionally trains the model to work with fewer layers. - At inference you choose the size with the model's `truncate_dim`; that belongs to loading and encoding, not to training. ## Choosing sizes and weights - Start from the sizes you might actually serve. For a 384-dimension model such as `sentence-transformers/all-MiniLM-L6-v2`, `[384, 256, 128, 64]` covers a full-size index and three cheaper ones. - Use `matryoshka_weights` when one size matters most: a weight list such as `[1, 1, 2, 2]` puts more of the gradient on the small sizes you intend to ship, at some cost to the large ones. - Keep the list short when training time is tight, or set `n_dims_per_step` so each step only pays for a sample of sizes. - Check `model.get_embedding_dimension()` before writing the list; it is the hard upper bound and the value the warning compares against. The saved result is an ordinary `SentenceTransformer` checkpoint. Nothing in it forces truncation: whoever loads it chooses a size, so record the trained sizes in the model card or README so users know which ones were optimised. ## What it does not buy you The library's own Matryoshka documentation is explicit: training and inference of a Matryoshka model are **not faster, not more memory-efficient and not smaller**. The model still produces the full vector; only storing and comparing the truncated vectors gets cheaper. How much retrieval quality a given truncation costs is a separate question about embedding dimensionality, to be measured on your own data.
- How do you see, during training, whether the 64-dimension slice is improving?Create one evaluator per size with `truncate_dim` set, for example an `InformationRetrievalEvaluator` at 64, 128 and the full size, and pass them as a list or a `SequentialEvaluator` to the trainer. Each logs its own metrics, so the small slice's curve is visible next to the full one.
- Does MatryoshkaLoss work with CachedMultipleNegativesRankingLoss?Yes. The docstring says it is compatible with the cached losses; it decorates their loss computation so the cached embeddings are truncated per dimension, keeping both the large batch and the multi-size objective.
- A Matryoshka-trained model trains and encodes faster than a regular one.
- MatryoshkaLoss is a standalone loss that replaces MultipleNegativesRankingLoss.
- Leaving the full dimension out of matryoshka_dims has no effect on quality.
- The smaller sizes come from a learned projection layer added to the model.
- MatryoshkaLoss cannot be combined with the cached in-batch negatives losses.