How do you wire Sentence Transformers' InformationRetrievalEvaluator into SentenceTransformerTrainer so the kept checkpoint is the one with the best nDCG@10, not the lowest loss?
answer
- three dictionaries keyed by ID
- the evaluator argument
- name, score function, metric
- the eval_ prefix
- load_best_model_at_end with matching strategies
basics
~10 sBuild InformationRetrievalEvaluator from queries, corpus and relevant_docs dicts with a name, pass it as evaluator=, and set load_best_model_at_end=True with metric_for_best_model naming its key, such as eval_support-dev_cosine_ndcg@10.
solid answer
~40 sI build the evaluator from three dicts: `queries` (query ID to text), `corpus` (document ID to text) and `relevant_docs` (query ID to a set of document IDs), plus a `name` such as `support-dev`, and pass it to `SentenceTransformerTrainer(evaluator=...)`. It runs on the `eval_strategy` / `eval_steps` schedule and reports keys shaped `<name>_<score function>_<metric>@k`, so a cosine model logs `support-dev_cosine_ndcg@10`, which the trainer prefixes to `eval_support-dev_cosine_ndcg@10`. I then set `load_best_model_at_end=True`, `metric_for_best_model` to that key, and matching `eval_strategy` / `save_strategy`; since the name does not end in `loss`, Transformers treats higher as better. In Sentence Transformers v6 the evaluator embeds queries with `encode_query` and the corpus with `encode_document`, so a prompted model is scored the way it will be served.
code
python · 20 linesfrom sentence_transformers import SentenceTransformerTrainer, SentenceTransformerTrainingArguments
from sentence_transformers.sentence_transformer.evaluation import InformationRetrievalEvaluator
dev_evaluator = InformationRetrievalEvaluator(
queries={"q1": "How do I reset two-factor login?"},
corpus={"d1": "Reset it under Settings, Security.", "d2": "Invoices are under Billing."},
relevant_docs={"q1": {"d1"}},
name="support-dev",
)
args = SentenceTransformerTrainingArguments(
output_dir="models/support",
eval_strategy="steps", eval_steps=200,
save_strategy="steps", save_steps=200, save_total_limit=2,
load_best_model_at_end=True,
metric_for_best_model="eval_support-dev_cosine_ndcg@10",
)
trainer = SentenceTransformerTrainer(
model=model, args=args, train_dataset=train_dataset,
loss=loss, evaluator=dev_evaluator,
)go deeper
Recall the three inputs, queries, corpus and relevant_docs, and that the evaluator is passed to the trainer with the evaluator argument.
Explain how metric keys are composed, why the trainer adds eval_, and which training arguments must agree for load_best_model_at_end to work.
Catch silent query drops from mismatched IDs, include realistic distractors in the corpus, and add a general benchmark evaluator as a regression alarm.
Own the dev set as a product asset: decide who curates it, how it tracks real traffic, and how checkpoint selection and release decisions stay separate.
## Why an evaluator instead of the eval loss `SentenceTransformerTrainer` can compute a loss on an `eval_dataset`, but for an in-batch negatives loss that number depends on the batch composition and says little about retrieval. An **evaluator** is an object the trainer calls on a schedule to compute task metrics on the current model. You can pass an `eval_dataset`, an `evaluator`, both, or neither; evaluation runs on the `eval_strategy` and `eval_steps` training arguments. For a retrieval fine-tune the natural choice is `InformationRetrievalEvaluator`. ## Building InformationRetrievalEvaluator It needs three dictionaries and a name: - **`queries`**: query ID to query text. - **`corpus`**: document ID to document text; include distractor documents, not only the relevant ones, or the task is trivial. - **`relevant_docs`**: query ID to a **set** of relevant document IDs. - **`name`**: a label that prefixes every metric key, such as `support-dev`. Two behaviours to know. A query with no entry, or an empty set, in `relevant_docs` is **silently left out**, so a mismatched ID type (an integer in one dict, a string in another) can shrink the evaluation set without an error. And the corpus is encoded in chunks of `corpus_chunk_size`, 50,000 by default, which bounds memory on large corpora. By default it reports accuracy, precision and recall at 1, 3, 5 and 10, MRR@10, nDCG@10 and MAP@100, all configurable with `ndcg_at_k`, `mrr_at_k` and the related arguments. Unless you pass `score_functions`, it scores with the model's own similarity function, named by `similarity_fn_name` (cosine unless the model says otherwise). ## Getting the metric name right Metric keys are built as `<name>_<score function>_<metric>@<k>`, and the evaluator's `primary_metric` is nDCG at the largest `ndcg_at_k`. Inside the trainer every evaluator key gains the `eval_` prefix. So: | Piece | Example value | |---|---| | evaluator `name` | `support-dev` | | score function | `cosine` | | metric | `ndcg@10` | | key in the trainer's logs | `eval_support-dev_cosine_ndcg@10` | Transformers adds the `eval_` prefix to `metric_for_best_model` itself when it is missing, but the middle segments must match exactly; drop the score function and the lookup fails. ## Keeping the best checkpoint 1. Set `eval_strategy` and `save_strategy` to the same value (for example `"steps"`), with `save_steps` a multiple of `eval_steps`; Transformers rejects `load_best_model_at_end` otherwise, unless `save_strategy` is `"best"`. 2. Set `load_best_model_at_end=True` and `metric_for_best_model` to the evaluator key. 3. Leave `greater_is_better` unset: Transformers infers `True` because the name does not end in `loss`. 4. Keep `save_total_limit` low; with `load_best_model_at_end=True` the best checkpoint is always retained alongside the most recent ones. ## Running it outside the trainer An evaluator is a plain callable: `dev_evaluator(model)` returns the metrics dict for any model, so you can score the starting checkpoint before `trainer.train()` and the final one afterwards with exactly the same code. During training the trainer passes it `output_dir/eval` as the output path, and with `write_csv=True` (the default) each run appends a row of metrics to a CSV file there, which survives even when no experiment tracker is configured. For a model trained with `MatryoshkaLoss`, the evaluator's `truncate_dim` argument scores a truncated slice, so one evaluator per size shows how each size is learning. ## Prompts and asymmetric models In Sentence Transformers v6 the evaluator embeds queries with `encode_query` and corpus documents with `encode_document`. A model that ships `query` and `document` prompts is therefore evaluated with them applied, matching how it will be called in production. You can override with `query_prompt_name` / `query_prompt` and `corpus_prompt_name` / `corpus_prompt`. v6.0 brought `TripletEvaluator` in line with the same convention, so asymmetric models report different triplet accuracy than under v5. ## Guarding general retrieval too A domain fine-tune can improve your dev set while degrading general retrieval. `NanoBEIREvaluator` needs no data of your own: it downloads small versions of public retrieval benchmarks and reports per-dataset metrics plus aggregated ones such as `NanoBEIR_mean_cosine_ndcg@10`. Pass a list of evaluators (the trainer wraps it in a `SequentialEvaluator`) and every evaluator's metrics are logged, while `metric_for_best_model` still picks the one key that decides which checkpoint is kept. Deciding what counts as "better enough" to ship is an evaluation-methodology question; the wiring above only makes the number trustworthy and the checkpoint selection automatic.
- Your dev evaluator reports 40 queries, but you built it from 300. What happened?Queries without a non-empty entry in `relevant_docs` are dropped. Usually the IDs do not match: integer IDs in one dict and string IDs in another, or `relevant_docs` keyed by IDs that never appear in `queries`. Normalise every ID to one type and rebuild.
- How do you also watch general-purpose retrieval while selecting on your own dev set?Pass a list such as `[dev_evaluator, NanoBEIREvaluator()]` as `evaluator`; the trainer wraps it in a `SequentialEvaluator` and logs every evaluator's metrics. Keep `metric_for_best_model` on your dev key, and read the NanoBEIR aggregate as a regression alarm.
- The lowest eval loss is a good enough signal for a retrieval fine-tune.
- InformationRetrievalEvaluator takes the same (anchor, positive) columns as training.
- metric_for_best_model can be just ndcg@10 without the evaluator name.
- Queries missing from relevant_docs count as misses and lower the score.
- The evaluator encodes queries and documents identically, ignoring model prompts.
Assumes Sentence Transformers v6; its evaluators use encode_query and encode_document, and v6.0 changed TripletEvaluator to match.