Module contents
Stage 8 of 9Research 110 min

Retriever fine-tuning and multi-hop queries

Use the error taxonomy to improve retrieval: fine-tune the embedding model on GPU with contrastive loss and hard negatives mined from the index, and add hypothetical-document query rewriting and iterative retrieval for multi-hop questions. Validate each improvement on the frozen test set with paired tests.

After this lesson you can

  • Generate training pairs without test-set overlap and mine hard negatives.
  • Fine-tune the embedding model with InfoNCE on the RTX 4060 and reindex.
  • Implement query rewriting and iterative multi-hop retrieval.
  • Validate each improvement on the frozen test set with paired bootstrap.

Before you start

When good retrieval requires learning

A search engine returns ten fluent chunks related to the question, but none contains the answer. The generator can produce a convincing answer citing one; no improvement in writing retrieves missing evidence. Before fine-tuning, inspect the failure with the error taxonomy: is the source absent from the corpus, lost in chunking, missing from candidates, or present but unused by the agent? Only the third case directly points to retriever ranking. Contrastive tuning cannot fix a nonexistent source or turn a literal citation into semantic support.

In dense retrieval, query and passage are vectors ranked by similarity. Fine-tuning the encoder changes that geometry: some documents become closer neighbors for certain questions. The figure compares projections from a recorded run. Useful distances and cosines are computed in the original space, not inferred from two-dimensional separation. If UMAP is fitted separately before and after, an imagined arrow between panels does not represent comparable physical displacement.

InteractiveRetriever space before and after

The first eight queries by lexicographic ID from the internal development partition of SciFact train. These external examples are exploratory. The negative is the first result in the original ranking without known positive evidence for that query.

Query 1073, split internal development split of SciFact train; annotated positive 4824840; highlighted negative 17023584.

  • Query 1073
  • Its annotated positive
  • Its mined negative
  • Other queries and documents

Positive 4824840: cosine before 0.859, after 0.647, difference −0.213. Corpus ranks: 1 before, 1 after.

Negative 17023584 (highlighted): cosine before 0.843, after 0.352, difference −0.492. Corpus ranks: 2 before, 55 after.

Cosines use the original embeddings. A positive difference means greater similarity, while retrieval quality depends on ranking and evidence. UMAP compresses dimensions and distorts distances. The before and after projections use independent orientations and scales, so screen movement cannot measure movement in embedding space. An unannotated negative can still contain valid evidence.

Data provenance

Model intfloat/multilingual-e5-small, revision 614241f622f53c4eeff9890bdc4f31cfecc418b3; UMAP 0.5.9.post2, cosine, n_neighbors=10, min_dist=0.1, seed 20261028. Two independent projections. Ranks across 5183 documents use descending cosine and break ties by numeric ID. SHA-256: projections be5bed5f72cd5cce8390b9bb6f764696f53e8205da86aaa7b358ab20d94dfbff, vectors 9d3759943958949ace6f5c6b1bcfb9da5b14926ee4a3ddfdce9b521e08a85630, protocol c9a695041115713cd80ccddd38b7d8cf485bf200194b0ca54d91635d69543414.

Embeddings
Cosine margin, positive − negative0.016
Positive rank1
Negative rank2
Inspect queries, positives, and hard candidates from one specific run. Projection reduces dimensions; compare original cosines and do not assume every point improves.

The lesson’s target has two parts, both measured on the evaluation you manually reviewed and froze in the custom collection: improved recall@10 on its test questions with a paired bootstrap interval excluding zero, and improved agent success on multi-hop tasks under the agent evaluation protocol. The labs supply pieces in order. First, full contrastive fine-tuning on SciFact, with expert relevance labels to check the procedure end to end; the same cell accepts your collection’s development pairs. Then two rewriting and iterative-retrieval controls on HotpotQA. Finally, a cell compares baseline and fine-tuned encoders on your frozen test and guidance measures agent success with the new retriever. A favorable interval on an external benchmark does not replace comparison on your collection: it measures a different estimand over another question and document distribution.

Split before generating

Choose a split unit matching what you want to generalize to. If multiple questions, versions, or chunks derive from one paper, assign the paper or duplicate group to one split. Freeze assignments and save identifiers, versions, and hashes before generating questions or mining candidates. Also split by document family when revisions are nearly identical or a paper and preprint coexist. Random pair splitting can place the same passage or an overlapping chunk on both sides and measure memorization. Search for text duplicates and title, author, and content similarity; review doubtful cases and retain the criterion.

Two different experimental questions exist. For generalization to new documents, do not generate training examples from test documents. In transductive retrieval over a known corpus, the index may contain documents appearing as test candidates, but test queries and relevance judgments must not participate in training or selection. Specify which is measured. Sharing a corpus does not automatically invalidate the second question, but does not establish the first. If your goal requires separate sources, do not silently substitute the transductive scenario.

To create a pair, take an authorized training chunk, propose a query it can answer, and retain the document and version reference. Automatic generation can invent a premise, ask a question too broad, or include the answer literally. Human review must check the passage answers it, the question is unambiguous, and no missing context is needed. Save proposals, rejections, and corrections; a model validating its own proposal is not independent review. If a question has multiple valid passages, record all known ones. Incomplete relevance affects training and metrics.

Do not use test questions or answers to choose temperature, negative count, or epoch. Development allows choosing these and detecting failures; test comes after the procedure is fixed. Repeated inspection to tune the system turns it into development methodologically. For multi-hop tasks separate not only final questions but also intermediate sources and connected question families when the hypothesis requires generalizing to new sources. Retain provenance for every hop: an ID list without versions or relationships does not demonstrate the evidence chain.

The negative that actually answered

Mining starts with a baseline-model index and training queries. Retrieve more candidates than needed and remove the known positive, duplicates, and overlapping chunks of the same answer. Then check whether other candidates also answer: lack of a label is not evidence of irrelevance. A result from the same document may provide the fact in other words; a different document may be a second correct source. Penalizing these as negatives pushes down documents the system should retrieve.

There is a deliberate tension: a random negative is often easy, so the model already scores it far below the positive and receives little signal. A close candidate is informative precisely because it is hard to distinguish, but may also be an omitted positive. Excluding by rank, author, or similarity is an approximate filter, not proof of falsity. Retain an “uncertain” category, inspect a sample, and where possible expand annotations before calling it negative. Mixing random and hard negatives allows comparing their signals. Record index, encoder, candidate count, and filter; remining with a new model changes the training distribution.

Noise also affects other batch positives. If two queries share a relevant passage or equivalent positives, treating the other’s positive as a negative causes the same conflict. An ID and known-relevance mask prevents some cases; it does not discover unannotated relevance. A multi-positive loss assigning mass to a valid set is another option, but requires specifying that set and does not solve incomplete labels. Source-group sampling reduces collisions but may reduce diversity or make comparisons too easy. No filter should be described as perfect without measurement.

One loss, many candidates

Let a batch contain BB pairs (qi,pi)(\vb{q}_i,\vb{p}_i) and, for query ii, a set HiH_i of hard negatives. The encoder produces the vectors; if using cosine, normalize them and explicitly handle zero-norm vectors. With score s(q,p)s(\vb{q},\vb{p}) and temperature τ>0\tau>0, one query’s loss is

ℓi=−log⁡exp⁡(s(qi,pi)/τ)∑j=1Bexp⁡(s(qi,pj)/τ)+∑h∈Hiexp⁡(s(qi,h)/τ).\ell_i=-\log\frac{\exp(s(\vb{q}_i,\vb{p}_i)/\tau)}{\sum_{j=1}^{B}\exp(s(\vb{q}_i,\vb{p}_j)/\tau)+\sum_{\vb{h}\in H_i}\exp(s(\vb{q}_i,\vb{h})/\tau)}.

The mean over ii is batch loss. The denominator contains the positive once, the other B−1B-1 positives as in-batch negatives, and that query’s hard negatives. With masks omit forbidden candidates from the denominator; do not remove the query’s own positive. This expression assumes one positive per query; a multi-positive rule needs another formula. If each query brings a hard negative hj\vb{h}_j and they are shared across the batch, as the lab and MultipleNegativesRankingLoss do, then Hi={h1,…,hB}H_i=\{\vb{h}_1,\dots,\vb{h}_B\} for every ii: each query sees 2B2B candidates and another query’s mined hard negative acts as an additional negative, with the same risk of being relevant. The contrastive loss is interpreted as classification: assign probability to the positive passage among candidates.

If PjP_j is softmax of temperature-scaled scores, differentiation with respect to an unscaled score gives (Pj−1)/τ(P_j-1)/\tau for the positive and Pj/τP_j/\tau for each negative. Descent raises positive score and lowers negatives, subject to encoder parameter sharing and normalization. A high-probability false negative receives an especially strong signal in the wrong direction. A small temperature concentrates probability on strongest competitors and multiplies derivatives by 1/τ1/\tau; training may become unstable or saturated, but collapse does not necessarily follow. Check gradient norm, loss, similarity distribution, and development results instead of diagnosing solely by temperature.

Compute with log-sum-exp: subtract the maximum logit before exponentiating and add it back to the logarithm. This preserves the result and avoids numerical overflow. Lower training loss does not guarantee better recall: it can reflect overfitting, easy examples, or learning generator shortcuts. If the encoder transforms queries and documents asymmetrically, retain suitable prefixes and instructions in training and inference. The original E5 work describes contrastive pretraining with weak supervision and evaluation on 56 BEIR and MTEB datasets; those results do not predict our fine-tuning effect.

What the information bound actually says

The connection to mutual information requires a precise sampling experiment. Write K=N+1K=N+1 for one positive and NN negatives. Let (X,Y)(X,Y) be drawn from the joint distribution and negatives independently from marginal PYP_Y, conditionally independent of XX and the positive. Choose a uniform position JJ for the positive among KK candidates. A classifier assigns probability q(J∣X,Y1:K)q(J\mid X,Y_{1:K}) and its loss LL is expected cross-entropy for that choice.

Some sources use NN for total candidate count and write log⁡N\log N. Here NN counts negatives only. The observed loss in one batch is not a guaranteed bound: LL is an expectation under specified sampling. The bound does not automatically identify mutual information with recall or answer quality.

Proof

Compare distribution PP of the experiment above with QQ, which chooses uniform JJ but draws every candidate independently from the marginal independently of XX. The likelihood ratio is dPdQ(j,x,y1:K)=p(yj∣x)p(yj)\frac{dP}{dQ}(j,x,y_{1:K})=\frac{p(y_j\mid x)}{p(y_j)}, because only the positive changes from marginal to conditional; its logarithm averaged under PP gives DKL(P∥Q)=I(X;Y)D_{\mathrm{KL}}(P\|Q)=I(X;Y). The chain rule decomposes that divergence into the divergence between laws of (X,Y1:K)(X,Y_{1:K}) under PP and QQ, which is nonnegative, plus the expectation under PP of DKL(P(J∣X,Y1:K) ∥ Q(J∣X,Y1:K))D_{\mathrm{KL}}\big(P(J\mid X,Y_{1:K})\,\|\,Q(J\mid X,Y_{1:K})\big). Under QQ, JJ is uniform and independent of everything else, so the second term is log⁡K−HP(J∣X,Y1:K)=IP(J;X,Y1:K)\log K-H_P(J\mid X,Y_{1:K})=I_P(J;X,Y_{1:K}). Thus I(X;Y)≥log⁡K−HP(J∣X,Y1:K)I(X;Y)\geq \log K-H_P(J\mid X,Y_{1:K}). Finally expected cross-entropy LL of any classifier is at least conditional entropy HP(J∣X,Y1:K)H_P(J\mid X,Y_{1:K}) (the difference is an expected KL divergence), yielding I(X;Y)≥log⁡K−LI(X;Y)\geq\log K-L.

∎

CPC introduces this family of contrastive objectives and the bound using NN for total candidates.

Hard mining selects negatives according to query and index; by construction they are not independent marginal samples. The classification function remains computable and may help, but the proof above no longer directly makes it a mutual-information bound. Filtering, duplicates, and example dependencies can also invalidate assumptions. Moreover, the bound is upper-limited by log⁡K\log K because loss is nonnegative: with few candidates it may be uninformative even if actual information is greater.

Train, save, and reindex

A verifiable implementation separates four states: initial encoder, training pairs and negatives, checkpoint selected using development, and corpus index rebuilt with that checkpoint. Save model and tokenizer versions, pooling and normalization configuration, splits, seeds, step count, hyperparameters, and each file’s fingerprints. Also record rejected examples and any candidate-list modification. Do not mix old and new embeddings within one index: their coordinates need not share geometry even with equal dimension. Reencode documents and jointly update index and metadata. A stale index can hide improvement or create misleading results.

For reproducible comparison, save a stable mapping from each vector to its chunk ID. Test some documents by reading content by ID after building the index: a row-order shift can return wrong text even when vector computations are correct. With an approximate index, compare its neighbors with exact search on a sample and separately measure approximation effects. Keep its parameters constant when comparing encoders or declare the change. Checkpoint, ID table, and index form a deployable version; if construction fails, do not publish a partial mix of versions.

An 8 GiB GPU’s memory is divided among weights, activations, gradients, optimizer states, batch, index, and other loads. Actual use depends on architecture, length, and precision: weight-file size is not peak training memory. As an order of magnitude, multilingual-e5-small has 117.7 million parameters, 96 million in its 250,037-piece vocabulary embedding table; in float32, weights, gradients, and two AdamW moments occupy about 4×4×117,7⋅106≈1,94\times 4\times 117{,}7\cdot10^6\approx 1{,}9 GB before activations, which grow with batch and length (up to 512 tokens). Start with reasonable batches and lengths and measure peak with torch.cuda.max_memory_allocated. Gradient accumulation reproduces a microbatch mean under certain conditions, but does not make examples in different microbatches negatives in the same softmax. Activation checkpointing and mixed precision alter memory-computation tradeoffs; record use and check numerical stability. Reducing batch to fit also changes in-batch negative count and the classification problem: declare it another configuration, not the same one with less memory.

Early stopping selects an epoch using a rule fixed on development; it must not consult test each epoch. With an efficient fine-tuning strategy, also retain adapters and configuration needed to reconstruct the complete encoder. First compare with the initial model under the same corpus, chunking, metric, and budget. Then change one thing at a time when attribution is the goal. If mining, encoder, and chunking change together, comparison measures the whole package, not each component’s isolated effect.

Lab: mine, fine-tune, and rebuild the index

By default the lab uses 505 SciFact train queries whose expert-annotated evidence matches BEIR positives. It splits them by connected components of the query–evidence-document graph: 403 training queries and 102 for internal development evaluation. The 76 evidence documents of that evaluation are used as neither training positives nor negatives. This ID split misses some versions or textual duplicates, and both subsets belong to SciFact train: it checks the procedure and chooses hyperparameters, not an independent test.

If environment variable P05_L02_RUN points to your frozen custom collection run folder (containing evaluacion-congelada.json), the same cell trains on your data. The mining index contains only structural chunks of the development split. Training pairs are candidates generated from those chunks that are not in frozen evaluation and were not rejected during review; unreviewed ones enter, bringing noise. Frozen development questions form internal evaluation: chunks overlapping their evidence are neither positives nor negatives. Test documents do not appear anywhere, as pairs, negatives, or in the mining index: this is the document separation required above. Internal evaluation instead splits by chunk, not document; it helps select hyperparameters and detect failures, not draw conclusions.

The whole index (5,183 SciFact documents) is encoded with pinned multilingual-e5-small revision and, for each training query, the first dense candidate not among known positives or reserved evidence documents is mined. An unannotated candidate can still be relevant. An extra known positive in a batch is masked for that query; four cases occur in SciFact. Custom loss is compared on CPU with sentence-transformers MultipleNegativesRankingLoss in an unmasked control; another test checks the masked version and gradients via log-sum-exp. Unmasked parity does not prove annotations complete.

With batch 4, one epoch, temperature 0.05, and AdamW at 2 × 10⁻⁵, SciFact tuning is 101 steps. The model is then saved and the whole corpus reencoded; mixing vectors from both versions invalidates comparison. This is the complete full-scale lab without shortcuts. In this lesson’s verification run, on an 8 GB RTX 4060 Laptop, this cell took about five minutes with 3.15 GiB peak CUDA memory, and macro recall@10 rose from 0.955065 to 0.968137 on 102 internal queries: four improved, two worsened, 96 unchanged. Paired difference was +0.013072, with percentile bootstrap interval from 3,000 query resamples [−0.019608; 0.049837]. It includes zero, so this comparison does not demonstrate improvement. That is unsurprising: the initial model already retrieves 95.5% of evidence, leaving little room, and 102 queries give low resolution. Queries sharing a source can be dependent; query resampling does not measure uncertainty among independent sources. Repetition should produce the same counts; small fourth-decimal differences may occur with another CUDA or library version.

The figure uses eight internal queries, one known positive and the negative mined before tuning for each. The two UMAP projections are fitted independently; cosines and ranks use original vectors over 5,183 documents with ties by ID. Notice what projection does not show: all cosines drop considerably after tuning (positives from about 0.87 to about 0.63), because temperature 0.05 rewards separating positive from competitors, not bringing it closer in absolute value. Ranking depends on positive-negative margin, which grows for all eight queries: for example from 0.016 to 0.295 for query 1073, whose negative falls from rank 2 to 55. The unannotated candidate may be a false negative.

You need Python with CUDA PyTorch, requests, numpy, sentence-transformers, transformers, huggingface_hub, umap-learn, and pynndescent, plus dependencies. The program downloads corpora (a few MB) and pinned model revision (about 470 MB) if missing from cache, checks data SHA-256 hashes, and writes everything to a new folder within p05-l08 in the directory specified by ATLAS_LAB_DIR (default ~/atlas-lab, the project convention): protocol with environment versions, training plan, tuned model in modelo-ajustado/, vectors, figure data, and results. The tuned model path printed at the end is used for confirmatory comparison and the agent. On GPU out of memory, reduce BATCH or MAX_TOKENS and record it as another configuration for reasons discussed above. Verification used Python 3.13, PyTorch 2.11 with CUDA 12.8, sentence-transformers 5.1.2, transformers 5.20.2, and umap-learn 0.5.9; with other versions the protocol records yours and last decimals can move. Before training, the cell compares its InfoNCE with sentence-transformers on a synthetic case with and without a mask and stops if losses or gradients differ.

[ ]Contrastive fine-tuning and reindexing on SciFactLocal GPU
"""Ajuste contrastivo del recuperador: SciFact train por defecto o tu colección de p05-l02.

Datos: sin variables, SciFact train (partición interna de desarrollo). Con
P05_L02_RUN=<ejecución congelada de p05-l02>, tus fragmentos de desarrollo y sus
candidatas; nunca lee las preguntas ni los documentos de prueba.
Salida: ATLAS_LAB_DIR/p05-l08 (por defecto ~/atlas-lab/p05-l08), una carpeta por ejecución.
"""
import csv
import gc
import hashlib
import importlib.metadata
import io
import json
import math
import os
import platform
import random
import tarfile
import tempfile
import zipfile
from collections import defaultdict
from pathlib import Path

import numpy as np
import requests

OWN=os.environ.get('P05_L02_RUN')
LAB=Path(os.environ.get('ATLAS_LAB_DIR',Path.home()/'atlas-lab')).expanduser()/'p05-l08'
LAB.mkdir(parents=True,exist_ok=True)
BEIR='https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/scifact.zip'
BEIR_SHA='536e14446a0ba56ed1398ab1055f39fe852686ecad24a6306c80c490fa8e0165'
ORIGINAL='https://scifact.s3-us-west-2.amazonaws.com/release/latest/data.tar.gz'
ORIGINAL_SHA='11c621288d41ac144d29b13b0f8503b3820b7d6e8b1f6ff24dff335c196d76be'
MODEL='intfloat/multilingual-e5-small';REV='614241f622f53c4eeff9890bdc4f31cfecc418b3'
SEED=20261028;BATCH=4;MAX_TOKENS=512;TAU=.05;LR=2e-5;EPOCHS=1
OUT=Path(tempfile.mkdtemp(prefix='ajuste-propio-' if OWN else 'ajuste-scifact-',dir=LAB))
print('Directorio:',OUT,flush=True)
def sha(b):return hashlib.sha256(b).hexdigest()
def canonical(x):return json.dumps(x,ensure_ascii=False,sort_keys=True,separators=(',',':'))
def save(name,data):
 path=OUT/name;path.write_text(json.dumps(data,ensure_ascii=False,indent=2)+'\n',encoding='utf-8',newline='\n');return sha(path.read_bytes())
def download(url,expected):
 r=requests.get(url,timeout=180);r.raise_for_status();data=r.content
 if sha(data)!=expected:raise ValueError('Huella inesperada: '+url)
 return data

def dataset():
 b=download(BEIR,BEIR_SHA);o=download(ORIGINAL,ORIGINAL_SHA)
 with tarfile.open(fileobj=io.BytesIO(o),mode='r:gz') as tar:
  match=[m for m in tar.getmembers() if m.name.endswith('/claims_train.jsonl')]
  if len(match)!=1:raise ValueError('claims train ambiguo')
  original=tar.extractfile(match[0]).read()
 claims={str(c['id']):c for c in (json.loads(line) for line in original.splitlines())}
 with zipfile.ZipFile(io.BytesIO(b)) as z:
  def read(name):
   m=[n for n in z.namelist() if n.endswith('/'+name) or n==name]
   if len(m)!=1:raise ValueError('miembro ausente o ambiguo: '+name)
   return z.read(m[0])
  corpus_b=read('corpus.jsonl');queries_b=read('queries.jsonl');qrels_b=read('qrels/train.tsv')
  corpus=[json.loads(x) for x in corpus_b.splitlines()]
  qrels=defaultdict(set)
  for row in csv.DictReader(io.StringIO(qrels_b.decode('utf-8')),delimiter='\t'):
   q,d=row['query-id'],row['corpus-id']
   if int(row['score'])>0 and claims[q].get('evidence',{}).get(d):qrels[q].add(d)
  queries={x['_id']:x['text'] for x in (json.loads(line) for line in queries_b.splitlines()) if x['_id'] in qrels}
 docs={x['_id']:x['title']+'\n'+x['text'] for x in corpus}
 assert set(queries)==set(qrels) and all(v and v<=set(docs) for v in qrels.values())
 hashes={'beir_sha256':sha(b),'original_sha256':sha(o),'corpus_sha256':sha(corpus_b),'queries_sha256':sha(queries_b),'qrels_train_sha256':sha(qrels_b),'claims_train_sha256':sha(original)}
 return docs,queries,qrels,hashes

def split(qrels):
 parent={}
 def root(x):
  parent.setdefault(x,x)
  while parent[x]!=x:parent[x]=parent[parent[x]];x=parent[x]
  return x
 def join(a,b):parent[root(a)]=root(b)
 for q,docs in qrels.items():
  for d in docs:join('q:'+q,'d:'+d)
 groups=defaultdict(list)
 for q in sorted(qrels):groups[root('q:'+q)].append(q)
 ordered=sorted(groups.values(),key=lambda x:tuple(x));random.Random(SEED).shuffle(ordered)
 target=round(len(qrels)*.2);held=[];train=[]
 for group in ordered:
  if len(held)<target:held.extend(group)
  else:train.extend(group)
 held=sorted(held);train=sorted(train)
 td=set().union(*(qrels[q] for q in train));hd=set().union(*(qrels[q] for q in held))
 assert not td&hd and set(train).isdisjoint(held) and len(train)+len(held)==len(qrels)
 return train,held,td,hd,sorted([len(g) for g in ordered],reverse=True)

def idkey(x):return (0,int(x),'') if x.isdigit() else (1,0,x)

def read_jsonl(path):
 with open(path,encoding='utf-8') as f:return [json.loads(line) for line in f if line.strip()]

def own_dataset(run):
 """Tu colección de p05-l02. Solo la partición de desarrollo: la prueba no se lee."""
 run=Path(run).expanduser().resolve();frozen_path=run/'evaluacion-congelada.json'
 if not frozen_path.is_file():raise FileNotFoundError('Congela antes la evaluación de p05-l02: falta '+str(frozen_path))
 frozen_bytes=frozen_path.read_bytes();frozen=json.loads(frozen_bytes)
 chunks=[c for c in read_jsonl(run/'chunks.jsonl') if c['strategy']=='estructura' and c['split']=='dev']
 docs={c['id']:c['text'] for c in chunks}
 def relevant(item):
  # Fragmentos estructurales del mismo documento que solapan la evidencia revisada.
  f=item['final'];d=item['candidate']['doc_id']
  return {c['id'] for c in chunks if c['doc_id']==d and c['start']<f['evidence_end'] and f['evidence_start']<c['end']}
 frozen_ids={item['candidate']['id'] for item in frozen['questions']}
 rejected={r['candidate_id'] for r in read_jsonl(run/'revisiones.jsonl') if r['decision']!='aceptada_manualmente'} if (run/'revisiones.jsonl').exists() else set()
 queries={};qrels={};held=[];train=[]
 for item in frozen['questions']:
  if item['candidate']['split']!='dev':continue
  qid='dev-'+item['candidate']['id'];queries[qid]=item['final']['question'];qrels[qid]=relevant(item);held.append(qid)
 hd=set().union(*(qrels[q] for q in held))
 for c in read_jsonl(run/'candidatos.jsonl'):
  if c['split']!='dev' or c['id'] in frozen_ids or c['id'] in rejected or c['chunk_id'] not in docs or c['chunk_id'] in hd:continue
  qid='train-'+c['id'];queries[qid]=c['question'];qrels[qid]={c['chunk_id']};train.append(qid)
 if not train or not held:raise ValueError('Hacen falta candidatas de entrenamiento y preguntas congeladas de desarrollo')
 td=set().union(*(qrels[q] for q in train))
 hashes={'run':str(run),'frozen_sha256':sha(frozen_bytes),'manifest_sha256':frozen['manifest_sha256'],'chunks_sha256':sha((run/'chunks.jsonl').read_bytes()),'candidates_sha256':sha((run/'candidatos.jsonl').read_bytes())}
 return docs,queries,qrels,hashes,sorted(train),sorted(held),td,hd

def own_infonce(q,p,n,tau,mask=None):
 import torch
 import torch.nn.functional as F
 q=F.normalize(q,dim=1);p=F.normalize(p,dim=1);n=F.normalize(n,dim=1)
 [email protected]((p,n),dim=0).T/tau
 if mask is not None:scores=scores.masked_fill(mask,-1e9)
 return F.cross_entropy(scores,torch.arange(len(q),device=q.device))

def verify_loss():
 import torch
 from sentence_transformers.losses import MultipleNegativesRankingLoss
 torch.manual_seed(SEED)
 v=[torch.randn(4,7,dtype=torch.float64,requires_grad=True) for _ in range(3)]
 x=own_infonce(*v,TAU);gx=torch.autograd.grad(x,v,retain_graph=True)
 reference=MultipleNegativesRankingLoss(torch.nn.Identity(),scale=1/TAU).compute_loss_from_embeddings(v,None)
 gr=torch.autograd.grad(reference,v)
 diff=abs((x-reference).item());grad=max((a-b).abs().max().item() for a,b in zip(gx,gr))
 assert diff<1e-10 and grad<1e-10
 mask=torch.zeros((4,8),dtype=torch.bool);mask[0,1]=True;mask[2,5]=True
 masked_loss=own_infonce(*v,TAU,mask)
 q=torch.nn.functional.normalize(v[0],dim=1)
 candidates=torch.nn.functional.normalize(torch.cat((v[1],v[2]),dim=0),dim=1)
 [email protected]/TAU
 manual=torch.stack([torch.logsumexp(logits[i][~mask[i]],dim=0)-logits[i,i] for i in range(4)]).mean()
 mg=torch.autograd.grad(masked_loss,v,retain_graph=True);expected=torch.autograd.grad(manual,v)
 masked_diff=abs((masked_loss-manual).item());masked_grad=max((a-b).abs().max().item() for a,b in zip(mg,expected))
 assert masked_diff<1e-10 and masked_grad<1e-10
 return {'loss_difference':diff,'gradient_max_difference':grad,'masked_loss_difference':masked_diff,'masked_gradient_max_difference':masked_grad,'case':'controles sintéticos sin máscara y con máscara'}

def encode(model,texts):
 vectors=model.encode(texts,batch_size=8,convert_to_numpy=True,normalize_embeddings=True,show_progress_bar=False)
 assert vectors.shape[0]==len(texts) and np.isfinite(vectors).all()
 return np.asarray(vectors,dtype=np.float32)

def train_epoch(plan,docs,queries,qrels):
 import torch
 import torch.nn.functional as F
 from sentence_transformers import SentenceTransformer
 torch.manual_seed(SEED);torch.cuda.manual_seed_all(SEED)
 model=SentenceTransformer(MODEL,revision=REV,device='cuda',local_files_only=True);model.max_seq_length=MAX_TOKENS
 model.train();opt=torch.optim.AdamW(model.parameters(),lr=LR);losses=[];masked=0
 order=list(plan);random.Random(SEED).shuffle(order)
 for offset in range(0,len(order),BATCH):
  batch=order[offset:offset+BATCH];qs=[x['q'] for x in batch];pos=[x['positive'] for x in batch];neg=[x['negative'] for x in batch]
  def represent(texts):
   features={k:v.to('cuda') for k,v in model.tokenize(texts).items()}
   return model(features)['sentence_embedding']
  opt.zero_grad(set_to_none=True)
  q=represent(['query: '+queries[x] for x in qs]);p=represent(['passage: '+docs[x] for x in pos]);n=represent(['passage: '+docs[x] for x in neg])
  mask=torch.zeros((len(qs),2*len(qs)),dtype=torch.bool,device='cuda')
  for i,qid in enumerate(qs):
   for j,did in enumerate(pos+neg):
    if did in qrels[qid] and j!=i:mask[i,j]=True;masked+=1
  loss=own_infonce(q,p,n,TAU,mask);loss.backward();opt.step();losses.append(loss.detach().item())
  if len(losses)%20==0:print('Ajuste pasos:',len(losses),'/',math.ceil(len(order)/BATCH),flush=True)
  del q,p,n,loss,mask
 # Formato sentence-transformers: la celda de prueba y el agente lo cargan con SentenceTransformer(ruta).
 path=OUT/'modelo-ajustado';model.save(str(path))
 del opt;gc.collect();torch.cuda.empty_cache()
 return model,losses,masked,sha((path/'model.safetensors').read_bytes())

def ranking(matrix,qvec,ids):
 # ids ya está ordenado (por número en SciFact): el empate se rompe por esa posición.
 scores=matrix@qvec;order=np.lexsort((np.arange(len(ids)),-scores));return scores,order

def metrics(matrix,vectors,qids,qrels,docids):
 rows=[]
 for qid,vec in zip(qids,vectors):
  scores,order=ranking(matrix,vec,docids);top=[docids[i] for i in order[:10]];truth=qrels[qid]
  rows.append({'query_id':qid,'recall10':len(set(top)&truth)/len(truth),'hit10':bool(set(top)&truth),'top10':top})
 return rows

def bootstrap(a,b,n=3000):
 rng=np.random.default_rng(SEED);delta=np.asarray(b)-np.asarray(a)
 samples=delta[rng.integers(0,len(delta),size=(n,len(delta)))].mean(axis=1)
 lo,hi=np.quantile(samples,[.025,.975]);return {'difference':float(delta.mean()),'low':float(lo),'high':float(hi),'resamples':n,'seed':SEED,'unit':'consulta'}

def main():
 import torch
 from sentence_transformers import SentenceTransformer
 from huggingface_hub import hf_hub_download,snapshot_download
 import umap
 torch.set_num_threads(1);assert torch.cuda.is_available(),'Se requiere CUDA'
 snapshot_download(MODEL,revision=REV,allow_patterns=['config.json','model.safetensors','modules.json','1_Pooling/config.json','sentence_bert_config.json','sentencepiece.bpe.model','special_tokens_map.json','tokenizer.json','tokenizer_config.json'])
 initial_file=hf_hub_download(MODEL,'model.safetensors',revision=REV,local_files_only=True)
 tokenizer_file=hf_hub_download(MODEL,'tokenizer.json',revision=REV,local_files_only=True)
 control=verify_loss();print('Control InfoNCE:',control,flush=True)
 if OWN:
  docs,queries,qrels,hashes,train,held,td,hd=own_dataset(OWN);groups=None
  source='Colección propia de p05-l02: fragmentos estructurales y candidatas de desarrollo; dev interno = preguntas congeladas de desarrollo'
 else:
  docs,queries,qrels,hashes=dataset();train,held,td,hd,groups=split(qrels)
  source='SciFact train, partición interna exploratoria por componentes de evidencia'
 docids=sorted(docs,key=idkey);allq=sorted(queries);pos_idx={k:i for i,k in enumerate(docids)};q_idx={k:i for i,k in enumerate(allq)}
 protocol={'data':source,'own_collection':bool(OWN), 'data_hashes':hashes,'n_documents':len(docs),'train_queries':train,'heldout_queries':held,'train_evidence_ids':sorted(td,key=idkey),'heldout_evidence_ids':sorted(hd,key=idkey),'components':groups,'seed':SEED,'batch':BATCH,'max_tokens':MAX_TOKENS,'tau':TAU,'lr':LR,'epochs':EPOCHS,'model':MODEL,'revision':REV,'initial_weights_sha256':sha(Path(initial_file).read_bytes()),'tokenizer_sha256':sha(Path(tokenizer_file).read_bytes()),'in_batch':'Enmascara todos los positivos conocidos salvo el positivo asignado','hard_negative':'Top denso original sin positivos conocidos ni documentos de evidencia de evaluación; no implica irrelevancia','disclaimer':'Dev interno para elegir y depurar; la prueba congelada se evalúa aparte.' if OWN else 'No es el conjunto propio revisado, ni prueba independiente; ambas particiones están dentro de SciFact train.'}
 protocol['environment']={'python':platform.python_version(),'packages':{name:importlib.metadata.version(name) for name in ('torch','numpy','requests','sentence-transformers','transformers','huggingface-hub','umap-learn','pynndescent')},'cuda_runtime':torch.version.cuda,'device':torch.cuda.get_device_name()}
 protocol_sha=save('protocolo.json',protocol)
 print('Protocolo',protocol_sha,'train',len(train),'dev interno',len(held),'doc dev excluidos de entrenamiento',len(hd),flush=True)
 model=SentenceTransformer(MODEL,revision=REV,device='cuda',local_files_only=True);model.max_seq_length=MAX_TOKENS
 model.eval();torch.cuda.reset_peak_memory_stats()
 print('Codificando corpus original',len(docids),flush=True)
 before_docs=encode(model,['passage: '+docs[x] for x in docids])
 before_q=encode(model,['query: '+queries[x] for x in allq])
 print('Índice original completo',flush=True)
 plan=[]
 for qid in train:
  scores,order=ranking(before_docs,before_q[q_idx[qid]],docids)
  negative=next(docids[i] for i in order if docids[i] not in qrels[qid] and docids[i] not in hd)
  plan.append({'q':qid,'positive':sorted(qrels[qid],key=idkey)[0],'negative':negative,'negative_score':float(scores[pos_idx[negative]])})
 assert all(x['positive'] not in hd and x['negative'] not in hd and x['negative'] not in qrels[x['q']] for x in plan)
 plan_sha=save('plan-entrenamiento.json',plan);print('Plan de entrenamiento fijado',plan_sha,flush=True)
 before_rows=metrics(before_docs,before_q[[q_idx[q] for q in held]],held,qrels,docids)
 del model;gc.collect();torch.cuda.empty_cache()
 model,losses,masked,model_sha=train_epoch(plan,docs,queries,qrels)
 print('Pico de memoria CUDA en el ajuste:',round(torch.cuda.max_memory_allocated()/2**30,2),'GiB',flush=True)
 model.eval();print('Recodificando todo el corpus con el modelo ajustado',flush=True)
 after_docs=encode(model,['passage: '+docs[x] for x in docids])
 after_q=encode(model,['query: '+queries[x] for x in allq])
 after_rows=metrics(after_docs,after_q[[q_idx[q] for q in held]],held,qrels,docids)
 del model;gc.collect();torch.cuda.empty_cache()
 vectors_path=OUT/'vectores.npz';np.savez_compressed(vectors_path,before_docs=before_docs,after_docs=after_docs,before_queries=before_q,after_queries=after_q)
 vector_sha=sha(vectors_path.read_bytes())
 examples=[];selected=held[:8];selected_docs=set()
 for q in selected:
  original,order=ranking(before_docs,before_q[q_idx[q]],docids)
  negative=next(docids[i] for i in order if docids[i] not in qrels[q]);positive=sorted(qrels[q],key=idkey)[0]
  selected_docs.update((positive,negative));examples.append({'query_id':q,'positive_id':positive,'negative_id':negative})
 selected_docs=sorted(selected_docs,key=idkey);points=[('q',q) for q in selected]+[('d',d) for d in selected_docs]
 def projected(qv,dv):
  x=np.stack([qv[q_idx[id]] if kind=='q' else dv[pos_idx[id]] for kind,id in points])
  result=umap.UMAP(n_neighbors=min(10,len(points)-1),n_components=2,min_dist=.1,metric='cosine',random_state=SEED,n_jobs=1).fit_transform(x)
  return {(kind,id):[float(t) for t in pair] for (kind,id),pair in zip(points,result)}
 projected_before=projected(before_q,before_docs);projected_after=projected(after_q,after_docs)
 for e in examples:
  q=e['query_id'];e['before']={};e['after']={}
  for label,qv,dv,proj in [('before',before_q,before_docs,projected_before),('after',after_q,after_docs,projected_after)]:
   scores,order=ranking(dv,qv[q_idx[q]],docids);ranks=np.empty(len(order),dtype=int);ranks[order]=np.arange(1,len(order)+1)
   e[label]={'query_xy':proj[('q',q)],'positive_xy':proj[('d',e['positive_id'])],'negative_xy':proj[('d',e['negative_id'])],
             'positive_cosine':float(scores[pos_idx[e['positive_id']]]),'negative_cosine':float(scores[pos_idx[e['negative_id']]]),
             'positive_rank':int(ranks[pos_idx[e['positive_id']]]),'negative_rank':int(ranks[pos_idx[e['negative_id']]])}
 widget={'dataset':source,'split':'dev interno','selection':'primeras ocho consultas por ID ordenado','negative':'primero del ranking original que no sea positivo conocido; puede ser relevante sin anotar','rank':'1-indexado, coseno descendente y empate por ID','projection':{'library':'umap-learn','version':importlib.metadata.version('umap-learn'),'metric':'cosine','n_neighbors':10,'min_dist':.1,'seed':SEED,'before_after':'proyecciones independientes, coordenadas no comparables directamente'},'protocol_sha256':protocol_sha,'vectors_sha256':vector_sha,'examples':examples}
 widget_sha=save('widget-data.json',widget)
 before=[r['recall10'] for r in before_rows];after=[r['recall10'] for r in after_rows];diff=bootstrap(before,after)
 result={'protocol_sha256':protocol_sha,'plan_sha256':plan_sha,'model_dir':str(OUT/'modelo-ajustado'),'model_weights_sha256':model_sha,'vectors_sha256':vector_sha,'widget_sha256':widget_sha,'n_train':len(train),'n_held':len(held),'excluded_held_docs':len(hd),'loss_control':control,'train_losses':losses,'masked_known_positives':masked,'recall10_before':float(np.mean(before)),'recall10_after':float(np.mean(after)),'paired_bootstrap':diff,'rows_before':before_rows,'rows_after':after_rows}
 save('resultados.json',result);print('RESULTADOS',json.dumps({k:v for k,v in result.items() if k not in ('rows_before','rows_after','train_losses')},ensure_ascii=False),flush=True)
 print('Modelo ajustado (P05_L08_MODELO para la celda siguiente):',OUT/'modelo-ajustado',flush=True)

if __name__=='__main__':main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Rewriting a question does not create a source

In HyDE, the model generates text resembling a relevant answer and an encoder turns it into a vector to retrieve real documents. The text is a tool for locating neighbors, not evidence: it may contain false details. The dense bottleneck does not guarantee their removal. Do not add the hypothesis to the corpus as a source or cite it in an answer. Compare original, hypothetical, and explicit combined queries under equal or documented generation and retrieval budgets. Choose the variant on development. A hypothesis with an invented identifier can guide search into the wrong neighborhood; retaining the literal query may help exact identifiers.

A hypothetical query run on CPU

This cell reproduces HyDE in a small external exploratory control. It selects the first ten bridge questions by ID from HotpotQA distractor/validation, with ten unique candidate titles and two annotated supports. Qwen2.5-0.5B-Instruct generates one hypothetical passage per question on CPU with greedy decoding and at most 48 new tokens. That text is not a corpus document or source: it only forms the dense query. multilingual-e5-small receives the literal question with query: prefix and both hypothesis and ten documents with passage: prefix. It compares two cosine rankings over the same ten candidates; ties use title then original position.

The program needs Python with torch, transformers, numpy, pandas, and pyarrow, data download access, and pinned revisions of both models if not cached. It uses only CPU and two PyTorch threads. It downloads the HotpotQA split once (about 27 MB) to the lab’s p05-l08 folder, verifies SHA-256, and saves hypotheses, rankings, and summary in a new subfolder whose path is printed. Questions and supports come from the same external split as the next lab; the criterion is macro recall@2 against its two known support titles and does not measure answer correctness.

In the recorded run literal query obtained macro recall@2 0.60 and HyDE 0.55; both titles appeared in the top two in 3/10 cases for each method. Nine paired recall differences were zero and one was −0.5. The generator produced 332 tokens total: three outputs reached the allowed 48 tokens and none were empty. These counts describe that run’s outputs and are not universal time or cost. The sample is too small to conclude which method is better; generating hypotheses adds work and can introduce false premises. Ten candidates are already provided, and title retrieval is neither agent success nor custom-corpus evaluation.

[ ]HyDE with generation and retrieval on CPULocal GPU
import hashlib
import json
import os
from pathlib import Path
import tempfile
import urllib.request

import numpy as np
import pandas as pd
import torch
import torch.nn.functional as F
from transformers import AutoModel, AutoModelForCausalLM, AutoTokenizer

URL = 'https://huggingface.co/datasets/hotpotqa/hotpot_qa/resolve/14f0ace3c3fac7bd86149c616b5b05d8282e5c6a/distractor/validation/0000.parquet'
SHA256 = 'c20b638ca82b21d04fe12e14ff417ad05153d4d215a65de54497fca4e972f7c6'
GEN = 'Qwen/Qwen2.5-0.5B-Instruct'
GEN_REV = '7ae557604adf67be50417f59c2c2f167def9a775'
ENC = 'intfloat/multilingual-e5-small'
ENC_REV = '614241f622f53c4eeff9890bdc4f31cfecc418b3'
LAB = Path(os.environ.get('ATLAS_LAB_DIR', Path.home() / 'atlas-lab')).expanduser() / 'p05-l08'
LAB.mkdir(parents=True, exist_ok=True)
OUT = Path(tempfile.mkdtemp(prefix='hyde-', dir=LAB))
print('Directorio:', OUT, flush=True)
# El parquet (unos 27 MB) se descarga una vez y lo comparte la celda multi-salto.
file = LAB / 'hotpotqa-distractor-validation.parquet'
if not file.exists() or hashlib.sha256(file.read_bytes()).hexdigest() != SHA256:
    with urllib.request.urlopen(URL, timeout=120) as source, file.open('wb') as target:
        while block := source.read(1 << 20):
            target.write(block)
if hashlib.sha256(file.read_bytes()).hexdigest() != SHA256:
    raise ValueError('La huella de HotpotQA no coincide')

records = []
for row in pd.read_parquet(file).to_dict(orient='records'):
    docs = [(str(t), list(s)) for t, s in zip(row['context']['title'], row['context']['sentences'])]
    gold = sorted(set(str(t) for t in row['supporting_facts']['title']))
    if row['type'] == 'bridge' and len(gold) == 2 and len(docs) == 10 and len({d[0] for d in docs}) == 10 and all(g in {d[0] for d in docs} for g in gold):
        records.append((str(row['id']), str(row['question']), docs, gold))
records.sort(key=lambda x: x[0])
records = records[:10]
if len(records) != 10:
    raise ValueError('Faltan casos para la muestra prefijada')

torch.set_num_threads(2)
gen_tokenizer = AutoTokenizer.from_pretrained(GEN, revision=GEN_REV)
generator = AutoModelForCausalLM.from_pretrained(GEN, revision=GEN_REV, torch_dtype=torch.float32).to('cpu').eval()
assert next(generator.parameters()).device.type == 'cpu'
hypotheses = []
with torch.inference_mode():
    for i, (item_id, question, _, _) in enumerate(records):
        messages = [
            {'role': 'system', 'content': 'Write one short hypothetical encyclopedia passage that could help answer the question. It may be speculative. Do not state that the passage is a verified source.'},
            {'role': 'user', 'content': question},
        ]
        prompt = gen_tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
        encoded = gen_tokenizer(prompt, return_tensors='pt')
        ids = generator.generate(**encoded, do_sample=False, max_new_tokens=48, pad_token_id=gen_tokenizer.eos_token_id)
        new_tokens = ids[0, encoded['input_ids'].shape[1]:]
        text = gen_tokenizer.decode(new_tokens, skip_special_tokens=True).strip()
        hypotheses.append({'id': item_id, 'hypothesis': text, 'output_tokens': len(new_tokens), 'length_limit_reached': len(new_tokens) == 48})
        print('Hipótesis', i + 1, '/', len(records), flush=True)
del generator

enc_tokenizer = AutoTokenizer.from_pretrained(ENC, revision=ENC_REV)
encoder = AutoModel.from_pretrained(ENC, revision=ENC_REV).to('cpu').eval()
assert next(encoder.parameters()).device.type == 'cpu'
def embed(texts):
    arrays = []
    with torch.inference_mode():
        for i in range(0, len(texts), 8):
            batch = enc_tokenizer(texts[i:i+8], max_length=512, truncation=True, padding=True, return_tensors='pt')
            state = encoder(**batch).last_hidden_state
            mask = batch['attention_mask'].unsqueeze(-1)
            pooled = (state * mask).sum(dim=1) / mask.sum(dim=1).clamp(min=1)
            arrays.append(F.normalize(pooled, p=2, dim=1).cpu().numpy())
    return np.concatenate(arrays, axis=0)

results = []
for (item_id, question, docs, gold), hypothesis in zip(records, hypotheses):
    # Mismo encoder de documentos: prefijo passage para documentos e hipótesis.
    vectors = embed(['query: ' + question, 'passage: ' + hypothesis['hypothesis']] + ['passage: ' + title + '\n' + ' '.join(sentences) for title, sentences in docs])
    matrix = vectors[2:]
    literal_scores, hyde_scores = matrix @ vectors[0], matrix @ vectors[1]
    def top2(scores):
        order = sorted(range(len(docs)), key=lambda i: (-float(scores[i]), docs[i][0].casefold(), i))
        return [docs[i][0] for i in order[:2]]
    literal, hyde = top2(literal_scores), top2(hyde_scores)
    def recall(titles):
        return len(set(titles) & set(gold)) / len(gold)
    results.append({'id': item_id, 'question': question, 'gold': gold, **hypothesis,
                    'literal_top2': literal, 'hyde_top2': hyde,
                    'literal_recall2': recall(literal), 'hyde_recall2': recall(hyde),
                    'literal_both': set(gold).issubset(literal), 'hyde_both': set(gold).issubset(hyde)})
summary = {'dataset_url': URL, 'dataset_sha256': SHA256, 'partition': 'distractor/validation',
           'selection': 'primeros 10 IDs bridge ordenados con 10 títulos únicos y 2 soportes',
           'generator': GEN, 'generator_revision': GEN_REV, 'encoder': ENC, 'encoder_revision': ENC_REV,
           'device': 'cpu', 'decoding': 'greedy, 48 tokens nuevos máximo', 'n': len(results),
           'literal_recall2_macro': sum(r['literal_recall2'] for r in results) / len(results),
           'hyde_recall2_macro': sum(r['hyde_recall2'] for r in results) / len(results),
           'literal_both': sum(r['literal_both'] for r in results), 'hyde_both': sum(r['hyde_both'] for r in results),
           'output_tokens_total': sum(r['output_tokens'] for r in results),
           'hipotesis_vacias': sum(not r['hypothesis'] for r in results),
           'parejas_sin_cambio': sum(r['hyde_recall2'] == r['literal_recall2'] for r in results),
           'parejas_cambio_menos_05': sum(r['hyde_recall2'] - r['literal_recall2'] == -.5 for r in results),
           'length_limit_reached': sum(r['length_limit_reached'] for r in results),
           'limits': 'Solo diez candidatos dados por pregunta; la hipótesis es una consulta no evidencial y los soportes no prueban respuesta correcta.'}
(OUT / 'trazas.json').write_text(json.dumps(results, ensure_ascii=False, indent=2), encoding='utf-8')
(OUT / 'resumen.json').write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps(summary, ensure_ascii=False, indent=2), flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Consider a question comparing a figure from two papers: retrieving paper A first and then searching B may help if the first identifies B. If both titles already occur in the question, two independent parallel queries may be simpler and avoid contaminating the second hop with first-hop error. Least-to-most decomposition helps when an intermediate answer is necessary to formulate or solve the next stage, not merely because a question is long. For each hop retain subquery, evidence, ID, decision, and budget. The final answer must support each claim with corresponding sources.

An agent may explore several chains, but a wider step-level beam multiplies calls, candidates, and opportunities for error. Limit depth, branches, and tokens; define what happens when evidence is missing or results conflict. A wrong intermediate answer can cause a coherent but wrong subsequent query. Separately evaluate first-hop retrieval, conditional second-hop retrieval, and whole-chain success. To measure the second hop without confounding the first, a control can receive the correct intermediate entity; declare this privileged information, not equivalent to a complete agent.

An external two-hop control

The next cell runs a CPU lexical comparison on HotpotQA distractor/validation, distributed under CC BY-SA 4.0. It downloads a revision-pinned version, checks SHA-256, and selects the first 100 sorted bridge-type IDs with ten different titles and exactly two annotated support titles. This is exploratory external development analysis, not your frozen test. It needs pandas and pyarrow; it reuses the previous cell’s parquet (or downloads it if absent) and saves traces and summary in a new p05-l08 subfolder whose path it prints.

The three policies share the first BM25 result over the ten documents supplied with each question. A one-step search returns its first two documents. The two-step policy searches for a candidate title mentioned literally in the first document: it uses the longest mention with deterministic tie-breaking for the second search. Without a mention of at least two words, it reuses the original question excluding the first document. The privileged control queries the annotated support title different from the first: it deliberately uses reference labels and is therefore not a deployable agent. If the first document is wrong, no method retaining it can retrieve both supports in two documents.

The indicator is finding both support titles, not answering correctly or proving that a detected mention is the relevant bridge entity. Only ten HotpotQA candidates per question are searched, not all Wikipedia. The cell retains cases with no mention without changing the denominator. This is a document retrieval control, not complete multi-hop question success.

In one run with the stated fingerprint, one step retrieved both titles in 31/100 questions, two steps in 44/100, and privileged control in 74/100. Literal mention was found in 50/100. In 16 tasks two steps succeeded where one failed, and in 3 the reverse occurred. Paired difference was +0.13, with percentile bootstrap interval from 2,000 resamples [0.05; 0.21], seed 20261028. The sample is a small fixed development selection, the label does not guarantee a correct final answer, and policies change the query; the interval does not validate a general improvement or replace evaluating your own agent.

[ ]Iterative retrieval on HotpotQA, CPULocal GPU
import hashlib
import json
import math
import os
from pathlib import Path
import random
import re
import tempfile
import urllib.request
from collections import Counter

import pandas as pd

URL = 'https://huggingface.co/datasets/hotpotqa/hotpot_qa/resolve/14f0ace3c3fac7bd86149c616b5b05d8282e5c6a/distractor/validation/0000.parquet'
SHA256 = 'c20b638ca82b21d04fe12e14ff417ad05153d4d215a65de54497fca4e972f7c6'
LAB = Path(os.environ.get('ATLAS_LAB_DIR', Path.home() / 'atlas-lab')).expanduser() / 'p05-l08'
LAB.mkdir(parents=True, exist_ok=True)
OUTPUT = Path(tempfile.mkdtemp(prefix='multisalto-', dir=LAB))
dataset = LAB / 'hotpotqa-distractor-validation.parquet'
if not dataset.exists() or hashlib.sha256(dataset.read_bytes()).hexdigest() != SHA256:
    with urllib.request.urlopen(URL, timeout=120) as source, dataset.open('wb') as sink:
        while block := source.read(1 << 20):
            sink.write(block)
digest = hashlib.sha256(dataset.read_bytes()).hexdigest()
if digest != SHA256:
    raise ValueError('La huella del dataset no coincide: ' + digest)

# BM25 estándar con IDF positiva. Empates por título y después posición original.
def tokens(s):
    return re.findall(r'[^\W_]+', s.casefold(), flags=re.UNICODE)

def rank(query, docs, exclude=()):
    rows = [tokens(title + ' ' + ' '.join(sentences)) for title, sentences in docs]
    freq = [Counter(row) for row in rows]
    lengths = [len(row) for row in rows]
    avg = sum(lengths) / len(lengths)
    scores = []
    for idx, (title, _) in enumerate(docs):
        score = 0.0
        for word in tokens(query):
            df = sum(word in f for f in freq)
            idf = math.log(1 + (len(docs) - df + .5) / (df + .5))
            f = freq[idx][word]
            score += idf * f * 2.2 / (f + 1.2 * (1 - .75 + .75 * lengths[idx] / avg))
        if idx not in exclude:
            scores.append((idx, score))
    return [idx for idx, _ in sorted(scores, key=lambda pair: (-pair[1], docs[pair[0]][0].casefold(), pair[0]))]

def mentioned_title(docs, first):
    # La entidad candidata es un título de los diez que aparece literalmente
    # en el texto recuperado. No se consultan las anotaciones de soporte.
    text = ' '.join(docs[first][1]).casefold()
    options = []
    for i, (title, _) in enumerate(docs):
        name = title.casefold()
        if i != first and len(tokens(name)) >= 2 and re.search(r'(?<!\w)' + re.escape(name) + r'(?!\w)', text):
            options.append((i, title))
    if not options:
        return None
    # Elección determinista de la mención más larga, con desempate por título.
    return sorted(options, key=lambda item: (-len(item[1]), item[1].casefold(), item[0]))[0][1]

frame = pd.read_parquet(dataset)
records = []
for row in frame.to_dict(orient='records'):
    docs = [(str(title), list(sentences)) for title, sentences in zip(row['context']['title'], row['context']['sentences'])]
    gold = sorted(set(str(x) for x in row['supporting_facts']['title']))
    if row['type'] == 'bridge' and len(gold) == 2 and len(docs) == 10 and len({d[0] for d in docs}) == 10 and all(g in {d[0] for d in docs} for g in gold):
        records.append((str(row['id']), str(row['question']), docs, gold))
records.sort(key=lambda x: x[0])
records = records[:100]
if len(records) != 100:
    raise ValueError('Se esperaban 100 casos bridge elegibles')

out = []
for item_id, question, docs, gold in records:
    initial = rank(question, docs)
    first = initial[0]
    bridge = mentioned_title(docs, first)
    # Sin mención utilizable, repetir la consulta original excluyendo el primero.
    follow = rank(bridge if bridge is not None else question, docs, exclude={first})[0]
    # El control lee etiquetas humanas: título de soporte aún no recuperado.
    remaining_gold = [title for title in gold if title != docs[first][0]]
    oracle_title = remaining_gold[0]
    oracle = rank(oracle_title, docs, exclude={first})[0]
    single_titles = [docs[index][0] for index in initial[:2]]
    two_titles = [docs[first][0], docs[follow][0]]
    oracle_titles = [docs[first][0], docs[oracle][0]]
    success = lambda found: set(gold).issubset(set(found))
    out.append({'id': item_id, 'gold_titles': gold, 'single': single_titles,
                'first': docs[first][0], 'bridge': bridge, 'two_step': two_titles,
                'oracle_query': oracle_title, 'oracle': oracle_titles,
                'single_success': success(single_titles), 'two_success': success(two_titles),
                'oracle_success': success(oracle_titles)})

single = sum(r['single_success'] for r in out)
two = sum(r['two_success'] for r in out)
oracle = sum(r['oracle_success'] for r in out)
different = sum(r['single_success'] != r['two_success'] for r in out)
rng = random.Random(20261028)
delta = [(int(r['two_success']) - int(r['single_success'])) for r in out]
bootstrap = sorted(sum(rng.choice(delta) for _ in out) / len(out) for _ in range(2000))
summary = {'fuente': URL, 'sha256': digest, 'split': 'distractor/validation',
           'seleccion': 'primeros 100 IDs ordenados de bridge con 10 títulos únicos y 2 soportes',
           'n': len(out), 'un_paso_ambos_soportes': single, 'dos_pasos_ambos_soportes': two,
           'control_oraculo_ambos_soportes': oracle,
           'mencion_encontrada': sum(r['bridge'] is not None for r in out),
           'diferencias_pareadas': different,
           'mejoran': sum(r['two_success'] and not r['single_success'] for r in out),
           'empeoran': sum(r['single_success'] and not r['two_success'] for r in out),
           'delta_dos_menos_uno': (two-single)/len(out),
           'bootstrap_percentil_2000_95': [bootstrap[49], bootstrap[1949]],
           'limites': 'Diez candidatos por pregunta; recuperación de títulos, no respuesta ni juicio semántico. Oráculo usa soporte anotado.'}
(OUTPUT / 'trazas.json').write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding='utf-8')
(OUTPUT / 'resumen.json').write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps(summary, ensure_ascii=False, indent=2))
print('Carpeta de salida:', OUTPUT)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Measure change on the same tasks

For query ii, let RiR_i be known relevant documents and Ti(10)T_i^{(10)} the ten retrieved. If RiR_i is nonempty, per-query recall is ∣Ri∩Ti(10)∣/∣Ri∣|R_i\cap T_i^{(10)}|/|R_i|; its query mean is macro recall@10. With exactly one annotated relevant item it equals the fraction of queries whose relevant item appears in ten results. With several relevant items it generally differs from that hit rate. Fix relevance unit and ranking: document or chunk, grouping chunks of the same document, and handling ties or fewer than ten results. Do not remove failed queries from the denominator for convenience.

With incomplete relevance, a useful unlabeled document may count as error; an incorrect judgment may count as success. Calculated recall is relative to available judgments. For every query evaluate initial and tuned retrievers against the same collection and criterion, obtaining aia_i and bib_i. Difference is Δ^=1m∑i(bi−ai)\widehat\Delta=\frac1m\sum_i(b_i-a_i). Paired bootstrap resamples query indices with replacement, preserving each (ai,bi)(a_i,b_i) pair; difference percentiles form an interval for that procedure. If multiple queries depend on one source and the goal is generalization to sources, resample source groups and declare estimand and weighting. A small set or selected sample can produce unreliable intervals.

Agent evaluation needs a second estimand: complete success per multi-hop task with answer and evidence criteria fixed before comparison. Retrieving one more passage in ten does not imply the agent reads it, uses it correctly, or finishes within budget. Evaluate both configurations on the same tasks with the same policy except the studied change; retain timeouts, invalid outputs, and costs. With repetitions average within task before resampling tasks, or define another estimand beforehand. Between-task uncertainty and between-run variability are not interchangeable.

An interval excluding zero for recall provides evidence compatible with a difference under that protocol, not universal improvement or guaranteed practical relevance. Trying many temperatures and rewrites and choosing the best test result introduces selection. Keep test closed during development and record confirmatory comparisons. If systems generate different subqueries, a difference may result from query as well as retriever: an additional fixed-query evaluation can isolate the index component. A negative or inconclusive exploratory result remains useful if reported with denominators and limitations.

Lab: confirmatory comparison on your frozen test

This cell decides the lesson’s first result and runs once, with procedure already fixed on development. It needs two environment variables: P05_L02_RUN, the same frozen custom collection run used for tuning, and P05_L08_MODELO, the modelo-ajustado folder printed by the tuning lab. Before calculating, it checks that model was trained with this frozen evaluation (comparing the fingerprint in its protocol) and refuses to write a second report if one already exists: repeating test until favorable turns it into development. Without the variables it only prints what is missing.

The index is deployable: all structural chunks, development and test, encoded separately with each model. A test question’s relevance consists of chunks from its document overlapping reviewed evidence. The cell computes recall@10 per question with baseline encoder (aia_i) and tuned encoder (bib_i), and two 95% percentile bootstrap intervals for Δ^\widehat\Delta with 10,000 resamples: one by question and another by document, resampling test documents with all their questions and estimating the same per-question mean. With few test documents (p05-l02 reserves one in five), the document interval will be wide; it is the honest one for generalizing to new documents, and the result criterion must be declared before running. It runs on GPU if available, otherwise CPU; with a few thousand chunks it takes minutes.

[ ]Baseline versus fine-tuned on the frozen testLocal GPU
"""Comparación confirmatoria en la prueba congelada de p05-l02 (una sola vez)."""
import hashlib
import json
import os
from pathlib import Path

import numpy as np

MODEL = 'intfloat/multilingual-e5-small'
REV = '614241f622f53c4eeff9890bdc4f31cfecc418b3'
SEED = 20261028
RESAMPLES = 10_000


def sha(data):
    return hashlib.sha256(data).hexdigest()


def read_jsonl(path):
    with open(path, encoding='utf-8') as f:
        return [json.loads(line) for line in f if line.strip()]


def percentile_interval(samples):
    low, high = np.quantile(samples, [.025, .975])
    return [float(low), float(high)]


def compare(run, tuned):
    import torch
    from sentence_transformers import SentenceTransformer
    run, tuned = Path(run).expanduser().resolve(), Path(tuned).expanduser().resolve()
    report = tuned.parent / 'prueba-congelada.json'
    if report.exists():
        raise FileExistsError(f'Ya evaluaste este modelo en prueba: {report}')
    frozen_bytes = (run / 'evaluacion-congelada.json').read_bytes()
    frozen = json.loads(frozen_bytes)
    protocol = json.loads((tuned.parent / 'protocolo.json').read_text(encoding='utf-8'))
    if not protocol.get('own_collection') or protocol['data_hashes']['frozen_sha256'] != sha(frozen_bytes):
        raise ValueError('Ese modelo no se ajustó con esta evaluación congelada')
    chunks = [c for c in read_jsonl(run / 'chunks.jsonl') if c['strategy'] == 'estructura']
    ids = sorted(c['id'] for c in chunks)
    text = {c['id']: c['text'] for c in chunks}
    tests = [q for q in frozen['questions'] if q['candidate']['split'] == 'test']
    if not tests:
        raise ValueError('La evaluación congelada no tiene preguntas de prueba')

    def relevant(item):
        f, doc = item['final'], item['candidate']['doc_id']
        return {c['id'] for c in chunks if c['doc_id'] == doc
                and c['start'] < f['evidence_end'] and f['evidence_start'] < c['end']}

    truth = [relevant(q) for q in tests]
    assert all(truth), 'Toda pregunta revisada debe tener algún fragmento relevante'
    device = 'cuda' if torch.cuda.is_available() else 'cpu'

    def recall10(model):
        model.max_seq_length = 512
        D = model.encode(['passage: ' + text[i] for i in ids], batch_size=16,
                         normalize_embeddings=True, convert_to_numpy=True)
        Q = model.encode(['query: ' + q['final']['question'] for q in tests], batch_size=16,
                         normalize_embeddings=True, convert_to_numpy=True)
        values = []
        for scores, rel in zip(Q @ D.T, truth):
            top = np.lexsort((np.arange(len(ids)), -scores))[:10]  # empate: orden de ID
            values.append(len({ids[j] for j in top} & rel) / len(rel))
        return np.asarray(values)

    a = recall10(SentenceTransformer(MODEL, revision=REV, device=device))
    b = recall10(SentenceTransformer(str(tuned), device=device))
    delta = b - a
    rng = np.random.default_rng(SEED)
    by_question = delta[rng.integers(0, len(delta), size=(RESAMPLES, len(delta)))].mean(axis=1)
    docs = sorted({q['candidate']['doc_id'] for q in tests})
    position = {d: k for k, d in enumerate(docs)}
    group = np.asarray([position[q['candidate']['doc_id']] for q in tests])
    sums, counts = np.bincount(group, weights=delta), np.bincount(group)
    draw = rng.integers(0, len(docs), size=(RESAMPLES, len(docs)))
    by_document = sums[draw].sum(axis=1) / counts[draw].sum(axis=1)
    result = {'run': str(run), 'frozen_sha256': sha(frozen_bytes), 'model_dir': str(tuned),
              'n_questions': len(tests), 'n_documents': len(docs), 'n_chunks_index': len(ids),
              'recall10_base': float(a.mean()), 'recall10_tuned': float(b.mean()),
              'difference': float(delta.mean()), 'improve': int((delta > 0).sum()),
              'worsen': int((delta < 0).sum()), 'unchanged': int((delta == 0).sum()),
              'ci95_by_question': percentile_interval(by_question),
              'ci95_by_document': percentile_interval(by_document),
              'resamples': RESAMPLES, 'seed': SEED,
              'rows': [{'question_id': q['candidate']['id'], 'doc_id': q['candidate']['doc_id'],
                        'recall10_base': float(x), 'recall10_tuned': float(y)}
                       for q, x, y in zip(tests, a, b)]}
    with report.open('x', encoding='utf-8') as f:
        json.dump(result, f, ensure_ascii=False, indent=2)
    print(json.dumps({k: v for k, v in result.items() if k != 'rows'}, ensure_ascii=False, indent=2))
    for name in ('ci95_by_question', 'ci95_by_document'):
        low, high = result[name]
        verdict = 'excluye el cero' if low > 0 or high < 0 else 'incluye el cero'
        print(f'{name}: [{low:+.4f}; {high:+.4f}] {verdict}')
    print('Informe:', report)


RUN, TUNED = os.environ.get('P05_L02_RUN'), os.environ.get('P05_L08_MODELO')
if RUN and TUNED:
    compare(RUN, TUNED)
else:
    print('Define P05_L02_RUN (tu ejecución congelada de p05-l02) y P05_L08_MODELO '
          '(la carpeta modelo-ajustado del ajuste con esa misma ejecución).')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The second estimand, agent success on your multi-hop tasks, is measured with the agent-loop lesson and agent evaluation protocol: same tasks, seeds, and policy, changing only the encoder. SentenceTransformer accepts the local modelo-ajustado path instead of a repository name, so replace the dense retriever’s model-and-revision pair with that folder and rebuild the index. Average repetitions within each task and resample tasks as there. Better recall without better success is possible and informative: it indicates the bottleneck is reading, synthesis, or budget rather than retrieval.

Exercises

CodeA query against its candidates
Implement info_nce(q, p, negatives, tau) with NumPy. q and p are vectors of dimension d; negatives has shape (N,d) and combines other batch queries’ positives and hard negatives. Use dot product without implicit normalization and positive tau. Return loss, gradient with respect to q, gradient with respect to p, and gradient matrix of negatives. Evaluate log-sum-exp stably. Tests compare finite differences and check a large-logit case.
import numpy as np

def info_nce(q, p, negatives, tau):
  pass
Shift+Enter to run
ProofFrom classification to mutual information
Prove: Prove the InfoNCE bound for one joint positive and N independent marginal negatives, with K=N+1 candidates.
0
J is the uniform positive position; Q uses the marginal for all candidates. L is expected cross-entropy of any classifier of J.

Step 1 of 3. What is the divergence between the positive experiment and Q?

QuizA second valid passage
The index returns an unlabeled passage that correctly answers a query. It is added as a hard negative and scores highly. What immediate effect does its loss term have?
QuizIs another hop needed?
A question requires finding an entity's successor institution; its current name appears only in a document that must first be retrieved. Which strategy is best justified?
Key idea

Fine-tuning changes a learned geometry, but verifiable improvement requires controlled sources and splits, audited negatives, reindexing, and a paired comparison measuring both retrieval and complete success. HyDE and hops guide search; only retrieved and verified sources support the answer.