Module contents
Lesson 22 of 31Core 115 min

Retrieval-augmented generation end to end

Develop retrieval-augmented generation from probabilistic document marginalization through chunking, hybrid retrieval, reranking, query transformation, citation checks and context-position effects, with a measured local pipeline.

After this lesson you can

  • Write RAG-sequence and RAG-token distributions and derive the retriever gradient.
  • Build RAG without frameworks: chunking, hybrid index, reranking, numbered sources and cited answers.
  • Compare chunking and contextual enrichment with measured ablations.
  • Apply query rewriting, HyDE and multiple queries and measure when they help.
  • Reproduce small-scale evidence-position and distractor effects.

Before you start

Retrievable knowledge

A retrieval-augmented generation system queries a corpus and supplies passages to the generator for an answer. Updating the index can change available information without retraining the model; a citation allows source inspection. None of these properties is automatic: permissions, updates, retrieval quality and citation verification remain system decisions. Fine-tuning and RAG can also be combined, for example to adapt answer format and retrieve changing facts.

A latent document

In the probabilistic RAG formulation, retriever pη(z∣x)p_\eta(z\mid x) assigns probability to document zz given question xx and generator pθp_\theta produces answer y=(y1,…,yT)y=(y_1,\ldots,y_T). RAG-sequence marginalizes the same document for the entire sequence:

pseq(y∣x)=∑z∈ZK(x)pη(z∣x)∏t=1Tpθ(yt∣x,z,y<t).p_{\text{seq}}(y\mid x)=\sum_{z\in\mathcal Z_K(x)}p_\eta(z\mid x) \prod_{t=1}^{T}p_\theta(y_t\mid x,z,y_{<t}).

In RAG-token the mixture is inside the product, so different tokens can receive greater contributions from different documents:

ptoken(y∣x)=∏t=1T∑z∈ZK(x)pη(z∣x) pθ(yt∣x,z,y<t).p_{\text{token}}(y\mid x)=\prod_{t=1}^{T} \sum_{z\in\mathcal Z_K(x)}p_\eta(z\mid x)\, p_\theta(y_t\mid x,z,y_{<t}).

Here ZK(x)\mathcal Z_K(x) is the retrieved set and weights are normalized over it. A prompt concatenating passages for an LLM does not necessarily implement either distribution. The ability to mix documents does not guarantee a coherent or supported answer.

If the generator does not depend on η\eta and the retrieved set stays fixed during differentiation, the document posterior is

p(z∣x,y)=pη(z∣x)pθ(y∣x,z)∑z′pη(z′∣x)pθ(y∣x,z′),∇ηlog⁡pseq(y∣x)=∑zp(z∣x,y)∇ηlog⁡pη(z∣x).p(z\mid x,y)=\frac{p_\eta(z\mid x)p_\theta(y\mid x,z)} {\sum_{z'}p_\eta(z'\mid x)p_\theta(y\mid x,z')}, \qquad \nabla_\eta\log p_{\text{seq}}(y\mid x)= \sum_z p(z\mid x,y)\nabla_\eta\log p_\eta(z\mid x).

The observed answer increases weight on documents the generator explains well, not necessarily those proving the answer. Top-K selection is discrete and can change with parameters; the expression above treats the set as fixed. RAG studies both marginalizations; REALM trains retrieval with masked-language signal, FiD separately encodes passages and fuses their representations in the decoder, and RETRO incorporates retrieved chunks into language modeling.

In this synthetic example the retriever uses softmax over three logits and the generator assigns fixed likelihoods. For those logits, the gradient is posterior minus prior; a finite difference checks the calculation.

[ ]RAG posterior and gradientBrowser
import numpy as np
logits=np.array([0.3,-0.2,0.1])
likelihood=np.array([0.9,0.1,0.4])
def softmax(x):
    e=np.exp(x-x.max())
    return e/e.sum()
def objective(x):
    return np.log(softmax(x)@likelihood)
prior=softmax(logits)
posterior=prior*likelihood/(prior@likelihood)
gradient=posterior-prior
eps=1e-5
finite=np.array([(objective(logits+eps*np.eye(3)[i])-objective(logits-eps*np.eye(3)[i]))/(2*eps) for i in range(3)])
assert np.allclose(gradient,finite,atol=1e-8)
print('prior',prior.round(4),'posterior',posterior.round(4),'gradiente',gradient.round(4))

One answer, many stages

Ingestion preserves identifiers and provenance. Chunking creates indexable units; lexical and dense retrievers obtain candidates; fusion combines lists and a reranker orders them. The prompt builder chooses sources and respects the budget. Generation and citations are evaluated on the same question. Logging each stage shows whether coverage or the answer failed.

InteractiveX-ray of an answer

Question: Which NFL team represented the AFC at Super Bowl 50?

BM25; first five of the measured list.

  1. Super_Bowl_50 · ID 0 · 16.336
    Super Bowl 50 was an American football game to determine the champion of the National Football League (NFL) for the 2015 season. The American Football Conference (AFC) champion Denver Broncos defeated…
  2. Super_Bowl_50 · ID 22 · 14.750
    As the designated home team in the annual rotation between AFC and NFC teams, the Broncos elected to wear their road white jerseys with matching white pants. Elway stated, "We've had Super Bowl succes…
  3. Super_Bowl_50 · ID 25 · 11.712
    Various gold-themed promotions and initiatives were held throughout the 2015 NFL season to tie into the "Golden Super Bowl"; gold-tinted logos were implemented across the NFL's properties and painted …
  4. Super_Bowl_50 · ID 32 · 11.086
    In the United States, the game was televised by CBS, as part of a cycle between the three main broadcast television partners of the NFL. The network's lead broadcast team of Jim Nantz and Phil Simms c…
  5. Super_Bowl_50 · ID 24 · 11.009
    On June 4, 2014, the NFL announced that the practice of branding Super Bowl games with Roman numerals, a practice established at Super Bowl V, would be temporarily suspended, and that the game would b…
Cross-encoder
SQuAD source in top 5yes
Inspect lists and prompt for a real query; disabling the reranker changes displayed candidates.

The figure uses a query and passages from SQuAD, with BM25, E5, HNSW, RRF and cross-encoder run in the laboratory. Candidates are measured results; generated text and cost are shown only for the path actually run. Typographic dashes in passages are normalized in the view. Removing a stage changes the list but does not mean another generation was executed.

Chunking without losing context

Document chunking balances granularity and context. A short chunk can isolate a fact but separate a pronoun from its antecedent or a table from its header. Overlap reduces some boundary losses and increases duplicates, storage and cost. Preserving paragraphs and headings helps when document structure is reliable.

A contextual header can identify the document and summarize the section before indexing. If generated by a model it can contain errors and must not itself become evidence. Contextual Retrieval describes this family of methods; its figures depend on its data and do not replace a local ablation.

InteractiveHow should documents be chunked?
  • Evidence recall@5
  • Exact answer

Curves use fixed 25% overlap only for fixed windows; moving the control changes the example below, not the recorded measurements. Headers add words to the body and the generated summary may contain errors.

Chunk 1

Super Bowl 50 was an American football game to determine the champion of the National Football League (NFL) for the 2015 season. The American Football Conference (AFC) champion Denver Broncos defeated the National Football Conference (NFC) champion Carolina Panthers 24-10 to earn their third Super Bowl title. The game was played on February 7, 2016, at Levi's Stadium in the San Francisco Bay Area at Santa Clara, California. As this was the 50th Super Bowl, the league emphasized the "golden

Chunk 2

San Francisco Bay Area at Santa Clara, California. As this was the 50th Super Bowl, the league emphasized the "golden anniversary" with various gold-themed initiatives, as well as temporarily suspending the tradition of naming each Super Bowl game with Roman numerals (under which the game would have been known as "Super Bowl L"), so that the logo could prominently feature the Arabic numerals 50.

Chunk 3

the Arabic numerals 50.

20
Chunks in this paragraph3
Measured recall@51.000
Measured accuracy0.250
Change size, overlap and strategy; curves come from the laboratory’s real sample.

Count tokens with the target model’s tokenizer, including headers and separators. The visual example uses words to show chunking; words and tokens are not equivalent. Curves show only eight questions and exact answers from the local model under the declared corpus and rules: they do not prove a generally optimal size.

Transforming queries and building the prompt

Query transformation can rewrite a question, split it into subquestions or generate several searches. HyDE generates a hypothetical document and uses its embedding to search real documents. That hypothetical text may invent facts and is not a source. Compare transformations with the original query on the same questions and judgments; use paired intervals for differences, not isolated averages alone.

The context budget must reserve instructions, question, separators and answer. If CC is the limit, II fixed tokens, RR reserved tokens and each passage occupies BB, at most ⌊(C−I−R)/B⌋\lfloor(C-I-R)/B\rfloor equal passages fit. In practice measure each sequence with the actual tokenizer and reject or truncate before exceeding the limit.

For verifiable citations, number sources, ask the model to cite and abstain when evidence is missing, and check identifiers for each claim. An existing citation proves only that the identifier is valid. Checking whether a literal answer appears in a source is a limited signal, not proof of semantic entailment; complex claims need further verification and human review where appropriate. The ALCE benchmark separates answer correctness and citation quality.

Retrieved passages are data, not instructions authorized to change the task. Index access control and resistance to instructions inserted in documents are part of system design.

Position and distractors

Position effects can cause the same passage to be used differently when moved within context. Retrieved distractors can resemble the question more than random passages. Lost in the Middle observed degradation at middle positions in its tasks and models; this is not a universal law.

InteractiveLost in the middle

Only two selected SQuAD questions; this sample cannot yield a reliable interval. Results do not prove the model uses context or that a U-shaped curve exists.

Model
Distractors
Passages
Questions2
Positions1, 5, 10
Mean accuracy1.000
Compare observed accuracy when moving evidence; points use a small sample and do not force a U shape.

A correct answer can come from prior knowledge rather than the supplied passage. Compare positions and distractors with controls, additional questions and evidence of source use before attributing causality. More passages can improve coverage or add noise; measure both effects separately.

Local laboratory: retrieval and cited answers

These cells use PyTorch, NumPy, datasets, sentence-transformers, transformers, hnswlib, llama-cpp-python and huggingface_hub. They download models and data and save artifacts in rag-lab. The first selects the first 1200 SQuAD validation examples with 152 contexts, and eight questions from distinct contexts; in this run they belong to a small subset of four titles. It builds BM25, E5 embeddings, HNSW, RRF fusion and a cross-encoder. Recall@5 of the annotated source was 0.875, 1.000, 0.875 and 1.000 for BM25, dense, fusion and reranking respectively. These are eight cases, not a general estimate.

[ ]Ingestion, indices and rerankingLocal GPU
import json
from pathlib import Path
from datasets import load_dataset
from itertools import islice
ds=load_dataset('rajpurkar/squad',revision='7b6d24c440a36b6815f21b70d25016731768db1f',split='validation',streaming=True)
it=iter(ds)
rows=list(islice(it,1200))
if hasattr(it,'close'):it.close()
contexts={};questions=[]
for row in rows:
    ctx=row['context']
    if ctx not in contexts:contexts[ctx]={'id':len(contexts),'title':row['title'],'text':ctx}
    questions.append({'id':row['id'],'question':row['question'],'answers':row['answers']['text'],'context':contexts[ctx]['id']})
data={'contexts':list(contexts.values()),'questions':questions}
Path('rag-lab').mkdir(exist_ok=True)
with open('rag-lab/squad.json','w',encoding='utf-8') as f:json.dump(data,f,ensure_ascii=False)
print('examples',len(questions),'contexts',len(contexts),'titles',len(set(x['title'] for x in contexts.values())),flush=True)

import json,re,collections,numpy as np,torch,hnswlib
from sentence_transformers import SentenceTransformer
from transformers import AutoTokenizer,AutoModelForSequenceClassification
torch.set_num_threads(4)
data=json.load(open('rag-lab/squad.json',encoding='utf-8'))
docs=data['contexts']; seen=set(); questions=[]
for q in data['questions']:
    if q['context'] not in seen and q['answers']:
        questions.append(q);seen.add(q['context'])
    if len(questions)==8:break
device='cuda' if torch.cuda.is_available() else 'cpu'
encoder=SentenceTransformer('intfloat/multilingual-e5-small',revision='614241f622f53c4eeff9890bdc4f31cfecc418b3',device=device)
texts=[d['title']+' '+d['text'] for d in docs]
vectors=encoder.encode(['passage: '+x for x in texts],normalize_embeddings=True,batch_size=16,convert_to_numpy=True)
queries=encoder.encode(['query: '+q['question'] for q in questions],normalize_embeddings=True,batch_size=8,convert_to_numpy=True)
index=hnswlib.Index(space='cosine',dim=vectors.shape[1]);index.init_index(max_elements=len(docs),ef_construction=100,M=16,random_seed=22)
index.add_items(vectors,np.arange(len(docs)),num_threads=1);index.set_ef(64)
def toks(t):return re.findall(r'\w+',t.lower())
terms=[toks(t) for t in texts];counts=[collections.Counter(x) for x in terms]
df=collections.Counter(w for doc in counts for w in doc);avg=np.mean([len(x) for x in terms]);N=len(docs)
def bm25(q):
    score=np.zeros(N)
    for w in toks(q):
        if w not in df:continue
        idf=np.log(1+(N-df[w]+.5)/(df[w]+.5))
        for i,c in enumerate(counts):
            f=c[w]
            if f:score[i]+=idf*f*2.2/(f+1.2*(.25+.75*len(terms[i])/avg))
    return score
def fusion(a,b):
    s=collections.defaultdict(float)
    for l in (a,b):
        for rank,i in enumerate(l,1):s[int(i)]+=1/(60+rank)
    return sorted(s,key=lambda i:(-s[i],i)),s
modelname='cross-encoder/ms-marco-MiniLM-L6-v2';revision='233902d25c440f23af6f7d6e94d2946bac0bee0a'
tok=AutoTokenizer.from_pretrained(modelname,revision=revision)
cross=AutoModelForSequenceClassification.from_pretrained(modelname,revision=revision).to(device).eval()
results=[]
for q,v in zip(questions,queries):
    bs=bm25(q['question']);lex=np.argsort(-bs,kind='stable')[:20]
    labels,dist=index.knn_query(v,k=20,num_threads=1);dense=labels[0]
    fused,fscore=fusion(lex,dense);candidates=fused[:20];scores=[]
    with torch.no_grad():
        for start in range(0,len(candidates),8):
            sub=candidates[start:start+8]
            batch=tok([q['question']]*len(sub),[texts[i] for i in sub],padding=True,truncation=True,max_length=192,return_tensors='pt').to(device)
            scores.extend(cross(**batch).logits[:,0].cpu().tolist())
    rank=sorted(range(len(candidates)),key=lambda i:(-scores[i],candidates[i]))
    reranked=[candidates[i] for i in rank]
    results.append({'question':q,'lex':[int(x) for x in lex],'dense':[int(x) for x in dense],'fused':[int(x) for x in candidates],'reranked':[int(x) for x in reranked],
                    'bm25scores':bs[lex].tolist(),'denseScores':(1-dist[0]).tolist(),'fusedScores':[fscore[x] for x in candidates],
                    'crossScores':[float(scores[i]) for i in rank]})
for stage in ('lex','dense','fused','reranked'):
    recall=np.mean([int(r['question']['context'] in r[stage][:5]) for r in results])
    print(stage,'source-recall@5',float(recall),flush=True)
with open('rag-lab/pipeline.json','w',encoding='utf-8') as f:json.dump({'docs':docs,'cases':results},f,ensure_ascii=False)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The second cell loads both shards of GGUF Qwen2.5-7B-Instruct Q4_K_M, generates answers to three questions and requests citations. The budget uses a 4096-token context and the first 600 characters of each of five passages. It calculates exact match and token F1 against annotated answers, validates identifiers and checks whether any reference answer appears literally in a cited source. That last check is a lexical control, not proof that the citation entails the claim. This is a small sample and the model may know answers without using the source.

In the verified CPU run, all three answers exactly matched a reference, achieved token F1 1.0 and cited valid identifiers; in all three cases a reference answer appeared literally in a cited source. Times were approximately 354, 452 and 262 seconds per answer under shared load. These values describe only these three examples and do not prove causal fidelity or general performance.

[ ]Generation, accuracy and citationsLocal GPU
import json,re,string,time,collections
from llama_cpp import Llama
from huggingface_hub import hf_hub_download
data=json.load(open('rag-lab/pipeline.json',encoding='utf-8'))
repo='Qwen/Qwen2.5-7B-Instruct-GGUF';rev='bb5d59e06d9551d752d08b292a50eb208b07ab1f'
files=['qwen2.5-7b-instruct-q4_k_m-00001-of-00002.gguf','qwen2.5-7b-instruct-q4_k_m-00002-of-00002.gguf']
paths=[hf_hub_download(repo,f,revision=rev) for f in files]
llm=Llama(model_path=paths[0],n_ctx=4096,n_threads=4,verbose=False)
def norm(s):
    s=re.sub(r'\[\d+\]','',s).lower().translate(str.maketrans('','',string.punctuation))
    return ' '.join(w for w in s.split() if w not in ('a','an','the'))
def f1(pred,gold):
    p=norm(pred).split();g=norm(gold).split();common=sum((collections.Counter(p)&collections.Counter(g)).values())
    return 2*common/(len(p)+len(g)) if p and g else float(p==g)
results=[]
for case in data['cases'][:3]:
    q=case['question'];docs=[data['docs'][i] for i in case['reranked'][:5]]
    texts=[d['text'][:600] for d in docs]
    prompt=('Answer the question using only the numbered sources. Give a short answer followed by a source citation [n]; '
            'if the answer is not in the sources, say UNKNOWN.\nQuestion: '+q['question']+'\nSources:\n'
            +'\n'.join(f'[{i+1}] {text}' for i,text in enumerate(texts)))
    start=time.perf_counter();ans=llm.create_chat_completion(messages=[{'role':'user','content':prompt}],temperature=0,max_tokens=40)
    answer=ans['choices'][0]['message']['content'];elapsed=time.perf_counter()-start
    cited=[int(x) for x in re.findall(r'\[(\d+)\]',answer)]
    valid=bool(cited) and all(1<=x<=len(texts) for x in cited)
    support=valid and any(any(a.lower() in texts[i-1].lower() for a in q['answers'] if a) for i in cited)
    result={'question':q['question'],'answers':q['answers'],'answer':answer,
            'exact':any(norm(answer)==norm(a) for a in q['answers']),
            'f1':max(f1(answer,a) for a in q['answers']),'citations':cited,'valid':valid,'answer_in_cited_source':support,
            'source_ids':[d['id'] for d in docs],'texts':texts,'usage':ans['usage'],'seconds':elapsed}
    results.append(result)
    with open('rag-lab/generation.json','w',encoding='utf-8') as f:json.dump(results,f,ensure_ascii=False,indent=2)
    print('question',q['id'],'answer',repr(answer),'exact',result['exact'],'f1',result['f1'],'cites',cited,'answer-in-cited-source',support,'seconds',round(elapsed,1),flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

An additional check uses a published NLI model to compare the first cited passage with a declarative claim built from a template specific to the first question. It includes a control deliberately changing the entity. The predicted class is a fallible automatic signal: it does not turn a citation into proof or replace reviewing the claim and source.

In the verified run, the model assigned 0.9918 to entailment for the claim built with the actual answer and 0.9694 to contradiction for the altered control. These are classifier probabilities for two examples, not calibrated probabilities that a citation is correct.

[ ]Check support with NLILocal GPU
import json,re,torch
from transformers import AutoTokenizer,AutoModelForSequenceClassification
torch.set_num_threads(4)
rows=json.load(open('rag-lab/generation.json',encoding='utf-8'))
row=rows[0]
if not row['valid']:raise ValueError('La primera respuesta no tiene cita válida')
answer=re.sub(r'\[\d+\]','',row['answer']).strip().strip('.')
premise=row['texts'][row['citations'][0]-1]
# Plantilla específica para esta pregunta; el control cambia deliberadamente la entidad.
claims=[answer+' represented the AFC at Super Bowl 50.','Carolina Panthers represented the AFC at Super Bowl 50.']
name='cross-encoder/nli-deberta-v3-small';rev='fa2804872c3b4bd748f38c0185cc85775361e735'
tok=AutoTokenizer.from_pretrained(name,revision=rev)
model=AutoModelForSequenceClassification.from_pretrained(name,revision=rev).eval()
batch=tok([premise]*len(claims),claims,padding=True,truncation=True,max_length=512,return_tensors='pt')
with torch.no_grad(): probs=torch.softmax(model(**batch).logits,dim=1).tolist()
labels=['contradiction','entailment','neutral']
result=[{'claim':c,'probabilities':dict(zip(labels,p)),'label':labels[max(range(3),key=lambda i:p[i])]} for c,p in zip(claims,probs)]
print(result,flush=True)
with open('rag-lab/nli.json','w',encoding='utf-8') as f:json.dump(result,f,indent=2)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Local laboratory: chunks and queries

This cell uses the previously prepared corpus and Qwen2.5-1.5B-Instruct with E5. It generates a contextual header per paragraph, constructs fixed windows with 25% overlap and sentence-based chunks with or without title or generated context. It compares bodies of 40, 80 and 160 words on the same eight questions. The header is added to the body so the total can be larger: for a real token limit apply the chunking exercise.

For each configuration it measures whether the five chunks include the annotated paragraph with a reference answer, and exact match of the generated answer. It calculates paired bootstrap intervals against 80-word sentences. It then compares the original query, a rewrite, HyDE and fusion of original and rewrite. Hypothetical text is used only for retrieval, never as evidence. Results are exploratory: eight questions, passages from a public corpus and a model that may know the answers. Generating 152 headers and evaluating takes time; artifacts are saved in rag-lab.

In this sample, the original query with 80-word sentences achieved evidence recall@5 1.0 and accuracy 0.25; the rewrite achieved 0.75 and 0.125, HyDE 1.0 and 0.125, and fusion of original and rewrite 0.875 and 0.375. For the first question, hypothetical text incorrectly attributed the AFC conference to another team: that error is a real model output and must not be presented as a source. Paired intervals printed by the code reflect uncertainty in this tiny sample.

In an additional two-question comparison with ten cross-encoder-reranked candidates, alternating the best at both ends produced the same strict accuracy as preserving order: 0.5 each. In one answer the model wrote a sentence containing the correct name but not exactly matching the short reference answer. This observation does not prove equivalence between orders.

[ ]Ablations with the same questionsLocal GPU
import json,re,string,collections,numpy as np,torch
from transformers import AutoTokenizer,AutoModelForCausalLM
from sentence_transformers import SentenceTransformer
torch.set_num_threads(4)
data=json.load(open('rag-lab/squad.json',encoding='utf-8'))
docs=data['contexts'];seen=set();questions=[]
for q in data['questions']:
    if q['context'] not in seen and q['answers']:
        questions.append(q);seen.add(q['context'])
    if len(questions)==8:break
device='cuda' if torch.cuda.is_available() else 'cpu'
name='Qwen/Qwen2.5-1.5B-Instruct';rev='989aa7980e4cf806f80c7fef2b1adb7bc71aa306'
tok=AutoTokenizer.from_pretrained(name,revision=rev)
model=AutoModelForCausalLM.from_pretrained(name,revision=rev,dtype=torch.float16 if device=='cuda' else torch.float32).to(device).eval()
encoder=SentenceTransformer('intfloat/multilingual-e5-small',revision='614241f622f53c4eeff9890bdc4f31cfecc418b3',device=device)
def generate(prompt,limit=24):
    chat=tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=False,add_generation_prompt=True)
    batch=tok(chat,return_tensors='pt').to(device)
    with torch.no_grad():out=model.generate(**batch,max_new_tokens=limit,do_sample=False,pad_token_id=tok.eos_token_id)
    return tok.decode(out[0,batch['input_ids'].shape[1]:],skip_special_tokens=True).strip()
def norm(s):
    s=s.lower().translate(str.maketrans('','',string.punctuation))
    return ' '.join(w for w in s.split() if w not in ('a','an','the'))
def fixed(text,size):
    words=text.split();step=size-max(1,size//4)
    return [' '.join(words[i:i+size]) for i in range(0,len(words),step) if words[i:i+size]]
def structured(text,size):
    sentences=re.split(r'(?<=[.!?])\s+',text);out=[];current=[]
    for sentence in sentences:
        words=sentence.split()
        if len(words)>size:
            if current:out.append(' '.join(current));current=[]
            out.extend(' '.join(words[i:i+size]) for i in range(0,len(words),size))
        elif len(current)+len(words)>size:
            out.append(' '.join(current));current=words
        else:current.extend(words)
    if current:out.append(' '.join(current))
    return out
summaries=[]
for d in docs:
    s=generate('Write a short context label for this excerpt, without answering a question.\n'+d['title']+'\n'+d['text'][:600],20)
    summaries.append(s)
print('contextual headers generated',len(summaries),flush=True)
with open('rag-lab/summaries.json','w',encoding='utf-8') as f:json.dump(summaries,f,ensure_ascii=False)
qvec=encoder.encode(['query: '+q['question'] for q in questions],normalize_embeddings=True,convert_to_numpy=True,batch_size=8)
def evaluate(chunks,qvectors):
    X=encoder.encode(['passage: '+c['text'] for c in chunks],normalize_embeddings=True,convert_to_numpy=True,batch_size=16)
    hits=[];exact=[];selected=[]
    for q,v in zip(questions,qvectors):
        ranking=np.argsort(-(X@v),kind='stable')[:5]
        retrieved=[chunks[i] for i in ranking]
        hit=any(c['source']==q['context'] and any(a.lower() in c['body'].lower() for a in q['answers'] if a) for c in retrieved)
        prompt=('Answer with a short phrase using the sources. If absent say UNKNOWN.\n'
                +'\n'.join(f'[{i+1}] {c["text"]}' for i,c in enumerate(retrieved))
                +'\nQuestion: '+q['question']+'\nAnswer:')
        reply=generate(prompt,20)
        ok=any(norm(reply)==norm(a) for a in q['answers'])
        hits.append(int(hit));exact.append(int(ok));selected.append({'answer':reply,'ids':[int(i) for i in ranking]})
    return {'recall':float(np.mean(hits)),'exact':float(np.mean(exact)),'hits':hits,'exact_per_query':exact,'results':selected}
results={};cache={}
for size in (40,80,160):
    for strategy in ('fija','frases','encabezado','contextual'):
        chunks=[]
        for d,s in zip(docs,summaries):
            bodies=fixed(d['text'],size) if strategy=='fija' else structured(d['text'],size)
            for body in bodies:
                prefix=(d['title']+' | '+s+'\n') if strategy=='contextual' else ((d['title']+'\n') if strategy=='encabezado' else '')
                chunks.append({'source':d['id'],'body':body,'text':prefix+body})
        result=evaluate(chunks,qvec);result['chunks']=len(chunks)
        results[f'{strategy}-{size}']=result
        if strategy=='frases' and size==80:cache['chunks']=chunks
        print(strategy,size,'chunks',len(chunks),'recall',result['recall'],'exact',result['exact'],flush=True)
rng=np.random.default_rng(22)
baseline=results['frases-80']
for result in results.values():
    result['ci_vs_frases80']={}
    for field in ('hits','exact_per_query'):
        delta=np.array(result[field])-np.array(baseline[field])
        boot=delta[rng.integers(0,len(delta),(2000,len(delta)))].mean(axis=1)
        result['ci_vs_frases80'][field]=np.quantile(boot,[.025,.975]).tolist()
with open('rag-lab/chunks.json','w',encoding='utf-8') as f:json.dump(results,f,ensure_ascii=False,indent=2)
rewrites=[];hypotheses=[]
for q in questions:
    rewrites.append(generate('Rewrite this question as a concise search query; return only the query.\n'+q['question'],25))
    hypotheses.append(generate('Write a short hypothetical passage that could answer this question. Do not claim it is verified.\n'+q['question'],45))
rv=encoder.encode(['query: '+s for s in rewrites],normalize_embeddings=True,convert_to_numpy=True)
hv=encoder.encode(['passage: '+s for s in hypotheses],normalize_embeddings=True,convert_to_numpy=True)
base=results['frases-80']
transforms={'original':base,'reescrita':evaluate(cache['chunks'],rv),'hyde':evaluate(cache['chunks'],hv)}
# Multi-query combines original and rewritten rankings by reciprocal rank, not by vector averaging.
X=encoder.encode(['passage: '+c['text'] for c in cache['chunks']],normalize_embeddings=True,convert_to_numpy=True,batch_size=16)
hits=[];exact=[];selected=[]
for q,v1,v2 in zip(questions,qvec,rv):
    lists=[np.argsort(-(X@v),kind='stable')[:20] for v in (v1,v2)]
    score=collections.defaultdict(float)
    for ranking in lists:
        for rank,i in enumerate(ranking,1):score[int(i)]+=1/(60+rank)
    ids=sorted(score,key=lambda i:(-score[i],i))[:5];retrieved=[cache['chunks'][i] for i in ids]
    hits.append(int(any(c['source']==q['context'] and any(a.lower() in c['body'].lower() for a in q['answers'] if a) for c in retrieved)))
    reply=generate('Answer with a short phrase using the sources. If absent say UNKNOWN.\n'+'\n'.join(c['text'] for c in retrieved)+'\nQuestion: '+q['question']+'\nAnswer:',20)
    exact.append(int(any(norm(reply)==norm(a) for a in q['answers'])));selected.append({'answer':reply,'ids':ids})
transforms['multiple']={'recall':float(np.mean(hits)),'exact':float(np.mean(exact)),'hits':hits,'exact_per_query':exact,'results':selected}
rng=np.random.default_rng(22)
for name,result in transforms.items():
    result['ci_vs_original']={}
    for field in ('hits','exact_per_query'):
        delta=np.array(result[field])-np.array(base[field])
        boot=delta[rng.integers(0,len(delta),(2000,len(delta)))].mean(axis=1)
        result['ci_vs_original'][field]=np.quantile(boot,[.025,.975]).tolist()
    print('transform',name,'recall',result['recall'],'exact',result['exact'],'CI',result['ci_vs_original'],flush=True)
with open('rag-lab/transforms.json','w',encoding='utf-8') as f:json.dump({'rewrites':rewrites,'hypotheses':hypotheses,'results':transforms},f,ensure_ascii=False,indent=2)

# Coloca los candidatos mejor puntuados en extremos sin usar la etiqueta de relevancia.
trace=json.load(open('rag-lab/pipeline.json',encoding='utf-8'))
reorder=[]
for case in trace['cases'][:2]:
    original=case['reranked'][:10];ends=[None]*len(original);left=0;right=len(original)-1
    for i,idx in enumerate(original):
        if i%2==0:ends[left]=idx;left+=1
        else:ends[right]=idx;right-=1
    for method,ranking in [('orden',original),('extremos',ends)]:
        texts=[' '.join(docs[idx]['text'].split()[:35]) for idx in ranking]
        prompt='Answer with a short phrase using the sources. If absent say UNKNOWN.\n'+'\n'.join(texts)+'\nQuestion: '+case['question']['question']+'\nAnswer:'
        reply=generate(prompt,20);ok=any(norm(reply)==norm(a) for a in case['question']['answers'])
        reorder.append({'method':method,'question':case['question']['question'],'ids':ranking,'answer':reply,'exact':ok})
        print('reordenar',method,repr(reply),'exact',ok,flush=True)
with open('rag-lab/reordering.json','w',encoding='utf-8') as f:json.dump(reorder,f,ensure_ascii=False,indent=2)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Local laboratory: position and distractors

This cell uses the first two questions from different contexts of the same corpus. For each model it compares 10 and 20 passages, random or BM25-retrieved distractors, and evidence at the beginning, near the middle or at the end. Distractors exclude literal matches with annotated answers. Each passage is trimmed to 35 words and the answer evaluated by normalized exact match. The code saves each result on completion and can resume from the existing file.

With Qwen2.5-1.5B-Instruct all 24 combinations for two questions were run and accuracy was 1.0 on all. Another 24 were run with NF4-quantized Qwen2.5-7B-Instruct on GPU: for 20 passages with retrieved distractors, the mean over two questions was 0.5, 0.5 and 1.0 at beginning, middle and end; other configurations had 1.0 at each position. This proves neither a U-shaped curve nor use of evidence: team and player names may be in weights. The NF4 variant needs CUDA, bitsandbytes and accelerate plus original-weight downloads; GGUF Q4_K_M on CPU is another, slower quantization and saves separate results. Change which to choose. Observations are logged by model, position and question.

[ ]Evidence positionLocal GPU
import os,sys,json,re,string,random,time,collections
import numpy as np
data=json.load(open('rag-lab/squad.json',encoding='utf-8'))
docs=data['contexts'];seen=set();questions=[]
for q in data['questions']:
    if q['context'] not in seen and q['answers']:
        questions.append(q);seen.add(q['context'])
    if len(questions)==2:break
def norm(s):
    s=s.lower().translate(str.maketrans('','',string.punctuation))
    return ' '.join(w for w in s.split() if w not in ('a','an','the'))
def tokenize(s):return re.findall(r'\w+',s.lower())
words=[tokenize(d['text']) for d in docs];counts=[collections.Counter(w) for w in words]
df=collections.Counter(w for c in counts for w in c);N=len(docs);avg=np.mean([len(x) for x in words])
def bm(q):
    score=np.zeros(N)
    for w in tokenize(q):
        if w not in df:continue
        idf=np.log(1+(N-df[w]+.5)/(df[w]+.5))
        for i,c in enumerate(counts):
            f=c[w]
            if f:score[i]+=idf*f*2.2/(f+1.2*(.25+.75*len(words[i])/avg))
    return np.argsort(-score,kind='stable')
def snippet(text,answer=None):
    parts=text.split()
    if answer:
        offset=text.lower().find(answer.lower())
        pos=len(text[:max(0,offset)].split())
        start=max(0,min(len(parts)-35,pos-12))
    else:start=0
    return ' '.join(parts[start:start+35])
def make_prompt(q,kind,k,pos):
    answers=q['answers'];target=q['context'];randomizer=random.Random(2200+target+k)
    eligible=[i for i,d in enumerate(docs) if i!=target and not any(a.lower() in d['text'].lower() for a in answers if a)]
    if kind=='aleatorio':randomizer.shuffle(eligible);others=eligible[:k-1]
    else:
        allowed=set(eligible);others=[int(i) for i in bm(q['question']) if int(i) in allowed][:k-1]
    passages=[snippet(docs[i]['text']) for i in others]
    passages.insert(pos,snippet(docs[target]['text'],answers[0]))
    assert len(passages)==k and answers[0].lower() in passages[pos].lower()
    return ('Answer the question using the passages. Return only a short answer; if absent, say UNKNOWN.\n'
            +'\n'.join(f'[{i+1}] {p}' for i,p in enumerate(passages))
            +'\nQuestion: '+q['question']+'\nAnswer:')
which='1.5b'  # '7b' para GGUF en CPU, '7b-nf4' para pesos originales en GPU
if which=='7b-nf4':
    import torch
    from transformers import AutoTokenizer,AutoModelForCausalLM,BitsAndBytesConfig
    name='Qwen/Qwen2.5-7B-Instruct';rev='a09a35458c702b33eeacc393d103063234e8bc28'
    tok=AutoTokenizer.from_pretrained(name,revision=rev)
    config=BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type='nf4',bnb_4bit_compute_dtype=torch.float16)
    model=AutoModelForCausalLM.from_pretrained(name,revision=rev,quantization_config=config,device_map={'':0},dtype=torch.float16).eval()
    def generate(prompt):
        text=tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=False,add_generation_prompt=True)
        batch=tok(text,return_tensors='pt').to('cuda')
        with torch.no_grad():out=model.generate(**batch,max_new_tokens=20,do_sample=False,pad_token_id=tok.eos_token_id)
        new=out[0,batch['input_ids'].shape[1]:]
        return tok.decode(new,skip_special_tokens=True),int(out.shape[1])
elif which=='7b':
    from llama_cpp import Llama
    from huggingface_hub import hf_hub_download
    repo='Qwen/Qwen2.5-7B-Instruct-GGUF';rev='bb5d59e06d9551d752d08b292a50eb208b07ab1f'
    files=['qwen2.5-7b-instruct-q4_k_m-00001-of-00002.gguf','qwen2.5-7b-instruct-q4_k_m-00002-of-00002.gguf']
    paths=[hf_hub_download(repo,f,revision=rev) for f in files]
    model=Llama(model_path=paths[0],n_ctx=2048,n_threads=8,verbose=False)
    def generate(prompt):
        response=model.create_chat_completion(messages=[{'role':'user','content':prompt}],temperature=0,max_tokens=20)
        return response['choices'][0]['message']['content'],response['usage']['total_tokens']
else:
    import torch
    from transformers import AutoTokenizer,AutoModelForCausalLM
    name='Qwen/Qwen2.5-1.5B-Instruct';rev='989aa7980e4cf806f80c7fef2b1adb7bc71aa306'
    tok=AutoTokenizer.from_pretrained(name,revision=rev)
    device='cuda' if torch.cuda.is_available() else 'cpu'
    model=AutoModelForCausalLM.from_pretrained(name,revision=rev,dtype=torch.float16 if device=='cuda' else torch.float32).to(device).eval()
    def generate(prompt):
        text=tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=False,add_generation_prompt=True)
        t=tok(text,return_tensors='pt').to(device)
        with torch.no_grad():out=model.generate(**t,max_new_tokens=20,do_sample=False,pad_token_id=tok.eos_token_id)
        new=out[0,t['input_ids'].shape[1]:]
        return tok.decode(new,skip_special_tokens=True),int(out.shape[1])
output='rag-lab/position-'+which+'.json'
records=json.load(open(output,encoding='utf-8')) if os.path.exists(output) else []
completed={(r['kind'],r['k'],r['position'],r['question']) for r in records}
for kind in ('aleatorio','recuperado'):
    for k in (10,20):
        for pos in (0,(k-1)//2,k-1):
            for q in questions:
                if (kind,k,pos+1,q['question']) in completed:continue
                prompt=make_prompt(q,kind,k,pos);start=time.perf_counter()
                response,tokens=generate(prompt);elapsed=time.perf_counter()-start
                record={'model':which,'kind':kind,'k':k,'position':pos+1,'question':q['question'],'answers':q['answers'],
                        'response':response,'exact':any(norm(response)==norm(a) for a in q['answers']),
                        'tokens':tokens,'seconds':elapsed}
                records.append(record)
                with open(output,'w',encoding='utf-8') as f:json.dump(records,f,ensure_ascii=False,indent=2)
                print(which,kind,k,pos+1,record['exact'],repr(response),'seconds',round(elapsed,1),flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofRetriever gradient
Prove: Derive the gradient of log p(y | x) in RAG-sequence with respect to retriever parameters, keeping the retrieved set fixed.
0
Write the joint distribution as pη(z | x) pθ(y | x,z), with θ independent of η.

Step 1 of 3. How is the sum of probabilities differentiated with respect to η?

Quiz
An answer needs facts from two documents. Which formulation offers a per-token mixture that can give them different contributions?
NumericHow many chunks fit?
The context permits 8192 tokens. Reserve 600 for instructions and question, 512 for the answer, and each chunk needs 350 plus a 20-token header. How many complete chunks fit?
CodeChunks with headers
Implement chunk_document(text, max_tokens, overlap, tokenizer). Recognize Markdown headings # through ###### and add their path joined by ' / ' to each chunk. Preserve whole sentences when they fit and split overly long ones. overlap is the maximum body tokens repeated between chunks of the same section. Never exceed max_tokens when retokenizing the complete string. The tokenizer offers encode(text, add_special_tokens=False) and decode(ids, skip_special_tokens=True).
def chunk_document(text, max_tokens, overlap, tokenizer):
  pass
Shift+Enter to run
CodeCitations by sentence
Implement check_citations(answer, passages). Return a list of dictionaries with sentence, missing (no citation) and invalid (identifiers outside 1..len(passages)). Recognize citations [n], including immediately after a period, and use heuristic punctuation splitting. Do not claim to check semantic entailment.
def check_citations(answer, passages):
  pass
Shift+Enter to run
Key idea
RAG is an evaluable chain: chunking, retrieval, context selection, generation and citations. A good answer and valid citation do not themselves prove evidence supports it.