skip to content

In Sentence Transformers, how does truncate_dim behave when set at load versus at encode, and what does it do to normalized vectors?

level: middleimportance: nice to knowfreq 6%

answer

  1. keeps the leading dimensions
  2. constructor default, per-call override
  3. truncate_embeddings context manager
  4. runs after the Normalize module
  5. normalize_embeddings runs after truncation

basics

~20 s

truncate_dim keeps the first N dimensions of each embedding: the constructor value is the default, an encode argument overrides it per call. Truncation happens after the model's Normalize module, so vectors stop being unit length unless normalize_embeddings=True.

solid answer

~30 s

`SentenceTransformer(name, truncate_dim=256)` sets a default; `encode(..., truncate_dim=128)` wins for that call; `with model.truncate_embeddings(64):` changes it temporarily; `get_embedding_dimension()` reports the truncated size. The cut is a slice of the leading dimensions applied after the whole module stack, including a `Normalize` module such as the one in `all-MiniLM-L6-v2`, so truncated vectors are no longer unit length. Cosine scores do not care, but dot-product scores do, so I pass `normalize_embeddings=True`, which runs after truncation. Truncation saves storage and search, not encoding time: the full forward pass still runs. Quality holds well mainly on checkpoints trained for it, the Matryoshka-style models.

go deeper

for a junior

Recall that truncate_dim keeps the first N dimensions and can be set when loading the model or on each encode call.

for a middle

Explain the precedence between constructor, encode argument and truncate_embeddings, and why truncation after Normalize breaks unit length.

for a senior

Catch a dot-product index silently degraded by unnormalized truncated vectors, and keep query and corpus dimensions pinned to one recorded value.

for a principal

Treat output dimension as an index-cost lever with the encoder cost unchanged, and require evidence the checkpoint was trained for truncation.

## What the flag does `truncate_dim` tells a `SentenceTransformer` to return only the **first N dimensions** of each sentence embedding. It is a plain slice of the output vector, not a projection or a learned reduction: a 768-dimension vector with `truncate_dim=256` becomes its first 256 numbers. Whether those 256 numbers are still a good embedding depends on how the checkpoint was trained. Models trained Matryoshka-style pack the most useful information into the leading dimensions, so a slice keeps most of their quality; ordinary checkpoints were not trained for it and can degrade sharply. How much a given cut costs is a question about embedding dimensionality, not about this flag. The flag itself just performs the cut you ask for; the library does not check whether the model was trained for it. ## Where you can set it, and which setting wins | Where | Scope | Example | |---|---|---| | Constructor | default for every call on this model | `SentenceTransformer(name, truncate_dim=256)` | | `encode` / `encode_query` / `encode_document` | this call only, overrides the default | `model.encode(texts, truncate_dim=128)` | | Context manager | calls inside the block | `with model.truncate_embeddings(64): ...` | The rule in the source is simple: the `encode` argument is used when given, otherwise the model's `truncate_dim`. `get_embedding_dimension()` returns the smaller of the model's output size and the model's `truncate_dim`, which is the number to size an index with. ```python from sentence_transformers import SentenceTransformer model = SentenceTransformer("mixedbread-ai/mxbai-embed-large-v1", truncate_dim=512) print(model.get_embedding_dimension()) # 512 emb = model.encode(["a passage"], normalize_embeddings=True) small = model.encode(["a passage"], truncate_dim=256, normalize_embeddings=True) print(emb.shape, small.shape) # (1, 512) (1, 256) ``` ## The ordering that matters: truncation after Normalize Inside `encode`, each batch goes through the full module stack first. For `sentence-transformers/all-MiniLM-L6-v2` that stack ends in a **`Normalize`** module, so the 384-dimension output has unit length. Only then is the slice applied. The order inside `encode` is: 1. run every module, including `Normalize` if the model has one; 2. apply `truncate_dim`; 3. apply `normalize_embeddings=True` if you asked for it; 4. apply `precision` quantization if you asked for it. Consequences: - A truncated vector from a normalizing model is **generally no longer unit length**. - With the default `similarity_fn_name` of `"cosine"`, scores are unaffected, because cosine divides by the lengths anyway. - With `"dot"`, or with a vector store configured for inner product on the assumption of unit vectors, scores and rankings shift. Passing `normalize_embeddings=True` fixes that, since it runs after the cut. - If you also quantize, the quantization ranges must be computed on the truncated vectors you actually store. ## What it saves and what it does not - **Saves:** bytes per vector, index memory, and distance-computation time, all in proportion to the cut. - **Does not save:** encoding time. The encoder still computes the full hidden size; the slice happens at the end. - **Does not change:** how many tokens are read. That is `max_seq_length`, a separate input-side setting. ## Diagnosing a truncation problem Typical symptoms and their usual causes: - **Rankings changed after enabling `truncate_dim`, but only for some queries.** The store scores by inner product on vectors that are no longer unit length; add `normalize_embeddings=True` or switch the store to cosine. - **Insert fails with a dimension error.** Part of the pipeline encodes with a per-call `truncate_dim` and part relies on the model default, or a reload changed the default. - **Quality collapsed at a modest cut.** The checkpoint was not trained for truncation; check its card before assuming the leading dimensions carry the signal. - **No latency improvement.** Expected: the encoder cost is unchanged, only search and storage got cheaper. ## Operational rules - Embed **queries and corpus with the same `truncate_dim`**; vectors of different lengths cannot be compared, and a mismatch typically surfaces as a shape error in the vector store. - Record the dimension alongside the index so a later model reload with a different default does not silently produce incompatible vectors. - The flag behaves the same on the PyTorch, ONNX and OpenVINO backends, since it is applied after the model runs.

  • A model loaded with truncate_dim=256 is passed to an indexing job that sizes its vector store from get_embedding_dimension(). What size does it get?
    256. `get_embedding_dimension()` returns the smaller of the model's output size and its `truncate_dim`, so the store is sized for the vectors `encode` will actually return. A per-call `truncate_dim` passed to `encode` is not reflected there, which is a reason to set the dimension on the model rather than per call in indexing code.
  • Does truncate_dim make encoding faster on CPU?
    Not meaningfully. The encoder and pooling still compute the full hidden size and the slice is taken at the end. The gains are in storage and search: fewer bytes per vector and cheaper distance computations. To cut encoding time, use a smaller checkpoint, a shorter `max_seq_length`, or the ONNX or OpenVINO backends.

  • Thinks truncate_dim reduces how many tokens the model reads
  • Expects truncate_dim to speed up the encoder's forward pass
  • Assumes truncated vectors from a normalizing model are still unit length
  • Believes truncate_dim at load overrides the value passed to encode
  • Truncates any checkpoint and assumes quality holds like a Matryoshka-trained one