skip to content

When you run Sentence Transformers' util.mine_hard_negatives over (question, answer) pairs, how do you stop it from mining answers that are actually correct?

level: seniorimportance: should knowfreq 9%

answer

  1. the closest candidates are suspect
  2. skip the top ranks
  3. a margin below the positive
  4. rescoring with a CrossEncoder
  5. range_min, relative_margin, max_score

basics

~20 s

Treat the very closest candidates as suspect: skip the top ranks with range_min, require a gap below the positive with relative_margin or absolute_margin, cap max_score, and optionally rescore candidates with a cross_encoder before they are filtered.

solid answer

~40 s

`mine_hard_negatives` embeds the questions and a candidate corpus (the answer column, plus any `corpus` you pass), retrieves each question's nearest candidates, removes that question's own positives by exact text, and keeps `num_negatives` of the rest. The danger is that the nearest non-matching answers are often correct answers nobody labelled. So I skip the top of the ranking with `range_min`, bound the window with `range_max`, and require each negative to score clearly below the positive with `relative_margin` (0.05 is the setting the docstring recommends from published mining research) or `absolute_margin`, plus a `max_score` ceiling. If I have a reranker, passing it as `cross_encoder` rescores the candidates before those filters apply. I read the statistics it prints, and I choose `output_format` knowing that `"triplet"` writes one row per negative.

code

python · 17 lines
python
from sentence_transformers import SentenceTransformer
from sentence_transformers.util import mine_hard_negatives

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

# pairs: a datasets.Dataset with columns ["question", "answer"]
mined = mine_hard_negatives(
    dataset=pairs,
    model=model,
    range_min=10,           # skip the closest ranks, where unlabelled positives hide
    range_max=50,
    relative_margin=0.05,   # keep a negative only if it scores 5% below the positive
    num_negatives=5,
    sampling_strategy="random",
    output_format="n-tuple",  # question, answer, negative_1 ... negative_5
    batch_size=128,
)

go deeper

for a junior

Recall that the utility turns pairs into rows with negatives, and that the nearest wrong-looking candidates may be correct answers nobody labelled.

for a middle

Explain range_min against min_score, absolute against relative margin, and how triplet and n-tuple outputs differ in row count and dropped pairs.

for a senior

Tune the filters from the printed statistics, spot-check mined rows for false negatives, and decide when a cross_encoder or a wider corpus is worth the extra mining time.

for a principal

Decide how much labelling effort to trade for mining heuristics, and make mining reproducible by pinning the mining model and caching its embeddings.

## What the utility does `sentence_transformers.util.mine_hard_negatives` turns a dataset of `(anchor, positive)` pairs into a dataset with **hard negatives**: texts that look similar to the anchor but are not its answer. Training a ranking loss such as `MultipleNegativesRankingLoss` on those rows makes the task harder than random in-batch negatives alone. The steps: 1. It reads the anchor and positive columns (the first two columns unless `anchor_column_name` / `positive_column_name` say otherwise). 2. It builds a candidate **corpus** from the positive column, plus any extra texts passed as `corpus`, and deduplicates it. 3. It embeds queries and corpus with the given `model` (`batch_size`, optional `query_prompt_name` / `corpus_prompt_name` for prompted models, optional FAISS search with `use_faiss=True`, optional `cache_folder` for the embeddings). 4. It retrieves the top candidates per query, optionally rescores them with a `cross_encoder`, discards the query's own positives, applies the rank, score and margin filters, and samples `num_negatives` per query with `sampling_strategy` `"top"` (default) or `"random"`. ## Why the closest candidates are dangerous The utility removes a question's positives **by exact text only**. In support data the same fix is often written several ways, and many tickets have more than one acceptable answer. Those alternatives are the nearest neighbours of the question, so a naive "take the top 3" turns correct answers into negatives. A **false negative** teaches the model to push a right answer away, which is worse than no negative at all. ## The filters and what each guards against | Argument | What it does | Guards against | |---|---|---| | `range_min` | skips the first N ranks of the candidate list | unlabelled positives clustered at the top | | `range_max` | stops considering candidates beyond rank N | slow mining and easy, useless negatives | | `max_score` | rejects candidates scoring above a ceiling | near-duplicates of the positive | | `min_score` | rejects candidates scoring below a floor | negatives too easy to teach anything | | `absolute_margin` | negative must score at least this much below the positive | candidates as close as the positive itself | | `relative_margin` | same, as a fraction of the positive's score | the same, scaled to each query | | `cross_encoder` | rescores candidates with a reranker before filtering | a bi-encoder's coarse similarity | The docstring cites a published study of mining methods and reproduces its strongest setting as `relative_margin=0.05` with `sampling_strategy="top"` and ten negatives or fewer. When `range_max` is left unset, the utility derives it from `range_min`, `num_negatives` and the number of positives per query, widening it when a margin or `max_score` is set because more candidates will be rejected. ## Choosing the output format - **`"triplet"`** (default) writes `(anchor, positive, negative)` rows, **one row per negative**. With `num_negatives=5` a pair becomes up to five rows that repeat the same anchor and positive, which is one more reason to train with `BatchSamplers.NO_DUPLICATES`. - **`"n-tuple"`** writes one row per pair with columns `negative_1` to `negative_n`, and **drops pairs for which it could not find `num_negatives` valid negatives**. The column count stays fixed, which `SentenceTransformer` training requires. - **`"labeled-pair"`** and **`"labeled-list"`** produce 0/1 labelled data, aimed at CrossEncoder training rather than at embedding losses. - `output_scores=True` adds the similarity scores, useful for distillation losses that need them. ## Keeping mining affordable Mining embeds every query and every corpus text once, then runs a nearest-neighbour search, so on large datasets it is a job of its own: - `use_faiss=True` switches the search to FAISS, which the docstring recommends for large datasets; on GPU it caps the candidates per query at 2048 and trims an automatically derived `range_max` to fit. - `cache_folder` stores the query and corpus embeddings and reloads them on the next call, keyed by model, prompts and texts, so re-tuning the filters does not re-embed. - `use_multi_process` spreads encoding over several GPUs or CPU processes. ## Reading the run With `verbose=True` (the default) the utility prints positive and negative score distributions, how many candidates each filter skipped, and how many queries ended up short of negatives. Use them: - A **negative mean close to the positive mean** suggests the filters are too loose and false negatives are getting through. - A **large share of queries without enough negatives** means the window is too narrow or the margin too strict; widen `range_max` or relax the margin. - Spot-check a sample of mined rows by hand; a handful of genuinely correct "negatives" is the clearest signal to raise `range_min` or add a `cross_encoder`. Why a cross-encoder judges pairs more reliably than the bi-encoder is a reranking question of its own; here it is simply a better scorer to filter with.

  • Mining reports that a large share of queries could not get enough negatives. What do you adjust?
    Widen the candidate window with a larger `range_max`, lower `range_min`, or relax `relative_margin` / `max_score`, then re-check the score statistics. With `output_format="n-tuple"` those queries are dropped entirely, so leaving it unaddressed silently shrinks the training set.
  • Why would you pass a separate corpus to mine_hard_negatives?
    By default only the dataset's positive column is the candidate pool, so negatives can only be other questions' answers. Passing `corpus` adds texts such as the full help-centre article set, giving harder and more varied negatives; the positives are still added to it and the whole corpus is deduplicated.

  • The highest-scoring non-matching answers are always the best hard negatives.
  • mine_hard_negatives automatically excludes paraphrases of the positive.
  • The triplet output keeps the same number of rows as the input pairs.
  • range_min is a minimum similarity score that a candidate must reach.
  • Mined hard negatives replace the in-batch negatives of the ranking loss.