A Sentence Transformers semantic-search prototype re-encodes the whole corpus on every query; how do you restructure it around util.semantic_search?
answer
- encode once, search many
- corpus vectors never depend on the query
- encode_document offline, encode_query per request
- hits carry corpus_id and score
- cache keyed by model, prompt and flags
basics
~10 sEncode the corpus once with encode_document() and cache the result; per request encode only the query with encode_query(), call util.semantic_search(query_emb, corpus_emb, top_k=k), and map each hit's corpus_id back to your texts.
solid answer
~40 sCorpus encoding is the expensive step and does not depend on the query, so it moves to start-up or an offline job: `corpus_emb = model.encode_document(corpus)`, saved with `np.save` so restarts skip it. Each request then pays for one short `model.encode_query(q)` plus a matrix product. `util.semantic_search(query_emb, corpus_emb, top_k=5)` returns one list per query of `{"corpus_id": ..., "score": ...}` dicts sorted by descending score; `corpus_id` is the row index, so the text list must stay in the same order as the embedding rows. It scores with `util.cos_sim` unless you pass `score_function`, searches exhaustively in chunks (`query_chunk_size=100`, `corpus_chunk_size=500000`), and the docs pitch it for corpora up to about a million entries. The cache is valid only for the same model, prompt and normalization settings that produced it.
code
python · 19 linesimport numpy as np
from sentence_transformers import SentenceTransformer, util
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
corpus = ["How to reset a password", "Billing cycles explained", "Exporting reports to CSV"]
# Offline, once per model + corpus version
np.save("corpus_emb.npy", model.encode_document(corpus, batch_size=64))
# At service start-up
corpus_emb = np.load("corpus_emb.npy")
# Per request: encode only the query
def search(q: str, k: int = 2):
query_emb = model.encode_query(q)
hits = util.semantic_search(query_emb, corpus_emb, top_k=k)[0]
return [(corpus[h["corpus_id"]], round(h["score"], 3)) for h in hits]
print(search("I forgot my login"))go deeper
Know the shape of the fix: corpus embedded once, query embedded per request, and semantic_search returning corpus_id and score dicts per query.
Explain semantic_search's defaults — top_k 10, cos_sim, chunk sizes — its exact search, and why corpus_id is a row index that must line up with your text list.
Show what invalidates a corpus cache: model, prompt, normalization, truncation or corpus order. Know where the matrix should live and when the corpus outgrows exhaustive search.
Weigh rebuild cost against freshness: who triggers re-embedding when the model or corpus changes, and how a versioned cache prevents mixing vectors from two recipes.
## Why the prototype is slow **Semantic search** with a bi-encoder has two halves: embed every corpus entry, then embed the query and find the corpus vectors that score highest against it. A prototype that calls `model.encode(corpus)` inside the request handler repeats the first half on every query. Every input goes through the transformer, so the cost grows with the corpus — 50,000 passages at the default `batch_size` of 32 means about 1,563 forward passes for each search — while the query itself is one short input. Nothing in `encode()` caches results between calls; the same text is re-encoded every time. The fix is structural: the corpus embeddings depend only on the corpus and the model, so compute them once and reuse them. ## The restructured flow 1. **Offline or at start-up**, encode the corpus with `model.encode_document(corpus, batch_size=...)`. For a checkpoint with query and document prompts this applies the document-side prompt; for one without, it is identical to `encode()`. 2. **Persist** the matrix next to the list of texts or ids it was built from, in the same order. 3. **At service start**, load the matrix once and keep it in memory — on the GPU if queries will be scored there. 4. **Per request**, encode only the query with `model.encode_query(q)`, which applies the query-side prompt when the model has one. 5. **Search** with `util.semantic_search(query_emb, corpus_emb, top_k=k)` and map each hit's `corpus_id` back to the stored text. ## What `util.semantic_search` takes and returns | Argument | Default | Meaning | |---|---|---| | `query_embeddings` | required | 2-D tensor (a 1-D vector or numpy array is accepted and converted) | | `corpus_embeddings` | required | 2-D tensor or numpy array of corpus vectors | | `top_k` | `10` | hits kept per query | | `score_function` | `util.cos_sim` | any function returning an all-pairs score matrix | | `query_chunk_size` | `100` | queries scored per step | | `corpus_chunk_size` | `500000` | corpus rows scored per step | The result is a list with **one entry per query**; each entry is a list of up to `top_k` dicts with keys `"corpus_id"` (an int, the row index into `corpus_embeddings`) and `"score"` (a Python float), sorted by decreasing score. The scores are plain floats, so they serialize to JSON directly. The search is **exact**: every corpus vector is scored, chunk by chunk, and a heap keeps the best `top_k`. If the query tensor sits on a different device from the corpus, it is moved to the corpus's device. The documentation positions it for corpora up to about a million entries; beyond that, or when you need persistence, filters and approximate search, the vectors belong in a vector index, which is a separate subject. ## Caching corpus embeddings A cache is only correct for the exact recipe that produced it. Invalidate it when any of these change: - the **model** or its revision; - the **prompt** applied to documents, including switching from `encode()` to `encode_document()`; - `normalize_embeddings` or `truncate_dim`; - the **corpus** itself — any insertion, deletion or reorder shifts row indices and breaks the `corpus_id` mapping. Practical choices: - `encode_document(...)` returns numpy by default, which `np.save` / `np.load` store compactly and which frees GPU memory as each batch finishes. - `convert_to_tensor=True` keeps the result on the model's device, convenient for an in-process search on a GPU; move a loaded matrix there with `.to(model.device)`. - Store the model id and the encoding flags beside the file so a mismatch is detectable rather than silent: vectors from two different models of the same dimension compare without error and produce meaningless scores. ## Keeping the search step fast The documentation's speed advice for `util.semantic_search` is short: - keep `query_embeddings` and `corpus_embeddings` on the **same GPU** — the function moves queries to the corpus's device, but a corpus left on the CPU is scored there; - normalize both sides once (`util.normalize_embeddings`) and pass `score_function=util.dot_score`, so the search does not re-normalize the corpus on every call; - batch several queries into one call when you can; they are scored together, up to `query_chunk_size` at a time. ## When to stop here `util.semantic_search` is the right tool for a prototype, an offline evaluation or a modest in-memory corpus. Reranking its hits with a cross-encoder, persisting vectors in a database and approximate indexes are next steps owned by other topics; the habit this question tests is that corpus encoding happens once, not per query.
- Why does util.semantic_search return a corpus_id instead of the matching text?It only sees the embedding tensors, so the only identity it has is the row index into `corpus_embeddings`. Keep the texts or document ids in a parallel list in the same order, and rebuild the cache whenever that order changes; filtering or deduplicating the corpus after encoding silently misaligns every id.
- When are query_chunk_size and corpus_chunk_size worth changing?They bound how much of the score matrix exists at once: by default 100 queries against 500,000 corpus rows per step, after which a heap keeps the best `top_k`. Raising them speeds up large batch searches at the cost of memory; lowering them keeps a big corpus searchable on a small GPU.
- Your cached corpus was built with encode(); queries now go through encode_query(). Is the cache still valid?Only if the model carries no prompts (and no `default_prompt_name`) and no `Router` module, in which case all three methods give identical vectors. For an asymmetric checkpoint the corpus was embedded without its document-side prompt, so rebuild it with `encode_document()` to match how the model was trained.
Re-encoding the corpus per query is like a librarian re-cataloguing every book each time a visitor asks a question. The catalogue is built once and kept; each visitor only fills in one request card, which is checked against it.
- encode() caches embeddings internally, so re-encoding the corpus is free
- util.semantic_search returns the matching corpus texts directly
- util.semantic_search performs approximate nearest-neighbour search
- Any two models with the same dimension can share one corpus cache
- corpus_id is a stable document id that survives reordering the corpus