skip to content

In Sentence Transformers, a retrieval prototype on an asymmetric checkpoint calls encode() for both queries and passages; what goes wrong, and how do encode_query, encode_document and prompts fix it?

level: seniorimportance: should knowfreq 12%

answer

  1. the checkpoint ships its own prompts
  2. inspect model.prompts after loading
  3. prompt, then prompt_name, then the default
  4. each side picks its own prompt and task
  5. default_prompt_name hits every plain encode()

basics

~20 s

Plain encode() applies only a prompt or prompt_name you pass, or default_prompt_name, so an asymmetric checkpoint embeds queries without its trained prefix. encode_query() and encode_document() pick the model's query and document prompts, and set the routing task, when you pass none.

solid answer

~40 s

Checkpoints trained with prefixes save them in `config_sentence_transformers.json` as a `prompts` dict, loaded into `model.prompts`. `encode()` resolves a prompt in one order: an explicit `prompt=` string, else `prompt_name=` looked up in `model.prompts`, else `default_prompt_name`, else nothing — so a bare `encode()` on queries silently skips the query prefix and recall drops with no error. `encode_query()` fills `prompt_name="query"` when you pass neither argument, `encode_document()` picks the document-side prompt, and both set `task` so a model with a `Router` module sends input down the matching branch. For a model with no prompts or router, all three methods return identical vectors. Check `model.prompts` after loading, pass `prompt_name=` explicitly when the checkpoint names a prompt differently, and beware `default_prompt_name="query"`: every plain `encode()`, including the corpus job, then gets the query prefix.

code

python · 16 lines
python
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("your-org/your-asymmetric-embedder")
print(model.prompts)              # e.g. {'query': 'query: ', 'document': 'passage: '}
print(model.default_prompt_name)  # None unless the config sets one

passages = ["Reset two-factor auth from the account page.", "Invoices are issued monthly."]
docs = model.encode_document(passages)                  # document prompt applied
q = model.encode_query("lost my 2FA phone")             # query prompt applied
q_same_text = model.encode("lost my 2FA phone", prompt_name="query")  # same text embedded, no task set

# A model card asks for prefixes its config does not save: supply them at load
model = SentenceTransformer(
    "your-org/your-asymmetric-embedder",
    prompts={"query": "query: ", "document": "passage: "},
)

go deeper

for a junior

Remember that asymmetric checkpoints ship prompts and that encode_query and encode_document apply them for you, while plain encode does not unless told.

for a middle

Explain the resolution order — prompt, then prompt_name, then default_prompt_name — and where model.prompts comes from: the saved config, constructor arguments or assignment.

for a senior

Diagnose the silent quality drop: inspect model.prompts, check how the corpus cache was built, and spot a default_prompt_name leaking the query prefix into document encoding.

for a principal

Make prompt handling part of the embedding contract: the method used per side is recorded with each index, so a model swap or prompt change triggers re-embedding rather than drift.

## The silent failure An **asymmetric** embedding checkpoint is trained to embed short queries and longer passages differently, usually by prepending a text **prompt** (an instruction or a short prefix) to one or both sides. Why such models need prefixes is a modelling question with its own home; the practical point here is that the library, not your code, should apply them — and plain `encode()` usually does not. The symptom is quiet: no exception, no warning, embeddings of the right shape, and retrieval quality that is simply worse than the model card promises. Evaluation numbers drop; nothing in the logs explains why. ## Where prompts live - **Saved with the checkpoint.** `config_sentence_transformers.json` can hold a `prompts` dict (for example a `"query"` and a `"document"` entry) and a `default_prompt_name`. - **On the loaded model.** `model.prompts` and `model.default_prompt_name` show what was loaded; print them before trusting any results. - **Passed at load time.** `SentenceTransformer(name, prompts={...}, default_prompt_name=...)` adds or overrides prompts; values you pass win over saved ones. Passing `{"query": "", "document": ""}` disables saved prompts. - **Assigned later.** `model.prompts = {...}` and `model.default_prompt_name = "..."` are plain attributes. When a model card tells you to prefix queries but the checkpoint's config saves no prompts, pass them yourself at load time so `encode_query` and `encode_document` can find them. ## How `encode()` resolves the prompt For every call, the library picks at most one prompt string, in this order: 1. An explicit `prompt="..."` string. If you also pass `prompt_name`, it is ignored with a logged warning. 2. Otherwise `prompt_name="..."`, looked up in `model.prompts`; an unknown name raises `ValueError` listing the available keys. 3. Otherwise the model's `default_prompt_name`, if set. 4. Otherwise no prompt. The chosen string is prepended to each input text before tokenization. ## What `encode_query` and `encode_document` add | Method | Prompt when you pass none | Task it sets | |---|---|---| | `encode()` | `default_prompt_name`, if any | none | | `encode_query()` | the model's `"query"` prompt | `"query"` | | `encode_document()` | the model's document-side prompt (the docs list `"document"`, `"passage"`, `"corpus"`) | `"document"` | Everything else — `batch_size`, `normalize_embeddings`, `convert_to_tensor` and the rest — passes straight through to `encode()`. The **task** matters for models built with a `Router` module, which sends queries and documents through different sub-modules; for ordinary models it has no effect. The library's own guidance: use `encode_query` and `encode_document` for retrieval with a clear query/document split, and `encode` for everything else (clustering, symmetric similarity). ## Diagnosing a suspect pipeline - Print `model.prompts` and `model.default_prompt_name` right after loading. - Check which method embedded the **corpus**: a cache built with `encode()` on an asymmetric model lacks the document prompt and must be rebuilt. - If the checkpoint names its passage prompt with a key you did not expect, pass `prompt_name=` explicitly instead of relying on the method's choice. - Compare `encode(q)` with `encode_query(q)` on one input: identical vectors mean the model carries no query prompt or router, so the methods are interchangeable for it. ## Fixing an index built the wrong way When the diagnosis confirms that queries or passages were embedded without their prompts: 1. Load the model and print `model.prompts`; if the card asks for prefixes the config does not carry, pass them in `prompts=` at load time. 2. Re-embed the **corpus** with `encode_document()` — a cache built with plain `encode()` cannot be patched, because the prompt changes every vector. 3. Switch the query path to `encode_query()`. 4. Re-run the retrieval evaluation on both versions before swapping the index, so the gain is measured rather than assumed. The library's docs give the shapes this takes in practice: some checkpoints want a short `"query: "` / `"passage: "` pair on both sides, others a longer instruction on the query side only. ## Two traps - **`default_prompt_name` is global.** Setting it to `"query"` so that queries get their prefix also prefixes every plain `encode()` call — including the job that embeds the corpus. Prefer the explicit methods over a default. - **Prompt tokens and pooling.** By default the `Pooling` module averages over prompt tokens too. Some instruction-style checkpoints are configured with `include_prompt=False` so the instruction is excluded from the pooled vector (the library sets this itself for the INSTRUCTOR family); `model.set_pooling_include_prompt(False)` changes it after loading. Leave it as the checkpoint saved it unless its card says otherwise.

  • What happens if you pass both prompt and prompt_name to encode()?
    The explicit `prompt` string wins and `prompt_name` is ignored, with a logged warning asking for one or the other. Separately, a `prompt_name` that is not a key of `model.prompts` raises `ValueError` listing the keys that exist, which is a quick way to discover how a checkpoint names its prompts.
  • For which models do encode(), encode_query() and encode_document() return identical vectors?
    For a model saved without query or document prompts, without a `default_prompt_name`, and without a `Router` module — a typical symmetric general-purpose checkpoint. Then the methods add nothing; using `encode_query` and `encode_document` anyway costs nothing and keeps the code correct if you later swap in an asymmetric model.
  • Are prompt tokens included in the pooled embedding?
    By default yes: `Pooling` averages over every token the encoder saw, prompt included. Some instruction-style checkpoints use `include_prompt=False` so the instruction is excluded from the pooled vector, and `model.set_pooling_include_prompt(False)` sets it after loading. Changing it on a model trained the other way changes its vectors, so follow the checkpoint.

  • encode() automatically applies the query prompt to inputs that look like questions
  • A missing prompt raises an error, so you would notice it
  • prompt_name takes precedence over an explicit prompt string
  • Setting default_prompt_name to query only affects query encoding
  • encode_query always runs a separate query encoder with its own weights