Module contents
Lesson 17 of 31Core 110 min

Embeddings for search: dense retrieval and bi-encoder training

Study dense retrieval with bi-encoders, pooling and normalization, asymmetric query/document encoding, contrastive training with in-batch and mined hard negatives, and Matryoshka embeddings. Evaluate a small embedding model against BM25.

After this lesson you can

  • Implement a bi-encoder with masked mean pooling and normalization to retrieve passages.
  • Prove equivalence of cosine, dot-product and Euclidean rankings for normalized vectors.
  • Fine-tune an embedding model with contrastive loss, in-batch and BM25-mined hard negatives in a custom loop.
  • Diagnose false negatives among hard negatives and their training effect.
  • Evaluate recall@k and nDCG@10 against BM25 and measure quality after Matryoshka truncation.

Before you start

Searching when the words change

A query about “protecting people’s information” may need a passage about differential privacy even when the words do not match. Lexical retrieval is a strong, verifiable baseline, but a dense representation can bring different formulations together by context. Proximity does not guarantee a passage answers the query: measure it with independent judgments.

InteractiveA map is not the ranking
  • Passages
  • Query

Query: encontrar textos por significado

Neighbors by cosine

D1 · 0.838 · norm 4.73: Un índice invertido enumera los documentos donde aparece cada término.

D3 · 0.832 · norm 4.69: Los embeddings codifican consultas y pasajes en vectores para búsqueda semántica.

D8 · 0.831 · norm 4.79: El recall mide cuántos documentos relevantes se recuperan.

Unnormalized query norm4.664
First passageD1
Change the query and toggle normalization. Positions are a PCA projection of passages; neighbors are ranked using the original 384 dimensions.

The eight passages and three queries form a Spanish educational corpus encoded with multilingual E5 small, masked mean pooling and model-specific prefixes. Points are projected onto the first two principal components of normalized passages; queries use the same mean and basis. List scores were calculated before projection. Visual distance therefore does not always reproduce the full ranking. For the first query, normalization changes the first result: document norm participates in the unnormalized dot product.

Two encoders, one index

In dense retrieval a query and each document are converted into vectors and ranked by a similarity function. A bi-encoder calculates f(q)f(q) and g(d)g(d) separately. It may share weights or use distinct parameters. Document vectors are computed once and indexed; when a query arrives only it must be encoded and neighbors searched. DPR uses this separation to retrieve passages.

A cross-encoder processes each query-passage pair jointly and can model detailed interactions between their tokens, but does not permit precomputing one passage representation valid for every query. It is suitable for reranking a limited candidate set. A bi-encoder compares vectors and can miss relationships appearing only when reading the pair jointly. Sentence-BERT studies a Siamese architecture for comparable sentence embeddings.

Word embeddings, CBOW and GloVe assign representations to words; here we need a representation for an entire text and retrieval task. A transformer encoder produces contextual token states. Converting them to a vector requires defining included positions and aggregation.

Pooling, masks and geometry

Embedding pooling and normalization forms one vector per text. If hi∈Rd\vb{h}_i\in\R^d is the state of token ii and mi∈{0,1}m_i\in\{0,1\} indicates it is not padding, the masked mean is

z=∑imihi∑imi,z^=z∥z∥2.\vb{z}=\frac{\sum_i m_i\vb{h}_i}{\sum_i m_i},\qquad \hat{\vb{z}}=\frac{\vb{z}}{\norm{\vb{z}}_2}.

The mask must contain at least one valid token, and normalization requires nonzero norm. A mean including padding changes when the same text is processed alongside a longer one. CLS and last-token pooling are other rules; correct pooling depends on model training, not universal preference. In a causal model with right padding, “last token” means the last valid token, not necessarily the batch’s last column.

For unit vectors u\vb{u} and v\vb{v}, the dot product equals cosine and

∥u−v∥22=2−2u⊤v.\norm{\vb{u}-\vb{v}}_2^2=2-2\vb{u}\T\vb{v}.

Thus maximizing cosine or dot product and minimizing Euclidean distance yields the same ordering, including ties. Without normalization, u⊤v=∥u∥∥v∥cos⁡θ\vb{u}\T\vb{v}=\norm{\vb{u}}\norm{\vb{v}}\cos\theta: a large norm can dominate direction. A zero vector has undefined cosine. The cosine bound [−1,1][-1,1] follows from Cauchy-Schwarz; norm is not a detail to mix between insertion and query.

Query and document are not always symmetric

Asymmetric encoding recognizes that a short query and an answer-containing passage play different roles. It can use two encoders or the same encoder with different instructions. E5 requires “query: ” and “passage: ” even in other languages; that convention is in its model card. Other models use different instructions or none. Adding invented prefixes to a model not trained with them changes its input and is not guaranteed to improve anything.

Changing the encoder, prefix, normalization or corpus segmentation means old vectors no longer necessarily represent the same space. Version these settings with the index and rebuild vectors when appropriate. The next query must use the same similarity convention as the index.

Training a comparison

Contrastive retriever fine-tuning brings the query closer to a positive passage and separates it from alternative candidates. For a batch of BB pairs and temperature τ>0\tau>0, one direction of InfoNCE is

ℓi=−log⁡exp⁡(s(qi,di+)/τ)∑j=1Bexp⁡(s(qi,dj+)/τ)+∑hexp⁡(s(qi,dh−)/τ).\ell_i=-\log\frac{\exp(s(q_i,d_i^+)/\tau)} {\sum_{j=1}^B\exp(s(q_i,d_j^+)/\tau)+\sum_h\exp(s(q_i,d_h^-)/\tau)}.

Positives of other queries act as in-batch negatives, and hard negatives retrieved by BM25 or a previous model can be added. Temperature controls softmax concentration. If pijp_{ij} is softmax probability and yijy_{ij} is one for the designated positive, the derivative with respect to similarity is (pij−yij)/τ(p_{ij}-y_{ij})/\tau before averaging queries. Thus a high-probability negative receives a larger gradient.

InteractiveWhat does each negative teach?
QP1P2P3Hard
1
0.98
grad −0.45
−0.64
grad 0.00
−0.34
grad 0.01
0.87
grad 0.44
2
−0.34
grad 0.01
0.98
grad −0.06
−0.64
grad 0.00
0.00
grad 0.04
3
−0.64
grad 0.00
−0.34
grad 0.01
0.98
grad −0.02
−0.87
grad 0.00

Q are queries; P1 to P3 are designated positives. The fourth passage is treated as negative. The diagonal entries are the only positive labels.

0.30
30
Mean loss0.198
Gradient for query 1, hard candidate0.443
Move the hard candidate and temperature. Mark that it is also relevant: the label does not change and loss will keep pushing it in the wrong direction.

The figure’s matrix uses cosines of two-dimensional unit vectors defined by angles; these are not training observations. It shows exact loss and derivatives of the illustrative model. A false negative is a genuinely relevant passage not listed as positive. Mining only the most similar candidates can increase their proportion. Excluding known positive judgments and filtering suspicious similarities reduces the problem, but incomplete labels and an imperfect threshold do not prove irrelevance. False negatives can also occur among positives of other in-batch queries.

Adaptable-size embeddings

Matryoshka embeddings are trained so prefixes of different dimensions are useful. A loss sums objectives evaluated on several prefixes; after truncation, renormalize the prefix if search uses cosine. A conventional model can also be truncated, but was not necessarily optimized for that. Matryoshka Representation Learning formulates this multiscale training.

If DD is the set of widths and PdP_d takes the first dd coordinates, a retrieval variant minimizes

L=∑d∈Dλd Lcontrastiva ⁣(Pdf(q)∥Pdf(q)∥2,Pdg(d′)∥Pdg(d′)∥2),λd≥0.\Loss=\sum_{d\in D}\lambda_d\, \Loss_{\text{contrastiva}}\!\left( \frac{P_d f(q)}{\norm{P_d f(q)}_2}, \frac{P_d g(d')}{\norm{P_d g(d')}_2} \right),\qquad \lambda_d\ge 0.

Each term is evaluated over a full batch of queries and passages, not one pair, and requires nonzero prefixes. Early coordinates receive gradients from all sizes including them; the last receive gradients only from wider objectives. Weights λd\lambda_d determine the balance. The expression describes one possible recipe; the next curve uses a published model, not one trained by this cell.

InteractiveQuality versus width
  • Static MRL (1024 full)
  • Standard E5 (384 full)

30 queries, 532 documents: all their judged relevant documents plus 500 additional ones. This is a small test, not a conclusive model comparison.

128
Dimensions128
Recall@10 MRL0.867
Recall@10 E50.833
2 million float32 vectors977 MiB
Compare models at common dimensions and observe vector memory. Curves come from a run on the subset described below.

The test uses 30 SciFact test queries and all their judged relevant documents plus 500 additional documents, 532 total. It compares a static Matryoshka model with E5, which is not an identical control differing only by loss: architecture, data and full dimension also change. Curves are measurements on this selection and may not be monotonic. They do not prove a general improvement or equal the full benchmark. The graph avoids a second axis: memory is shown separately and excludes metadata and index structure.

Raw memory for NN vectors of dd components with bb bytes per component is NdbNdb. Reducing dimensions reduces storage and similarity operations, but not necessarily the cost of running the full encoder. Quantization or an approximate index adds other decisions. Quality must be measured after truncation and normalization with the same corpus and queries.

For example, two million 768-component float32 vectors occupy 6.144 billion bytes before the index; the same vectors in float16 occupy half. If the model supports a useful 256-component float32 prefix, those vectors occupy 2.048 billion bytes. Figures exclude identifiers, copies, fragmentation and search structures. Changing precision can also alter ties and neighbors: measure quality after conversion, not just memory.

Choosing and evaluating

MTEB collects diverse tasks, but an average across classification, similarity and retrieval does not replace measuring retrieval in your domain, language and query length. Also check training data: if they include evaluations or nearby examples, a public number may not measure generalization. For Spanish, use a representative multilingual evaluation and compare with BM25, with per-query judgments and the same cutoff. Recall@k measures coverage and nDCG@10 measures graded-relevance order; both were defined in the previous lesson. Incomplete pooled judgments and unjudged documents remain limitations.

Browser laboratory: checking each piece

This cell uses the figure’s eight passages, four additional passages and four queries, with their sixteen original 384-component E5 embeddings encoded using the pinned revision in the local laboratory. The embedded compressed file contains unnormalized float32 values, not the PCA projection. Judgments are educational annotations on this corpus, not a benchmark. It calculates masked mean, exact cosine search, BM25 and reciprocal fusion; it reports recall@3, recall@10 and nDCG@10. Twelve passages allow cutoff 10 to exclude documents. Fusion assigns rank even to zero lexical scores; stable tie-breaking is part of the protocol.

[ ]Pooling, search and fusion with full embeddingsBrowser
import numpy as np
import re, math
from collections import Counter

docs = ["Un índice invertido enumera los documentos donde aparece cada término.","BM25 satura la frecuencia y normaliza por la longitud del documento.","Los embeddings codifican consultas y pasajes en vectores para búsqueda semántica.","Un montículo mínimo conserva los mejores candidatos de una consulta.","La privacidad diferencial limita la influencia de un registro en una salida.","La atención transforma vectores de tokens usando consultas, claves y valores.","La precisión mide la fracción de resultados recuperados que son relevantes.","El recall mide cuántos documentos relevantes se recuperan.","El producto escalar mide la alineación de dos vectores.","Un reranker evalúa juntos la consulta y cada candidato.","La fusión de rankings combina ordenaciones de varios recuperadores.","La relevancia graduada distingue grados de utilidad de un pasaje."]
queries = ["encontrar textos por significado", "cuántos resultados pertinentes encontró", "proteger información de personas", "cómo ponderar términos en documentos"]
relevant = [{2}, {6, 7}, {4}, {1}]
hidden = np.array([[[1., 2.], [3., 4.], [99., 99.]]])
mask = np.array([[1., 1., 0.]])
pooled = (hidden * mask[..., None]).sum(axis=1) / mask.sum(axis=1, keepdims=True)
assert np.allclose(pooled, [[2., 3.]])
def normalize(X):
    n = np.linalg.norm(X, axis=1, keepdims=True)
    if np.any(n == 0): raise ValueError("vector nulo")
    return X / n
sim = normalize(Q) @ normalize(D).T
terms = lambda s: re.findall(r"\w+", s.lower())
dt = [terms(d) for d in docs]
lens = np.array([len(t) for t in dt])
def lexical(q):
    scores = np.zeros(len(docs))
    for word in set(terms(q)):
        freq = np.array([Counter(t)[word] for t in dt])
        df = np.count_nonzero(freq)
        idf = np.log1p((len(docs)-df+0.5)/(df+0.5))
        scores += idf*freq*2.2/(freq+1.2*(0.25+0.75*lens/lens.mean()))
    return scores
def ranking(scores):
    return np.argsort(-scores, kind="stable")
def rrf(a, b):
    out = np.zeros(len(docs))
    for rank, j in enumerate(a, 1): out[j] += 1/(60+rank)
    for rank, j in enumerate(b, 1): out[j] += 1/(60+rank)
    return ranking(out)
def metrics(order, rel, k):
    hits = [int(j in rel) for j in order[:k]]
    recall = sum(hits)/len(rel)
    dcg = sum(v/math.log2(i+2) for i,v in enumerate(hits))
    ideal = sum(1/math.log2(i+2) for i in range(min(k,len(rel))))
    return recall, dcg/ideal
for i, q in enumerate(queries):
    dense = ranking(sim[i])
    sparse = ranking(lexical(q))
    fused = rrf(dense, sparse)
    for name, order in [("denso", dense), ("BM25", sparse), ("fusión", fused)]:
        print(q, name, "recall@3", metrics(order, relevant[i], 3)[0],
              "recall@10,nDCG@10", metrics(order, relevant[i], 10))

Fusion sums, for each document, the reciprocal of a constant plus its position in each ranking. It does not require BM25 and cosine scales to match. It does not guarantee outperforming both: check by query and keep evaluation separate from any weight or cutoff tuning.

Local laboratory: encoding and fine-tuning

You need local Python with PyTorch, transformers, sentence-transformers, rank_bm25 and requests, plus a connection to download models and SciFact. The next block reconstructs the first figure: it calculates unnormalized vectors, full similarities and PCA projection. The first three queries are those in the figure; the fourth and four extra passages complete the browser example. PCA sign can change without changing distances. Its output documents the calculation; it does not depend on platform temporary files.

[ ]Reconstruct E5 spaceLocal GPU
import json
import numpy as np
import torch
from transformers import AutoTokenizer, AutoModel

model_name = 'intfloat/multilingual-e5-small'
docs = [
    'Un índice invertido enumera los documentos donde aparece cada término.',
    'BM25 satura la frecuencia y normaliza por la longitud del documento.',
    'Los embeddings codifican consultas y pasajes en vectores para búsqueda semántica.',
    'Un montículo mínimo conserva los mejores candidatos de una consulta.',
    'La privacidad diferencial limita la influencia de un registro en una salida.',
    'La atención transforma vectores de tokens usando consultas, claves y valores.',
    'La precisión mide la fracción de resultados recuperados que son relevantes.',
    'El recall mide cuántos documentos relevantes se recuperan.',
]
queries = ['encontrar textos por significado', 'cuántos resultados pertinentes encontró', 'proteger información de personas', 'cómo ponderar términos en documentos']
revision = '614241f622f53c4eeff9890bdc4f31cfecc418b3'
tok = AutoTokenizer.from_pretrained(model_name, revision=revision)
model = AutoModel.from_pretrained(model_name, revision=revision).eval()
def encode(texts):
    with torch.inference_mode():
        x = tok(texts, padding=True, truncation=True, max_length=128, return_tensors='pt')
        h = model(**x).last_hidden_state
        mask = x['attention_mask'].unsqueeze(-1)
        return ((h * mask).sum(1) / mask.sum(1)).numpy()
d = encode(['passage: ' + s for s in docs])
q = encode(['query: ' + s for s in queries])
dn = d / np.linalg.norm(d, axis=1, keepdims=True)
qn = q / np.linalg.norm(q, axis=1, keepdims=True)
# PCA sobre pasajes normalizados; las consultas se proyectan con la misma media y base.
center = dn.mean(0)
_, _, vt = np.linalg.svd(dn - center, full_matrices=False)
dp = (dn-center) @ vt[:2].T
qp = (qn-center) @ vt[:2].T
data = {'docs': docs, 'queries': queries, 'docProjection': dp.tolist(), 'queryProjection': qp.tolist(),
        'cosine': (qn @ dn.T).tolist(), 'dot': (q @ d.T).tolist(),
        'docNorms': np.linalg.norm(d,axis=1).tolist(), 'queryNorms': np.linalg.norm(q,axis=1).tolist()}
print('model:', model_name, 'shapes:', d.shape, q.shape)
for query, sims in zip(queries, data['cosine']):
    print(query, 'nearest doc:', int(np.argmax(sims)), 'cosine:', max(sims))
print(json.dumps(data, ensure_ascii=False))
# Cuatro pasajes adicionales del laboratorio de navegador, codificados igual.
extra_docs = ['El producto escalar mide la alineación de dos vectores.',
              'Un reranker evalúa juntos la consulta y cada candidato.',
              'La fusión de rankings combina ordenaciones de varios recuperadores.',
              'La relevancia graduada distingue grados de utilidad de un pasaje.']
extra_d = encode(['passage: ' + s for s in extra_docs])
print('vectores originales navegador:', np.concatenate([d, extra_d]).shape, q.shape)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The next cell reconstructs the truncation curve. It uses the test split only as a descriptive demonstration, takes its first 30 queries by identifier, includes all judged relevant documents and adds the first 500 remaining corpus documents. This is a small selection deliberately enriched with relevant documents. It compares two different models, so it does not causally isolate Matryoshka loss. It is omitted from automatic tests because it downloads weights and encodes hundreds of texts; you can run it fully locally.

[ ]Reconstruct the truncation curveLocal GPU
import sys, json, zipfile, csv, io
import numpy as np
import torch
from sentence_transformers import SentenceTransformer

import requests
response = requests.get('https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/scifact.zip', timeout=90)
response.raise_for_status()
with zipfile.ZipFile(io.BytesIO(response.content)) as z:
    corpus = [json.loads(x) for x in z.read('scifact/corpus.jsonl').decode('utf-8').splitlines()]
    queries = {x['_id']: x['text'] for x in map(json.loads, z.read('scifact/queries.jsonl').decode('utf-8').splitlines())}
    rows = list(csv.DictReader(io.StringIO(z.read('scifact/qrels/test.tsv').decode('utf-8')), delimiter='\t'))
qrels = {}
for row in rows:
    if int(row['score']) > 0:
        qrels.setdefault(row['query-id'], set()).add(row['corpus-id'])
qids = sorted(qrels)[:30]
needed = set().union(*(qrels[q] for q in qids))
others = [x for x in corpus if x['_id'] not in needed][:500]
selected = [x for x in corpus if x['_id'] in needed] + others
ids = [x['_id'] for x in selected]
texts = [x.get('title', '') + ' ' + x['text'] for x in selected]
qs = [queries[q] for q in qids]
result = {'queries':len(qids),'documents':len(ids),'models':{}}
for name, prefix in [('sentence-transformers/static-retrieval-mrl-en-v1', False), ('intfloat/multilingual-e5-small', True)]:
    revision = '614241f622f53c4eeff9890bdc4f31cfecc418b3' if prefix else 'f60985c706f192d45d218078e49e5a8b6f15283a'
    model = SentenceTransformer(name, revision=revision, device='cuda' if torch.cuda.is_available() else 'cpu')
    q = model.encode([('query: ' if prefix else '')+s for s in qs], batch_size=16, show_progress_bar=True, normalize_embeddings=False)
    d = model.encode([('passage: ' if prefix else '')+s for s in texts], batch_size=16, show_progress_bar=True, normalize_embeddings=False)
    dims = [32,64,128,256,min(q.shape[1], d.shape[1])]
    out = []
    for dim in sorted(set(dims)):
        a, b = q[:,:dim], d[:,:dim]
        a = a/np.maximum(np.linalg.norm(a,axis=1,keepdims=True),1e-12)
        b = b/np.maximum(np.linalg.norm(b,axis=1,keepdims=True),1e-12)
        sims = a @ b.T
        recalls = []
        for i,qid in enumerate(qids):
            order = np.argsort(-sims[i], kind='stable')[:10]
            recalls.append(len(set(ids[j] for j in order) & qrels[qid])/len(qrels[qid]))
        out.append({'dim':dim, 'recall10':float(np.mean(recalls))})
    result['models'][name] = out
    print(name, out, flush=True)
print(result)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Now use the full SciFact dataset. This cell mines negatives with BM25, excludes known relevant documents and discards candidates with cosine at least 0.95 to the query under the initial encoder. That threshold is a heuristic, not a perfect detector. The batch can also contain false negatives among positives of other queries. It then compares custom InfoNCE with MultipleNegativesRankingLoss in evaluation mode, trains one pass with AdamW and evaluates before and after on test queries, as well as BM25. Test data are not used in fitting or threshold selection. quick=True limits queries to test the pipeline; False uses all. It is excluded from automatic tests due to the cost of encoding the corpus twice and training; run the full cell locally to measure your configuration.

[ ]Contrastive fine-tuning and separate evaluationLocal GPU
import csv, io, json, re, zipfile, requests
from collections import defaultdict
import numpy as np
import torch
from sentence_transformers import SentenceTransformer, losses
from rank_bm25 import BM25Okapi
from torch.nn import functional as F

quick = False  # True: 16 consultas de entrenamiento y 20 de test
torch.manual_seed(0)
np.random.seed(0)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
response = requests.get('https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/scifact.zip', timeout=90)
response.raise_for_status()
with zipfile.ZipFile(io.BytesIO(response.content)) as z:
    corpus = [json.loads(x) for x in z.read('scifact/corpus.jsonl').decode('utf-8').splitlines()]
    queries = {x['_id']: x['text'] for x in map(json.loads, z.read('scifact/queries.jsonl').decode('utf-8').splitlines())}
    def read_qrels(split):
        out = defaultdict(set)
        for row in csv.DictReader(io.StringIO(z.read(f'scifact/qrels/{split}.tsv').decode('utf-8')), delimiter='\t'):
            if int(row['score']) > 0: out[row['query-id']].add(row['corpus-id'])
        return out
    train, test = read_qrels('train'), read_qrels('test')
ids = [x['_id'] for x in corpus]
texts = [x.get('title', '') + ' ' + x['text'] for x in corpus]
lookup = {d:i for i,d in enumerate(ids)}
terms = lambda s: re.findall(r'\w+', s.lower())
bm = BM25Okapi([terms(x) for x in texts])
model = SentenceTransformer('intfloat/multilingual-e5-small', revision='614241f622f53c4eeff9890bdc4f31cfecc418b3', device=device)
train_ids = sorted(train)
test_ids = sorted(test)
if quick: train_ids, test_ids = train_ids[:16], test_ids[:20]
print('training queries:', len(train_ids), 'test queries:', len(test_ids), 'documents:', len(ids), flush=True)

def encode_passages():
    return model.encode(['passage: '+s for s in texts], batch_size=16, normalize_embeddings=True,
                        convert_to_numpy=True, show_progress_bar=True)
def encode_queries(qids):
    return model.encode(['query: '+queries[q] for q in qids], batch_size=16, normalize_embeddings=True,
                        convert_to_numpy=True, show_progress_bar=False)
def evaluate_ranks(ranks):
    recalls, ndcgs = [], []
    for q, scores in zip(test_ids, ranks):
        order = np.argsort(-scores, kind='stable')[:10]
        grades = [int(ids[i] in test[q]) for i in order]
        recalls.append(sum(grades)/len(test[q]))
        dcg = sum(g/np.log2(i+2) for i,g in enumerate(grades))
        ideal = sum(1/np.log2(i+2) for i in range(min(10,len(test[q]))))
        ndcgs.append(dcg/ideal if ideal else 0.)
    return float(np.mean(recalls)), float(np.mean(ndcgs))
def evaluate(vectors):
    return evaluate_ranks(encode_queries(test_ids) @ vectors.T)

vectors = encode_passages()
before = evaluate(vectors)
bm_test = evaluate_ranks([bm.get_scores(terms(queries[q])) for q in test_ids])
qtrain = encode_queries(train_ids)
triples, rejected = [], 0
for j,qid in enumerate(train_ids):
    order = np.argsort(-bm.get_scores(terms(queries[qid])), kind='stable')
    negative = None
    for idx in order:
        if ids[idx] in train[qid] or (qtrain[j] @ vectors[idx]) >= 0.95:
            rejected += 1
            continue
        negative = idx
        break
    if negative is not None:
        positive = lookup[sorted(train[qid])[0]]
        triples.append((qid, positive, negative))
print('triples:', len(triples), 'candidatos filtrados:', rejected, flush=True)
features = lambda texts: {k:(v.to(device) if hasattr(v, 'to') else v) for k,v in model.tokenize(texts).items()}
def batch_features(batch):
    return [features(['query: '+queries[q] for q,p,n in batch]),
            features(['passage: '+texts[p] for q,p,n in batch]),
            features(['passage: '+texts[n] for q,p,n in batch])]
def own_loss(fs, temp=0.05):
    q,p,n = [F.normalize(model(x)['sentence_embedding'], dim=1) for x in fs]
    logits = q @ torch.cat([p,n],dim=0).T / temp
    return F.cross_entropy(logits, torch.arange(q.shape[0], device=device))
model.eval()
fs = batch_features(triples[:4])
ref = losses.MultipleNegativesRankingLoss(model, scale=20.0)
with torch.no_grad():
    own, lib = own_loss(fs), ref(fs, None)
print('loss own/reference:', own.item(), lib.item(), flush=True)
assert torch.allclose(own, lib, atol=1e-5)

model.train()
opt = torch.optim.AdamW(model.parameters(), lr=2e-5)
steps = []
for start in range(0, len(triples), 4):
    batch = triples[start:start+4]
    if len(batch) < 2: continue
    opt.zero_grad(set_to_none=True)
    loss = own_loss(batch_features(batch))
    loss.backward()
    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.)
    opt.step()
    steps.append(loss.item())
model.eval()
after = evaluate(encode_passages())
print('training steps:', len(steps), 'first and last loss:', steps[0], steps[-1])
print('test recall@10, nDCG@10 before:', before, 'after:', after)
print('test recall@10, nDCG@10 BM25:', bm_test)
print('quick scope:', quick)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

A fall in training loss does not necessarily imply test improvement. Record seed, versions, query and document, per-query results and mining conditions. If fine-tuning worsens, inspect false negatives, truncated length and ranking changes before declaring a cause.

A short check with 16 training queries and 20 test queries over 5183 documents performed four steps. First-batch loss in evaluation mode was 1.423656 in the custom implementation and 1.423656 in the library; recall@10 rose from 0.85 to 0.925 and nDCG@10 from 0.6873 to 0.7433. BM25 on the same query selection obtained 0.7833 and 0.6484 respectively. These are results of that small test and one seed, not evidence that full fine-tuning improves generally. Running all queries is left for your environment and is not presented here as a measurement.

Exercises

ProofOne ranking, three expressions
Prove: For a unit-norm query and documents, sorting by descending cosine, descending dot product or ascending Euclidean distance produces the same ranking.
0
All vectors are nonzero and normalized.

Step 1 of 3. How are cosine and dot product related?

NumericVector budget
For two million passages calculate the sum, in decimal bytes, of these three independent indices: 768 float32 dimensions, 768 float16 dimensions and 256 float32 dimensions. Count only vectors.
Quiz
Why can hard negatives mined with the model itself worsen fine-tuning if not filtered?
Quiz
A model was trained without query or passage prefixes. What should you do before adding them?
CodeMasked mean
Implement mean_pool(hidden, attention_mask) using NumPy. hidden has shape (B,T,D), the mask (B,T), with at least one valid token per row. Return (B,D) and exclude padding.
import numpy as np
def mean_pool(hidden, attention_mask):
  pass
Shift+Enter to run
Key idea
A useful embedding depends on how it was trained, how its tokens are pooled and normalized, and per-query evaluation on your corpus; geometric proximity alone does not prove relevance.