Skip to Content
Recodocs

12 · Train embeddings and rerankers

Separate missing evidence from poor ordering. Train two MiniLM retrievers and compare frozen and tuned rerankers on the same shortlist.

13 min read
Part 3
Adapt models
Model
sentence-transformers/all-MiniLM-L6-v2 · cross-encoder/ms-marco-MiniLM-L6-v2
Data
BEIR SciFact and official qrels at b3b5335604bf5ee3c4447671af975ea25143d4f5 and 2938d17dc3b09882fdb8c12bbbe2e2dc0e75a029 (CC BY-SA 4.0 on both cards).
Hardware
Tesla T4, in Google Colab

You maintain a search tool for a team that checks claims against scientific papers. A reviewer searches for evidence about chromosome segregation in stem cells. The first result is about gene expression, and the second is about differences among stem cells. Before you spend time training a new ranker, check whether the paper the reviewer needs reached the shortlist.

SciFact claim 100

Search input
All hematopoietic stem cells segregate their chromosomes randomly.
Judged evidence
4381486 · Haematopoietic stem cells do not asymmetrically segregate chromosomes or retain BrdU
Rank 1
9154703 · Single-Cell RNA-Seq Reveals Dynamic, Random Monoallelic Gene Expression in Mammalian Cells
Rank 2
13980338 · Combined Single-Cell Functional and Gene Expression Analysis Resolves Heterogeneity within Stem Cell Populations
Rank 3
2608447 · Somatic coding mutations in human induced pluripotent stem cells
Rank 4
8290760 · Single-Cell Expression Analyses during Cellular Reprogramming Reveal an Early Stochastic and a Late Hierarchic Phase
Rank 5
10766688 · Sperm cross-over activity in regions of the human genome showing extreme breakdown of marker association.

Claim and titles from SciFact. Document IDs and order from the saved Hard negatives shortlist output.

Predict the result of reranking these 20 candidates, then check the run

The sole judged abstract was absent from all 20 candidates. Both rerankers received exactly those candidates, so neither could return it. In the saved results both score zero for this claim. BM25 and the frozen embedding each found the judged abstract at rank 1. The embedding trained with random negatives found it at rank 2. Inspect claim 100 in the per-query CSV. Pinned SciFact claims and corpus · Official test judgements · Kiel et al., the judged paper

Recall@20 asks what fraction of the judged abstracts reached the shortlist. nDCG@10 asks how well the first ten results are ordered, giving more credit to hits near the top. For claim 100, a missing paper gives zero on both measures. A sole judged paper at rank 2 gives full recall and partial ranking credit.

Random negatives retrieved the most evidence. The frozen reranker ordered its shortlist best.

Mean scores on the same 300 claims, on a 0–1 scale

1

Shortlist coverage

Recall@20

0.00.51.0Lexical BM250.8323Frozen embedding0.8333Random negatives0.8567Hard negatives0.8341Frozen reranker0.8341Tuned reranker0.8341

Ordering near the top

nDCG@10

0.00.51.0Lexical BM250.6519Frozen embedding0.6443Random negatives0.6553Hard negatives0.6552Frozen reranker0.6828Tuned reranker0.6133
Source · Archived SciFact per-query CSV, 300 held-out claims. Both rerankers use the Hard negatives shortlist.

1. Count shortlist misses before tuning

An embedding model helps find candidates in a search pool. A reranker compares a smaller candidate list in more detail. If the correct document never enters that list, reranking cannot recover it.

SciFact links a claim to abstracts that support or dispute it. Both count as relevant for search. The job here is to find those abstracts, leaving claim verification to the reviewer. All six methods were evaluated on the same 300 official test claims over 5,183 abstracts. Two training queries matched normalised test text and were excluded. That left 807 training queries. There are 181 judged abstracts in both splits, so the test measures generalisation to unseen queries over a shared corpus.

For each query let G be its set of judged abstracts and R20 the first 20 retrieved. Average the following across the test claims, including claims with zero hits.

Recall@20⁡=∣G∩R20∣∣G∣\operatorname{Recall@20} = \frac{|G \cap R_{20}|}{|G|}

Random negatives raised observed mean recall from 0.8333 for Frozen embedding to 0.8567 (+0.0233, or 2.33 points on a 0–100 scale). Lexical BM25 scored 0.8323 and Hard negatives scored 0.8341. For Hard negatives, 245 claims got all their judged abstracts, nine got some and 46 got none. A query count gives you the size of the complete-miss queue. Mean recall also captures partially covered claims.

Forty-six claims reached both rerankers without judged evidence

Claims grouped by how many of their judged abstracts are in the first 20 results

2
AllSomeNone
Lexical BM25
243 all12 some45 none
Frozen embedding
246 all8 some46 none
Random negatives
253 all8 some39 none
Hard negatives
245 all9 some46 none
Source · Archived SciFact per-query CSV, 300 held-out claims. Counts are derived from per-query recall of 1, between 0 and 1, and 0.

Measure coverage at the depth you actually send downstream. Atlassian reports a 26–40% relative improvement across Recall@60 and nDCG@1 after adapting Llama-Nemotron-Embed-1B-v2 on a public Jira-like dataset. NVIDIA reports Recall@60 moving from 0.751 to 0.951 in that example. Those cutoffs measure a 60-result candidate stage and one displayed position, compared with 20 and ten here. Atlassian, company-reported offline benchmark · NVIDIA, Atlassian comparison

2. Change the training negatives

A bi-encoder turns a claim and each abstract into separate vectors. At search time, the notebook uses the dot product of normalised vectors, equivalent to cosine similarity. At training time, it compares one judged positive with one example selected as a negative. The hard branch takes the first unjudged BM25 result in the top 50. The random branch draws outside that pool. Both exclude all known positives and use the same claim, chosen positive, checkpoint, batch order and optimiser.

In this reconstructed training example, the hard negative describes a weight-management trial. It shares language about behavioural interventions, but studies a different programme from the one named in the claim. The selection was replayed from the pinned data and seed 42 without a model call.

Training claim 1157

Search input
The DESMOND program demonstrates no significant impact on biochemical outcomes.
Same positive
12584053 · Effectiveness of a diabetes education and self management programme (DESMOND) for people with newly diagnosed type 2 diabetes mellitus: three year follow-up of a cluster randomised controlled trial in primary care
Random negative
16270577 · Nonclassical binding of formylated peptide in crystal structure of the MHC class lb molecule H2-M3
Hard negative
6841927 · Transtheoretical model-based multiple behavior intervention for weight management: effectiveness on a population basis.
positive = min(relevant, key=lambda doc: (-relevant[doc], doc))
pool = lexical_rank(qid)[:50]
hard = next(doc for doc in pool if doc not in relevant)
random_negative = rng.choice(doc_ids)
while random_negative in relevant or random_negative in pool:
    random_negative = rng.choice(doc_ids)

The median share of unique claim terms present in the negative was 22.7% for random negatives and 57.1% for hard negatives. This checks that the two selections differed. The labels are incomplete, so an unjudged document can still be relevant.

The hard negatives shared more claim terms

Distribution across 807 training triplets in each branch

3

Random negatives

Median coverage 22.7%

01002003000%50%100%

Hard negatives

Median coverage 57.1%

01002003000%50%100%
Source · Archived SciFact notebook on one Tesla T4. Medians are printed in the run. Histograms derived by replaying negative selection on the pinned data without model calls.

Audit very close negatives. In NV-Retriever’s paper, capping a negative’s similarity at 95% of its query’s positive score raised average nDCG@10 from 0.5407 to 0.5856 across Natural Questions, HotpotQA and FiQA for one E5 recipe. It is an ablation on a different model and different data. The lab’s highest-ranked BM25 rule has no positive-score filter. NV-Retriever, paper-reported ablation, Table 3

The embedding fit uses a two-way softmax on the positive and negative cosine similarities. The formula uses the positive and negative similarities s+ and s− and a temperature of 0.05.

Lembed=−log⁡exp⁡(s+/τ)exp⁡(s+/τ)+exp⁡(s−/τ)\mathcal{L}_{\mathrm{embed}} = -\log\frac{\exp(s_+/\tau)}{\exp(s_+/\tau)+\exp(s_-/\tau)}
query, positive, negative = vectors.chunk(3)
logits = torch.stack(((query * positive).sum(1), (query * negative).sum(1)), dim=1) / 0.05
loss = F.cross_entropy(logits, torch.zeros(len(batch), device=DEVICE, dtype=torch.long))

The final ten updates averaged losses of 0.0024 for Random negatives and 0.2442 for Hard negatives. Those losses use different negatives, so read held-out retrieval metrics to decide which system to keep. Hard and random got 0.6552 and 0.6553 nDCG@10 respectively. The paired difference rounded to four decimal places was −0.0001 (−0.01 points) with a 95% interval of −0.0292 to +0.0307, within sampling noise.

Compare data recipes on held-out queries. On synthetic questions over its technical docs, NVIDIA’s vendor walkthrough reports nDCG@10 rising from 0.55506 to 0.61559 and Recall@10 from 0.62979 to 0.69296. That recipe combined hard-negative mining with multi-document supervision. The lab changes one negative selector at a time, so its comparison can isolate that choice for this fit. NVIDIA, vendor walkthrough and NVDocs results

3. Keep the shortlist fixed and change the scorer

A cross-encoder scores a claim and abstract together. It can use interactions between their words, and has to score every candidate pair. Both cross-encoders started from the same MS MARCO MiniLM checkpoint. The tuned one used the 807 Hard negatives triplets. The loss F.softplus(negative - positive).mean() penalises cases where the negative’s score approaches or exceeds the positive’s. Evaluation sorted the same 20 candidates by each scorer and checked set equality for every claim.

frozen_candidates = runs['Hard negatives']
runs['Frozen reranker'] = rerank(new_reranker().eval(), frozen_candidates)
runs['Tuned reranker'] = rerank(tuned_reranker, frozen_candidates)
for label in ('Frozen reranker', 'Tuned reranker'):
    assert all(set(runs[label][q]) == set(frozen_candidates[q]) for q in test_ids)

Claim 183 reached both rerankers with its sole judged paper. Keep the candidates fixed and predict what happens to recall as that paper moves up or down. The ranks below are derived from the saved nDCG and the single relevant judgement. For a single judged hit at rank i in the first ten positions, nDCG is 1 / log₂(i + 1). Hashimoto et al., the judged paper

SciFact claim 183

Search input
Bone marrow cells contribute to adult macrophage compartments.
Judged evidence
12827098 · Tissue-resident macrophages self-maintain locally throughout adult life with minimal contribution from circulating monocytes.
Hard negatives
Recall@20 1.0000 · nDCG@10 0.3155 · inferred rank 8
Frozen reranker
Recall@20 1.0000 · nDCG@10 1.0000 · inferred rank 1
Tuned reranker
Recall@20 1.0000 · nDCG@10 0.5000 · inferred rank 3

Scores from the saved CSV. All three methods were judged on the same evidence ID.

For more than one judged abstract, accumulate gain at each rank and divide by the best possible ordering for that claim. Let gᵢ be the judgement grade of the abstract at position i, with unjudged results scored as zero. The lab’s positive test grades are all 1.

DCG10=∑i=1102gi−1log⁡2(i+1)nDCG10=DCG10IDCG10\begin{aligned} \mathrm{DCG}_{10} &= \sum_{i=1}^{10}\frac{2^{g_i}-1}{\log_2(i+1)} \\ \mathrm{nDCG}_{10} &= \frac{\mathrm{DCG}_{10}}{\mathrm{IDCG}_{10}} \end{aligned}

Check what the reranker does on your query mix. In the original BEIR benchmark, cross-encoder reranking of BM25’s top 100 beat BM25 on 16 of 18 datasets. FiQA-2018 moved from 0.236 to 0.347 nDCG@10, while Touché-2020 fell from 0.367 to 0.271. The candidate depth and tasks differ from this lab. BEIR, paper-reported benchmark, Table 2

Compare claims in pairs

Subtract each claim’s baseline nDCG from its score under the candidate method. Draw 300 differences with replacement, take their mean and repeat 3,000 times. The middle 95% of those means is the interval. It measures uncertainty from the test queries for these particular fits. The experiment used one training seed, and incomplete judgements still limit what the metrics can see.

difference = np.asarray(changed) - np.asarray(baseline)
sample = np.random.default_rng(SEED).integers(0, len(difference), size=(3000, len(difference)))
low, high = np.quantile(difference[sample].mean(axis=1), [0.025, 0.975])

The frozen reranker led the observed comparison with 0.6828 nDCG@10, up 0.0277 from 0.6552 (+2.77 points) for the Hard negatives retriever before reranking. The interval derived from the CSV, −0.0017 to +0.0575, includes zero, so the observed rise is within test-query sampling noise. Fine-tuning fell to 0.6133, a change of −0.0696 (−6.96 points) against the frozen scorer. Its interval, −0.0948 to −0.0442, stayed below zero. Both rerankers kept the same 0.8341 Recall@20.

Only the tuned reranker’s interval excludes zero

Change in mean nDCG@10 with 95% paired bootstrap intervals. Each panel uses the same scale.

4

Frozen embedding → Random negatives

+0.0109 [−0.0047, +0.0264]

−0.10−0.050+0.05

Random negatives → Hard negatives

−0.0001 [−0.0292, +0.0307]

−0.10−0.050+0.05

Hard negatives → Frozen reranker

+0.0277 [−0.0017, +0.0575]

−0.10−0.050+0.05

Frozen reranker → Tuned reranker

−0.0696 [−0.0948, −0.0442]

−0.10−0.050+0.05
Source · Archived SciFact per-query CSV, 300 held-out claims. Derived from 3,000 paired resamples, seed 42. The notebook prints the second and fourth comparisons.

The tuned reranker improved 25 claims, tied 191 and worsened 84. Those counts show how often the score moved. The interval uses the size of those changes as well. Inspect the paired outcomes before assuming a small mean change affected very few claims.

Reranker tuning worsened 84 claims and improved 25

Claims by direction of nDCG@10 change, candidate versus baseline

5

Frozen embedding → Random negatives

46 improved216 tied38 worsened

Random negatives → Hard negatives

53 improved186 tied61 worsened

Hard negatives → Frozen reranker

65 improved191 tied44 worsened

Frozen reranker → Tuned reranker

25 improved191 tied84 worsened
Source · Archived SciFact per-query CSV, 300 held-out claims. Derived by matching the six result rows per claim ID.

What to keep

Keep BM25 as the lexical baseline. Random negatives are the first new retriever to test when the reviewer’s problem is missing papers: they had the highest observed recall and found the paper for claim 100. Keep the frozen reranker as the baseline for ordering the tested Hard negatives shortlist. Evaluate it on Random negatives or a lexical–dense union before changing the candidate source in deployment. The combined pipeline was outside this experiment. Hold back the tuned reranker for this recipe and data.

What you observeWhat to check nextWhat the lab supports
Claim 100, where the judged paper is missing from the shortlistLook at Recall@20 and zero-hit counts. Compare the lexical and dense candidate lists.BM25 and Random negatives found the paper. Neither fixed-list reranker could recover it.
Claim 183, where the right paper is present but low downHold candidate IDs fixed and compare nDCG@10.The frozen scorer moved the sole judged result from rank 8 to 1. The tuned scorer put it third.
Your hard-negative branch looks better on individual queriesInspect the paired mean and interval, then repeat across training seeds.Hard versus random was within query-sampling noise for mean nDCG@10.
A tuned scorer makes the same shortlist less usefulKeep the frozen scorer and choose training duration on a separate development set.Tuning worsened mean nDCG@10 on the same candidates. Median latency was effectively unchanged at the reported precision.
  • Keep a lexical baseline. BM25 found the paper for claim 100 even though Hard negatives missed it.
  • Count empty evidence lists. Recall alone can conceal the claims for which the reviewer received no judged evidence at all.
  • Keep candidate IDs fixed when judging a new scorer. Claim 183 isolates a change in ordering because each scorer had access to the same judged paper.
  • Check paired gains and losses. A mean can hide the queries that got worse. Open their per-query rows before adding the scorer to the search path.
  • Time the candidate depth you plan to serve. The measured scoring budget covers a batch of 20 pairs and excludes retrieval.
  • Next to try, not tested here: widen the shortlist, filter suspected false negatives, or choose the reranker’s update count on development queries. Prediction-first exercises

How it was built

The measured run used one Tesla T4 (14.56 GiB reported by PyTorch), CUDA 13.0 and Python 3.13.16. The notebook pins transformers==4.51.3, sentence-transformers==4.1.0 and rank-bm25==0.2.2 and records torch 2.14.1+cu130, numpy 2.4.6, pandas 2.2.3 and pyarrow 23.0.1. It loads public safetensors, uses no hosted inference API and downloads the public benchmark when uncached.

ControlRecorded setting
Checkpointsall-MiniLM-L6-v2 at 1110a243fdf4706b3f48f1d95db1a4f5529b4d41 and MS MARCO MiniLM-L6-v2 at 233902d25c440f23af6f7d6e94d2946bac0bee0a
DataSciFact corpus and queries at b3b5335604bf5ee3c4447671af975ea25143d4f5. Judgements at 2938d17dc3b09882fdb8c12bbbe2e2dc0e75a029. Both mirrors label the data CC BY-SA 4.0.
TrainingSeed 42, two epochs, 24 triplets per batch, a 192-token limit and AdamW at 2e-5. Each fit ran 68 updates.
Retrieval and rankingExact cosine ranking over the shared corpus. The two cross-encoders score the same Hard negatives top 20. Batch size 64 for offline vectorisation and batched reranking.

Fit timing starts before model initialisation and ends after the synchronised updates. Peak GPU memory is PyTorch’s allocated memory during that interval and may include models still resident from an earlier fit. The notebook’s full elapsed timer starts after package setup and logged 198.44 seconds. That includes data loading, retrieval, evaluation and the latency check. For the pinned licences and model details, see the embedding model card and cross-encoder model card.

All three fits took under 40 seconds each

68 updates per fit on the same Tesla T4

6

Elapsed fit time

Random negatives38.41 sHard negatives28.66 sTuned reranker23.87 s

Peak allocated GPU memory

Random negatives2.43 GiBHard negatives2.60 GiBTuned reranker2.07 GiB
Source · Archived SciFact notebook on one Tesla T4. The fit timer includes model initialisation and the update loop. Peak is total PyTorch allocated memory during that interval.

The latency check runs each model on the first 60 sorted test IDs, with five warm-up claims per model. Each timed call scores 20 pairs at once and synchronises the GPU before stopping the clock. It measures tokenisation, device transfer and scoring after candidates have been retrieved. The notebook does not clock retrieval, sorting, concurrency or serving.

start = perf_counter()
pair_scores(model, [qid] * CANDIDATES, frozen_candidates[qid])
torch.cuda.synchronize()
samples.append(1000 * (perf_counter() - start))

Both rerankers took 44.58 ms at the median

Latency per claim in milliseconds, for 60 claims with 20 candidates each

7

Frozen reranker

Median 44.58 ms · p95 51.01 ms

015304560

Tuned reranker

Median 44.58 ms · p95 52.05 ms

015304560
Source · Archived SciFact notebook on one Tesla T4. Tokenisation, GPU transfer and scoring. Retrieval, sorting and service overhead are outside the timer.

Run it yourself

Download the executed notebook · Download the exact run report · Download all 1,800 per-query rows

Open the notebook on a GPU runtime to repeat the experiment. Sections 1–3 record the environment, check the split and build the matched triplets. Sections 4–5 train the two embeddings and the tuned cross-encoder. Sections 6–7 produce the scorecard, paired intervals, latency samples and the claim 100 printout. Section 8 saves the report and CSV. The file above keeps the ten experiment cells and their saved outputs.

Check the saved files
RecordSHA-256
Query split, sorted ID lists after deduplication89a69035fc17f7144051bcab34b41aaf8647cce8e0d114abfb9c1783476f4fbb
Executed notebook68a419f1c391ee8c667cd73f51b0f7ad0942049b84ce42678e141e4cc3d5ad9c
Run reporte5b591c4aafd96ec5aec64be83e4e1236dbc6a5b38a7e3fda7bd665a8abeef5a
Per-query CSV15e9b974be59dc0f65d11b5740f9a96782304e851c9208d1bd8986fd0eda1efb

The report and CSV match the bytes saved by the original notebook. The report also matches the JSON printed by the final experiment cell. The six means, paired changes and coverage counts above can be reproduced from the CSV without GPU inference.

Pick one of these untested changes. Write down which measure you expect to move before you run it.

  1. More candidates. Predict whether abstract 4381486 will appear for claim 100 and how p95 scoring time will change. Raise CANDIDATES to 40 and parameterise the ranking[:20] slice in metrics so you can report Recall@40 alongside Recall@20. Keep nDCG@10 fixed and print 4381486 in frozen_candidates['100'] for the expanded list.
  2. A filter for hard negatives. Predict how many of the original 807 hard negatives a positive-aware filter would replace, and in which direction held-out nDCG@10 would move. In §3, cap candidates by 0.95 × positive cosine similarity from the frozen encoder, with a documented fallback if no candidates pass. Keep the Random negatives branch unchanged. Inspect the replacement count and the paired interval in §6.
  3. Early stopping on separate queries. Predict whether the tuned reranker still trails its frozen counterpart. Split the training queries into fit and development groups, keep the official test set locked, and choose the update count by development nDCG@10. Repeat the fit on a small set of seeds, then use §6 to compare the selected scorers on the same fixed test candidates.

Back to Advanced LLM Fine Tuning

How is this page?

Last updated on