skip to content

In Sentence Transformers v6, how do normalize_embeddings and similarity_fn_name work together, and how do you switch a model to dot-product scoring?

level: middleimportance: should knowfreq 15%

answer

  1. unit length is opt-in
  2. normalize_embeddings=False by default
  3. cosine re-normalizes on every call
  4. set the name, not the method
  5. semantic_search has its own score_function

basics

~10 s

encode(normalize_embeddings=True) L2-normalizes each vector; similarity_fn_name picks what model.similarity() computes. In v6 switch with model.similarity_fn_name = "dot" or the constructor argument — assigning a function to model.similarity now silently shadows the method.

solid answer

~40 s

`normalize_embeddings` defaults to `False`, so `encode` returns the raw pooled vectors unless the checkpoint itself ends in a `Normalize` module. `similarity_fn_name` — `"cosine"`, `"dot"`, `"euclidean"` or `"manhattan"` — picks the function behind `model.similarity()` and `similarity_pairwise()`; it falls back to `"cosine"`, which normalizes both sides again on every call. Once both query and corpus vectors are unit length, `"dot"` ranks the same way with less work, and the docs suggest it for models ending in `Normalize`. Set it with `SentenceTransformer(..., similarity_fn_name="dot")`, `model.similarity_fn_name = "dot"`, or the saved `config_sentence_transformers.json`. In v6 `similarity` is a regular method: assigning your own function to `model.similarity` no longer raises, it silently shadows the method. `util.semantic_search` never reads the model's setting — pass `score_function=util.dot_score` there.

code

python · 15 lines
python
from sentence_transformers import SentenceTransformer, util

model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2", similarity_fn_name="dot")

docs = model.encode_document(["First passage.", "Second passage."], normalize_embeddings=True)
query = model.encode_query("Which passage?", normalize_embeddings=True)

print(model.similarity_fn_name)           # dot
scores = model.similarity(query, docs)     # dot product on unit vectors

# semantic_search ignores the model setting: say it explicitly
hits = util.semantic_search(query, docs, top_k=2, score_function=util.dot_score)

# Wrong in v6: silently shadows the method instead of raising
# model.similarity = util.dot_score

go deeper

for a junior

Remember that encode does not normalize unless asked, and that similarity_fn_name names the function similarity applies, with cosine as the fallback.

for a middle

Explain the resolution order of similarity_fn_name, why a model ending in Normalize pairs with dot, and why the flag must match on corpus and query paths.

for a senior

Diagnose mismatched scores: a v6 shadowed similarity method, semantic_search falling back to cos_sim, or a corpus normalized while queries were not. Name the one-line fix for each.

for a principal

Treat normalization and similarity choice as part of the index contract shared by every producer and consumer of vectors, versioned with the model, not toggled per service.

## Two settings, two places Sentence Transformers splits "make the vectors comparable" from "compare them" across two settings that live in different places: | Setting | Where | Default | What it does | |---|---|---|---| | `normalize_embeddings` | argument of `encode`, `encode_query`, `encode_document` | `False` | L2-normalizes each returned vector to length 1 | | `similarity_fn_name` | model attribute, constructor argument, saved config | saved config value, else `"cosine"` on first use | chooses the function `similarity()` and `similarity_pairwise()` apply | | `Normalize` module | part of the checkpoint's module list | present only if the checkpoint saved it | normalizes inside the forward pass, for every call | Why unit length lets dot product stand in for cosine is a geometry question with its own home; this answer is about the flags that apply it. ## `normalize_embeddings` in `encode()` `normalize_embeddings=True` divides each pooled vector by its L2 norm before it is returned. In the implementation this happens **after** `truncate_dim` is applied, so truncated vectors also come back unit length. It is a per-call flag: nothing about it is stored on the model, so a corpus job and a query path must both pass it, or both rely on a checkpoint that ends in `Normalize`. Checkpoints differ here. Some published models end in a `Normalize` module, so their output is unit length whatever you pass; others do not. Printing the model (its module list) or checking the norms of a few outputs settles it. ## `similarity_fn_name`: where the value comes from The model resolves the function in this order: 1. The `similarity_fn_name=` you pass to the `SentenceTransformer` constructor. 2. The `"similarity_fn_name"` key in the checkpoint's `config_sentence_transformers.json`, if it holds a supported value. 3. Otherwise `"cosine"`, set lazily the first time `similarity` or `similarity_pairwise` runs. You can change it at any time with `model.similarity_fn_name = "dot"` or with the enum, `SimilarityFunction.DOT_PRODUCT`. Saving the model writes the current value back into its config. Valid names for a `SentenceTransformer` are `"cosine"`, `"dot"`, `"euclidean"` and `"manhattan"`; anything else raises `ValueError`. The library's own note: when a model ends in `Normalize`, `"dot"` is the sensible choice, because `"cosine"` normalizes both inputs again on every call — the same ranking at extra cost. ## What changed in Sentence Transformers v6 - **`similarity` is a method, not a property.** In v5 it was a property returning a function, so `model.similarity = my_fn` raised `AttributeError`. In v6 the same assignment **silently shadows** the method on that instance: your function runs, but `similarity_pairwise` and the saved config still describe the old `similarity_fn_name`. The supported way to change scoring is to set `similarity_fn_name`, which updates both methods together. - **Half-precision scoring is upcast.** `similarity`, `similarity_pairwise` and the `util.cos_sim` family return float32 scores for float16 or bfloat16 embeddings, because half precision ties too many nearby scores to rank with. - Calls such as `model.similarity(e1, e2)` work unchanged. ## `util.semantic_search` does not consult the model `util.semantic_search` receives tensors, not a model, so it cannot know `similarity_fn_name`. Its `score_function` argument defaults to `util.cos_sim`. To keep a search step consistent with the model: - pass `score_function=util.dot_score` when the vectors are unit length and the model uses `"dot"`; - or pass `score_function=model.similarity`, which applies whatever the model is configured with; - never assume that setting the model attribute changes `semantic_search` results. For vectors loaded from disk, `util.normalize_embeddings(tensor)` applies the same L2 step after the fact; the library's own semantic-search example normalizes both the corpus and the queries this way and then scores with `util.dot_score`, and the similarity docs note that `"dot"` is faster than `"cosine"` on vectors that are already normalized, because cosine re-normalizes both inputs on every call. Keep in mind that `"euclidean"` and `"manhattan"` return **negated** distances, so for every choice of `similarity_fn_name` a higher score still means a closer match, and code that sorts descending works unchanged. ## A working checklist The failures in this area are silent — every combination runs and returns plausible numbers — so the guard is discipline rather than an error message: - Decide once whether stored vectors are unit length, and apply the same `normalize_embeddings` value on the corpus and query paths. - Set `similarity_fn_name` by name; never assign to `model.similarity`. - Mirror that choice in every `score_function` you pass to `util.semantic_search`. - Save the model after changing `similarity_fn_name` if other services load it, so the config carries the choice.

  • Your util.semantic_search scores differ from model.similarity scores on the same vectors. Why?
    `util.semantic_search` takes tensors, not the model, and scores with its own `score_function`, which defaults to `util.cos_sim`. If the model's `similarity_fn_name` is `"dot"` and the vectors are not unit length, the two disagree. Pass `score_function=util.dot_score`, or `score_function=model.similarity`, to keep them aligned.
  • What did assigning model.similarity = my_fn do before v6, and what does it do now?
    In v5 `similarity` was a read-only property, so the assignment raised `AttributeError`. In v6 it is a regular method, so the assignment silently shadows it on that instance: your function runs, but `similarity_pairwise` and the saved `similarity_fn_name` still describe the old function. Set `model.similarity_fn_name` instead.
  • Does model.similarity() on float16 embeddings return float16 scores in v6?
    No. Since v6, `similarity`, `similarity_pairwise` and the `util.cos_sim` family upcast half-precision inputs and return float32 scores, because float16 or bfloat16 arithmetic rounds nearby scores into ties that break ranking.

  • normalize_embeddings is on by default, so every encode output is unit length
  • Assign model.similarity = util.dot_score to switch to dot product
  • util.semantic_search follows the model's similarity_fn_name
  • Setting similarity_fn_name to dot normalizes the vectors for you
  • normalize_embeddings is saved on the model once you pass it

Assumes Sentence Transformers v6 (6.1.0): similarity became a regular method and half-precision scores are upcast to float32 in v6.