Evaluating and improving RAG: faithfulness, adaptive retrieval, GraphRAG and long context
Evaluate RAG by separating retrieval, context use, generation and claim-level faithfulness. Study verifier calibration, adaptive and iterative retrieval, GraphRAG and long-context comparison using measured local experiments.
After this lesson you can
- Design RAG evaluation attributing errors to retrieval, context use or generation.
- Implement claim-level faithfulness using NLI and an LLM judge and validate against 100 annotations with Cohen’s kappa.
- Implement iterative retrieval interleaved with reasoning for multi-hop questions and compare with one retrieval at matched cost.
- Build a minimal GraphRAG with entities, communities and summaries and measure where it outperforms vector RAG.
- Compare RAG with long context in accuracy, cost and latency using the same local model.
Before you start
- 23Probabilistic formulation of RAGGrounded generation with citationsContext position and distractor effectsReActRanking metricsPaired system comparisonGenerative verifier
- 20LLM-as-a-judgeLLM judge biases
- 25Knowledge graph as relational multigraphModularityLouvain and Leiden algorithms
- 18Length generalizationPosition interpolationYaRN
- 05Cohen's kappa and inter-annotator agreement
Diagnose before changing
Final accuracy does not say where a RAG chain failed. Were passages needed by the question retrieved? Did the answer use them? Do citations actually support each claim? Error attribution separates these questions, although imperfect judgments leave ambiguous cases. An answer can be correct through prior knowledge without support in context. An answer faithful to an incorrect source can be wrong.
For annotated relevant passage set and retrieved list , context recall is . Precision measures how much retrieved material is useful; with graded relevance specify weighting and treatment of ties and duplicates. Both measures depend on possibly incomplete annotations. Evaluate correctness against reference answers and faithfulness against delivered sources separately. RAGAS proposes per-dimension metrics; ARES combines trained judges and human-annotated data to correct estimates.
Checking claims
Claim-level faithfulness splits an answer into checkable units and verifies each against evidence. If claims have verdicts and are supported, one convention is . Unverified claims must be shown separately: counting them as supported inflates the score, and excluding them without disclosure hides coverage. One sentence can contain several facts. FActScore motivates decomposition into atomic facts and checking against a source.
A textual-inference model compares premise and hypothesis and estimates contradiction, entailment or neutrality. An LLM judge can emit a verdict and explanation; both can fail, truncate evidence or be prompt-sensitive. Before using them as an in-domain metric, prepare your own sample, request independent annotations, fix the rubric and analyze disagreements. For binary agreement, with observed proportion and expected marginal agreement , Cohen’s kappa is . A bootstrap by independent unit gives an interval, not removal of selection bias. If , the formula is undefined.
As an external reference, on 100 selected RAGTruth sentences NLI achieved agreement 0.68 and kappa 0.36 against published human markings; bootstrap interval was approximately [0.226, 0.500]. A Qwen2.5-7B NF4 judge achieved agreement 0.76 and kappa 0.52, interval [0.342, 0.679]. Fifty sentences with a marked span and 50 from unmarked answers were chosen from distinct sources. This balanced sample does not represent natural prevalence; absence of a mark is not exhaustive proof of entailment. Both received only the first 1000 characters of each context and evidence may be missing. This does not replace domain-specific annotations.
Search when needed
Adaptive retrieval decides whether to search again. FLARE uses uncertainty signals during generation to trigger retrieval; Self-RAG trains a model with special tokens to retrieve and critique. A generic prompt saying “critique” does not reproduce that training.
In iterative retrieval, the first passage can reveal an entity the question does not name; a later query searches for the second fact. IRCoT interleaves reasoning and retrieval steps. A ReAct agent can also invoke search as a tool; Search-R1 studies training to integrate search and reasoning. The visible trace is a summarized operational record, not a guarantee that every inference is correct.
Compare single retrieval, iteration and an agent with the same total passage count and an explicit token budget. Measure coverage of each fact, accuracy, calls and latency. An index built from benchmark candidates is not equivalent to searching all Wikipedia.
On two questions, single search retrieved one of two supporting titles and iteration retrieved both. Variants in that first comparison delivered four passages under the same 8192-token cap; intermediate calls made actual consumption differ. None of six answers exactly matched its reference. The tool variant in that comparison forces a second search. In an additional run, the lesson 13 ReAct engine decided when to search and finish: it retrieved both supporting titles on both questions but got neither exact match. On the first it ended with literal text “answer”; on the second it exhausted the four-step limit after two formatting errors. These traces show retrieving evidence does not guarantee using it.
To reproduce the autonomous variant, after preparing the HotpotQA index below download the ReAct engine as react_engine.py and the experiment as react-hotpot.py to the same directory. Run python react-hotpot.py with CUDA and local laboratory packages. The agent can perform up to two searches of two passages and has an 8192-token cap; it decides when to invoke the tool or finish. Traces are saved in rag-eval/react_autonomous.json.
Global questions and graphs
GraphRAG extracts entities and relationships, forms communities and summarizes groups before answering. It can help synthesize themes spread across many documents where neighbors from one query do not cover the corpus. Extraction can merge entities, invent edges or accumulate summary errors; inspect evidence and evaluate global and local questions separately. From Local to Global addresses global questions with community summaries. Reindexing and summarizing a frequently changing corpus also costs resources.
Retrieve or read everything
When comparing long context versus RAG, keep model, questions and correctness criterion fixed; record input and output tokens, latency and indexing cost. A small corpus fitting in one window does not show what happens with a larger one. More context can add coverage and distractors; advertised context length does not guarantee effective understanding. RULER extends evaluation beyond locating one needle, and Li and colleagues compare retrieval and long context across datasets. A hybrid system can retrieve documents and read more than one passage in context.
Local laboratory: calibrating verifiers
The cell downloads official RAGTruth files, checks their hash, selects 100 sources and runs NLI. It requires PyTorch, transformers, NumPy and requests; files are saved in rag-eval. These are published human labels, not our annotations. We deliberately select balanced classes and use only 1000 context characters so the judge receives the same input. An unmarked span does not guarantee entailment and truncation may hide evidence. Bootstrap resamples the 100 sources.
import hashlib,requests
from pathlib import Path
Path('rag-eval').mkdir(exist_ok=True)
base='https://raw.githubusercontent.com/ParticleMedia/RAGTruth/c103204b9ce28d6bbad859304bf30de72b8ed8fe/dataset/'
files={'response.jsonl':'e4c2e4ac24fff676d8984cc61c35d791612fadc58015335d97dd632375e18073',
'source_info.jsonl':'0dffc26ea9f3c1c3d7c7e8336b56ef1646e3cec876edffcca3c9c624d12d578b'}
for name,digest in files.items():
p=Path('rag-eval')/name
if not p.exists():
response=requests.get(base+name,timeout=120);response.raise_for_status();p.write_bytes(response.content)
if hashlib.sha256(p.read_bytes()).hexdigest()!=digest:raise ValueError('hash incorrecto: '+name)
import json,re,collections
path='rag-eval/'
sources={r['source_id']:r for r in (json.loads(s) for s in open(path+'source_info.jsonl',encoding='utf-8')) if r['task_type']=='QA'}
responses=sorted((json.loads(s) for s in open(path+'response.jsonl',encoding='utf-8')),key=lambda r:r['split']!='test')
by_label={0:[],1:[]};seen=set()
for r in responses:
if r['quality']!='good' or r['source_id'] not in sources or r['source_id'] in seen:continue
# La etiqueta original marca tramos alucinados; no equivale a implicación exhaustiva.
if r['labels']:
label=r['labels'][0];start=label['start'];end=label['end']
bounds=[(m.start(),m.end()) for m in re.finditer(r'[^.!?]+[.!?]?',r['response'])]
match=next(((a,b) for a,b in bounds if a<=start<b and end<=b),None)
if not match:continue
sentence=r['response'][match[0]:match[1]].strip();verdict=0
else:
sentence=re.split(r'(?<=[.!?])\s+',r['response'].strip())[0];verdict=1
if len(sentence)<15 or len(sentence)>400:continue
if len(by_label[verdict])>=50:continue
source=sources[r['source_id']]['source_info'];passages=source['passages']
by_label[verdict].append({'source_id':r['source_id'],'response_id':r['id'],'split':r['split'],'claim':sentence,'passages':passages,'human_no_marked_span':verdict,'labels':r['labels']})
seen.add(r['source_id'])
if all(len(x)==50 for x in by_label.values()):break
sample=by_label[0]+by_label[1]
with open(path+'human_sample.json','w',encoding='utf-8') as f:json.dump(sample,f,ensure_ascii=False,indent=2)
print('human annotation sample',collections.Counter(x['human_no_marked_span'] for x in sample),'unique sources',len(seen),flush=True)
import json,numpy as np,torch
from transformers import AutoTokenizer,AutoModelForSequenceClassification
torch.set_num_threads(4)
root='rag-eval/'
sample=json.load(open(root+'human_sample.json',encoding='utf-8'))
name='cross-encoder/nli-deberta-v3-small';rev='fa2804872c3b4bd748f38c0185cc85775361e735'
tok=AutoTokenizer.from_pretrained(name,revision=rev)
model=AutoModelForSequenceClassification.from_pretrained(name,revision=rev).eval()
for r in sample:
batch=tok(r['passages'][:1000],r['claim'],return_tensors='pt',truncation='only_first',max_length=512)
with torch.no_grad():probs=torch.softmax(model(**batch).logits,dim=-1)[0].tolist()
r['nli_probabilities']=dict(zip(['contradiction','entailment','neutral'],probs));r['nli_supported']=int(np.argmax(probs)==1)
def kappa(a,b):
a=np.asarray(a);b=np.asarray(b);observed=(a==b).mean();expected=(a.mean()*b.mean()+(1-a.mean())*(1-b.mean()))
return float((observed-expected)/(1-expected)) if expected<1 else float('nan')
a=np.array([r['human_no_marked_span'] for r in sample]);b=np.array([r['nli_supported'] for r in sample]);rng=np.random.default_rng(23)
boot=[]
for _ in range(2000):
ix=rng.integers(0,len(a),len(a));x=kappa(a[ix],b[ix])
if np.isfinite(x):boot.append(x)
result={'kappa':kappa(a,b),'agreement':float((a==b).mean()),'ci':np.quantile(boot,[.025,.975]).tolist(),'n':len(a),'sample':sample}
with open(root+'nli_eval.json','w',encoding='utf-8') as f:json.dump(result,f,ensure_ascii=False,indent=2)
print({k:v for k,v in result.items() if k!='sample'},flush=True)npm run lab and open the connection link.The next cell runs the 7B NF4 judge on the same sample. It requires a CUDA GPU, bitsandbytes and accelerate, and downloads pinned original weights. Verdicts are saved one by one and the run can resume. The interval corresponds to the published selection, not new annotation.
import json,os,time,numpy as np,torch
from transformers import AutoTokenizer,AutoModelForCausalLM,BitsAndBytesConfig
root='rag-eval/'
sample=json.load(open(root+'human_sample.json',encoding='utf-8'))
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()
rows=json.load(open(root+'judge-progress.json',encoding='utf-8')) if os.path.exists(root+'judge-progress.json') else []
done={r['response_id'] for r in rows}
for r in sample:
if r['response_id'] in done:continue
passage=r['passages'][:1000]
prompt=('Is the claim fully supported by the provided evidence? Reply only YES or NO.\nEvidence: '+passage+'\nClaim: '+r['claim']+'\nVerdict:')
chat=tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=False,add_generation_prompt=True)
batch=tok(chat,return_tensors='pt').to('cuda');start=time.perf_counter()
with torch.no_grad():out=model.generate(**batch,max_new_tokens=4,do_sample=False,pad_token_id=tok.eos_token_id)
reply=tok.decode(out[0,batch['input_ids'].shape[1]:],skip_special_tokens=True).strip()
verdict=1 if reply.upper().startswith('YES') else 0 if reply.upper().startswith('NO') else None
rows.append({'source_id':r['source_id'],'response_id':r['response_id'],'gold':r['human_no_marked_span'],'reply':reply,'verdict':verdict,'seconds':time.perf_counter()-start})
with open(root+'judge-progress.json','w',encoding='utf-8') as f:json.dump(rows,f,ensure_ascii=False,indent=2)
print(len(rows),reply,flush=True)
def kappa(a,b):
a=np.asarray(a);b=np.asarray(b);observed=(a==b).mean();expected=a.mean()*b.mean()+(1-a.mean())*(1-b.mean())
return float((observed-expected)/(1-expected)) if expected<1 else float('nan')
valid=[r for r in rows if r['verdict'] is not None];a=np.array([r['gold'] for r in valid]);b=np.array([r['verdict'] for r in valid]);rng=np.random.default_rng(23);boot=[]
for _ in range(2000):
ix=rng.integers(0,len(a),len(a));v=kappa(a[ix],b[ix])
if np.isfinite(v):boot.append(v)
result={'n':len(rows),'valid':len(valid),'agreement':float((a==b).mean()),'kappa':kappa(a,b),'ci':np.quantile(boot,[.025,.975]).tolist(),'rows':rows}
with open(root+'judge_eval.json','w',encoding='utf-8') as f:json.dump(result,f,ensure_ascii=False,indent=2)
print({k:v for k,v in result.items() if k!='rows'},flush=True)
del model
torch.cuda.empty_cache()npm run lab and open the connection link.For your own evaluation, this cell creates a template of 100 claims without verdicts. A person annotates 1 or 0 against shown context without seeing predictions, then reruns the cell to calculate agreement, kappa and intervals for both models. Later use a real-domain sample and second annotator to study disagreements. An empty template is not completed human annotation.
import csv,json,os,numpy as np
root='rag-eval/'
sample=json.load(open(root+'nli_eval.json',encoding='utf-8'))['sample']
judge=json.load(open(root+'judge_eval.json',encoding='utf-8'))['rows']
path=root+'own_annotations.csv'
if not os.path.exists(path):
with open(path,'w',encoding='utf-8',newline='') as f:
w=csv.DictWriter(f,fieldnames=['response_id','claim','context','human'])
w.writeheader()
for r in sample:w.writerow({'response_id':r['response_id'],'claim':r['claim'],'context':r['passages'][:1000],'human':''})
print('Plantilla creada: anota 1 si está sostenida y 0 si no, sin ver las predicciones.')
else:
with open(path,encoding='utf-8',newline='') as f:human=list(csv.DictReader(f))
labels={r['response_id']:r['human'].strip() for r in human}
if len(labels)!=len(sample) or any(labels.get(r['response_id']) not in ('0','1') for r in sample):
raise ValueError('Completa exactamente un veredicto 0 o 1 para cada respuesta')
truth=np.array([int(labels[r['response_id']]) for r in sample]);j={r['response_id']:r['verdict'] for r in judge}
if any(j.get(r['response_id']) not in (0,1) for r in sample):raise ValueError('Faltan veredictos del juez')
preds={'NLI':np.array([r['nli_supported'] for r in sample]),'juez':np.array([j[r['response_id']] for r in sample])}
def kappa(a,b):
observed=np.mean(a==b);expected=a.mean()*b.mean()+(1-a.mean())*(1-b.mean())
return (observed-expected)/(1-expected) if expected<1 else float('nan')
for name,pred in preds.items():
rng=np.random.default_rng(23)
draws=[]
for _ in range(2000):
ix=rng.integers(0,len(truth),len(truth));v=kappa(truth[ix],pred[ix])
if np.isfinite(v):draws.append(v)
if not draws:print(name,'kappa no definida');continue
print(name,'acuerdo',float(np.mean(truth==pred)),'kappa',kappa(truth,pred),'IC',np.quantile(draws,[.025,.975]).tolist())npm run lab and open the connection link.A second assistant-annotated sample
Besides published human markings, download this custom sample and save it as assistant_annotations.json in the working directory. It contains 100 claims about ten HotpotQA passages with text, binary label and evidence for each judgment. The assistant preparing the lesson wrote and read claims before seeing predictions: 1 means everything is supported by the passage and 0 means contradicted or unsupported. Absence of information is not contradiction. Judgments are neither human nor independent of the case author; the balanced sample includes deliberate number and entity changes and does not estimate real-error prevalence.
NLI agreed on 82 of 100 judgments, kappa 0.64, with bootstrap interval [0.48, 0.80] resampling all ten passages. The 7B judge agreed on 99 of 100, kappa 0.98 and interval [0.94, 1.00] under the same resampling; its disagreement rejected that Tyler Bates composes for video games, which the passage does say. This high number concerns constructed claims, many with simple number or entity changes, and does not demonstrate that performance on natural answers. Treating repeated sentences from one source as independent observations would artificially narrow the interval. Also review NLI disagreements: it accepted that Johnny Depp directed Ed Wood although the passage credits him as star and Tim Burton as director. The check does not replace independent human validation before using a judge in production.
The next cell runs both models on the same inputs, retains per-claim results and calculates kappa and clustered intervals. Each pinned model revision and the seed make the protocol reproducible; the 7B judge requires a CUDA GPU. NLI neutral is grouped with contradiction as “unsupported”; the two are not claimed semantically equivalent.
import json, hashlib, numpy as np, torch
from pathlib import Path
from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoModelForCausalLM, BitsAndBytesConfig
path=Path('assistant_annotations.json')
assert hashlib.sha256(path.read_bytes()).hexdigest()=='f9072e025e8f595ebe08472e895396e1a12456423c771ad7150a73c85b8db86d'
rows=json.loads(path.read_text(encoding='utf-8'))
torch.set_num_threads(4)
name='cross-encoder/nli-deberta-v3-small'; rev='fa2804872c3b4bd748f38c0185cc85775361e735'
tok=AutoTokenizer.from_pretrained(name,revision=rev)
nli=AutoModelForSequenceClassification.from_pretrained(name,revision=rev).eval()
pred=[]
for r in rows:
batch=tok(r['passage'],r['claim'],return_tensors='pt',truncation='only_first',max_length=512)
with torch.no_grad(): probabilities=torch.softmax(nli(**batch).logits,dim=-1)[0].tolist()
pred.append({'id':r['id'],'verdict':int(np.argmax(probabilities)==1),'probabilities':probabilities})
Path('assistant_nli.json').write_text(json.dumps(pred,indent=2),encoding='utf-8')
del nli, tok
name='Qwen/Qwen2.5-7B-Instruct'; rev='a09a35458c702b33eeacc393d103063234e8bc28'
tok=AutoTokenizer.from_pretrained(name,revision=rev)
cfg=BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type='nf4',bnb_4bit_compute_dtype=torch.float16)
judge=AutoModelForCausalLM.from_pretrained(name,revision=rev,quantization_config=cfg,device_map={'':0},dtype=torch.float16).eval()
output=[]
for r in rows:
prompt='Is the claim fully supported by the provided evidence? Reply only YES or NO.\nEvidence: '+r['passage']+'\nClaim: '+r['claim']+'\nVerdict:'
chat=tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=False,add_generation_prompt=True)
batch=tok(chat,return_tensors='pt').to('cuda')
with torch.no_grad(): generated=judge.generate(**batch,max_new_tokens=4,do_sample=False,pad_token_id=tok.eos_token_id)
raw=tok.decode(generated[0,batch['input_ids'].shape[1]:],skip_special_tokens=True).strip()
verdict=1 if raw.upper().startswith('YES') else 0 if raw.upper().startswith('NO') else None
output.append({'id':r['id'],'verdict':verdict,'raw':raw})
Path('assistant_judge.json').write_text(json.dumps(output,indent=2),encoding='utf-8')
def kappa(a,b):
observed=(a==b).mean(); expected=a.mean()*b.mean()+(1-a.mean())*(1-b.mean())
return (observed-expected)/(1-expected) if expected<1 else np.nan
for label, predictions in [('NLI',pred),('juez',output)]:
byid={x['id']:x for x in predictions}
valid=[r for r in rows if byid[r['id']]['verdict'] is not None]
a=np.array([r['assistant_label'] for r in valid]); b=np.array([byid[r['id']]['verdict'] for r in valid])
group=np.array([r['source_id'] for r in valid]); rng=np.random.default_rng(23); boot=[]
for _ in range(2000):
drawn=rng.choice(np.unique(group),len(np.unique(group)),replace=True)
ix=np.concatenate([np.flatnonzero(group==g) for g in drawn]); value=kappa(a[ix],b[ix])
if np.isfinite(value): boot.append(value)
print(label,'válidos',len(valid),'acuerdo',float((a==b).mean()),'kappa',kappa(a,b),'IC agrupado',np.quantile(boot,[.025,.975]))
del judge
torch.cuda.empty_cache()npm run lab and open the connection link.Local laboratory: multi-hop questions
The first cell downloads the first 20 HotpotQA validation questions and gathers their candidates in an index of 199 distinct titles with E5 embeddings. This is a benchmark-candidate index, not a search across all Wikipedia. It uses datasets, sentence-transformers, NumPy and PyTorch; data are saved in rag-eval.
import json
from datasets import load_dataset
from itertools import islice
from pathlib import Path
ds=load_dataset('hotpotqa/hotpot_qa','distractor',revision='1908d6afbbead072334abe2965f91bd2709910ab',split='validation',streaming=True)
rows=list(islice(ds,20))
Path('rag-eval').mkdir(parents=True,exist_ok=True)
with open('rag-eval/hotpot.json','w',encoding='utf-8') as f:json.dump(rows,f,ensure_ascii=False,indent=2)
print('HotpotQA',len(rows),'questions',flush=True)
import json,re,collections,numpy as np,torch
from sentence_transformers import SentenceTransformer
torch.set_num_threads(4)
rows=json.load(open('rag-eval/hotpot.json',encoding='utf-8'))
docs={}
for row in rows:
for title,sentences in zip(row['context']['title'],row['context']['sentences']):
docs.setdefault(title,title+' '+''.join(sentences))
titles=list(docs);texts=[docs[t] for t in titles]
model=SentenceTransformer('intfloat/multilingual-e5-small',revision='614241f622f53c4eeff9890bdc4f31cfecc418b3',device='cpu')
vectors=model.encode(['passage: '+x for x in texts],normalize_embeddings=True,convert_to_numpy=True,batch_size=16,show_progress_bar=True)
np.savez_compressed('rag-eval/index.npz',vectors=vectors)
with open('rag-eval/docs.json','w',encoding='utf-8') as f:json.dump({'titles':titles,'texts':texts},f,ensure_ascii=False,indent=2)
print('distinct titles',len(titles),'vectors',vectors.shape,flush=True)npm run lab and open the connection link.The second cell uses Qwen2.5-7B NF4, a hybrid BM25/E5 index and four passages per method. Iteration and tool variants make a second generated query; both have the same 8192-token cap but consume different actual tokens. It also compares one question with 5, 10 and 20 documents using RAG and direct reading. Finally it extracts relationships from eight documents, builds a graph and summarizes Louvain communities; inspect outputs because the model can invent relationships. This run explores two multi-hop questions and one long-context question; it does not demonstrate a general advantage. It requires CUDA, bitsandbytes, accelerate, networkx and the prepared index.
import json,re,collections,time,string,numpy as np,torch,networkx as nx
from sentence_transformers import SentenceTransformer
from transformers import AutoTokenizer,AutoModelForCausalLM,BitsAndBytesConfig
torch.set_num_threads(4)
root='rag-eval/'
rows=json.load(open(root+'hotpot.json',encoding='utf-8'))
docs=json.load(open(root+'docs.json',encoding='utf-8'));titles=docs['titles'];texts=docs['texts'];vectors=np.load(root+'index.npz')['vectors']
words=[re.findall(r'\w+',x.lower()) for x in texts];counts=[collections.Counter(w) for w in words]
df=collections.Counter(w for c in counts for w in c);N=len(texts);avg=np.mean([len(w) for w in words])
encoder=SentenceTransformer('intfloat/multilingual-e5-small',revision='614241f622f53c4eeff9890bdc4f31cfecc418b3',device='cpu')
def search(q,k,excluded=(),limit=None):
n=limit or N;lex=np.zeros(n)
for w in re.findall(r'\w+',q.lower()):
if w not in df:continue
idf=np.log(1+(N-df[w]+.5)/(df[w]+.5))
for i,c in enumerate(counts[:n]):
f=c[w]
if f:lex[i]+=idf*f*2.2/(f+1.2*(.25+.75*len(words[i])/avg))
v=encoder.encode(['query: '+q],normalize_embeddings=True,convert_to_numpy=True)[0];dense=vectors[:n]@v
score=np.zeros(n)
for order in (np.argsort(-lex,kind='stable'),np.argsort(-dense,kind='stable')):
for rank,i in enumerate(order,1):score[i]+=1/(60+rank)
return [int(i) for i in np.argsort(-score,kind='stable') if int(i) not in excluded][:k]
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,limit=32):
chat=tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=False,add_generation_prompt=True)
batch=tok(chat,return_tensors='pt').to('cuda');start=time.perf_counter()
with torch.no_grad():out=model.generate(**batch,max_new_tokens=limit,do_sample=False,pad_token_id=tok.eos_token_id)
answer=tok.decode(out[0,batch['input_ids'].shape[1]:],skip_special_tokens=True).strip()
return {'text':answer,'input_tokens':batch['input_ids'].shape[1],'output_tokens':out.shape[1]-batch['input_ids'].shape[1],'seconds':time.perf_counter()-start}
def evidence(ids):return '\n'.join(f'[{i+1}] '+ ' '.join(texts[j].split()[:100]) for i,j in enumerate(ids))
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'))
traces=[]
for case in (rows[1],rows[4]):
q=case['question'];gold=set(case['supporting_facts']['title'])
for method in ('single','iterative','react'):
if method=='single': ids=search(q,4);steps=[]
else:
first=search(q,2)
instruction=('Read the sources and propose a search query to find missing information for answering the question. Reply only with the query.' if method=='iterative' else 'You have a search tool. From these sources, choose the next search query needed to answer the question. Reply only with the query.')
mid=generate(instruction+'\nQuestion: '+q+'\nSources:\n'+evidence(first),40)
query=mid['text'];second=search(query,2,excluded=first);ids=first+second;steps=[{'ids':first,'next_query':query,'generation':mid},{'ids':second}]
final=generate('Answer the question using the sources. Give only a short answer.\nQuestion: '+q+'\nSources:\n'+evidence(ids),24)
tokens=sum(s.get('generation',{}).get('input_tokens',0)+s.get('generation',{}).get('output_tokens',0) for s in steps)+final['input_tokens']+final['output_tokens']
assert len(ids)==4 and tokens<=8192
trace={'method':method,'question':q,'reference':case['answer'],'ids':ids,'titles':[titles[i] for i in ids],
'steps':steps,'answer':final,'tokens':tokens,'gold_titles':sorted(gold),'recall':len(gold.intersection(titles[i] for i in ids))/len(gold),
'exact':norm(final['text'])==norm(case['answer'])}
traces.append(trace);print('multi',method,q[:35],trace['recall'],trace['exact'],tokens,flush=True)
with open(root+'multi.json','w',encoding='utf-8') as f:json.dump(traces,f,ensure_ascii=False,indent=2)
# Cortes de corpus anidados sobre la misma pregunta y el mismo modelo.
case=rows[0];q=case['question'];lengths=[]
for n in (5,10,20):
for method in ('todo','rag'):
ids=list(range(n)) if method=='todo' else search(q,4,limit=n)
result=generate('Answer the question using the sources. Give only a short answer.\nQuestion: '+q+'\nSources:\n'+evidence(ids),24)
row={'n':n,'method':method,'ids':ids,'answer':result,'exact':norm(result['text'])==norm(case['answer'])}
lengths.append(row);print('length',n,method,row['exact'],result['input_tokens'],flush=True)
with open(root+'long.json','w',encoding='utf-8') as f:json.dump(lengths,f,ensure_ascii=False,indent=2)
# Extracción libre; solo se agregan aristas que el modelo produzca como JSON válido.
graph=nx.Graph();extract=[]
for i in range(8):
prompt=('Extract up to three factual entity relations from the text. Return only JSON array of triples [subject, relation, object].\nText: '+ ' '.join(texts[i].split()[:100]))
result=generate(prompt,120);match=re.search(r'\[.*\]',result['text'],re.S)
try:triples=json.loads(match.group()) if match else []
except (ValueError,TypeError):triples=[]
clean=[]
for triple in triples:
if isinstance(triple,list) and len(triple)==3 and all(isinstance(x,str) and x.strip() for x in triple):
a,rel,b=triple;graph.add_edge(a.strip(),b.strip(),relation=rel.strip(),source=i);clean.append(triple)
extract.append({'doc':i,'raw':result,'triples':clean});print('graph',i,len(clean),flush=True)
communities=list(nx.community.louvain_communities(graph,seed=23)) if graph.number_of_edges() else []
summaries=[]
for c in communities:
edges=[f'{a} | {d["relation"]} | {b}' for a,b,d in graph.edges(data=True) if a in c and b in c]
result=generate('Summarize only these extracted relationships; do not invent facts.\n'+'\n'.join(edges),80)
summaries.append({'nodes':sorted(c),'edges':edges,'summary':result})
with open(root+'graph.json','w',encoding='utf-8') as f:json.dump({'extract':extract,'nodes':graph.number_of_nodes(),'edges':graph.number_of_edges(),'communities':summaries},f,ensure_ascii=False,indent=2)
print('graph communities',len(summaries),flush=True)npm run lab and open the connection link.Extraction produced 32 nodes, 26 edges and seven communities across eight documents. This last cell compares, using the same Qwen2.5-1.5B on CPU, answers based on four vector documents and all community summaries. Both variants answered the local question “Tim Burton”; both global answers were truncated at the generation limit. The lesson assistant manually judged both local answers complete and supported, and both global answers incomplete. The 7B judge agreed on all four after receiving question, answer and evidence. Its earlier calibration measured claim support, not summary completeness: these four judgments do not validate that task and this example does not measure a global advantage. The graph is undirected and does not implement hierarchical communities.
import json,re,time,torch,numpy as np
from sentence_transformers import SentenceTransformer
from transformers import AutoTokenizer,AutoModelForCausalLM
torch.set_num_threads(8)
root='rag-eval/'
docs=json.load(open(root+'docs.json',encoding='utf-8'))
graph=json.load(open(root+'graph.json',encoding='utf-8'))
summaries=[c['summary']['text'] for c in graph['communities']]
encoder=SentenceTransformer('intfloat/multilingual-e5-small',revision='614241f622f53c4eeff9890bdc4f31cfecc418b3',device='cpu')
documents=[' '.join(x.split()[:100]) for x in docs['texts'][:8]]
X=encoder.encode(['passage: '+x for x in documents],normalize_embeddings=True,convert_to_numpy=True)
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.float32).eval()
def generate(q,source):
prompt='Answer using only the sources. If unknown say UNKNOWN.\nSources:\n'+source+'\nQuestion: '+q+'\nAnswer:'
chat=tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=False,add_generation_prompt=True)
batch=tok(chat,return_tensors='pt');start=time.perf_counter()
with torch.no_grad():out=model.generate(**batch,max_new_tokens=60,do_sample=False,pad_token_id=tok.eos_token_id)
return {'text':tok.decode(out[0,batch['input_ids'].shape[1]:],skip_special_tokens=True),'tokens_in':batch['input_ids'].shape[1],
'tokens_out':out.shape[1]-batch['input_ids'].shape[1],'seconds':time.perf_counter()-start}
questions=[('global','What subjects and themes are present across these documents?'),('local','Who directed the film Ed Wood?')]
results=[]
for kind,q in questions:
v=encoder.encode(['query: '+q],normalize_embeddings=True,convert_to_numpy=True)[0]
ids=np.argsort(-(X@v),kind='stable')[:4].tolist()
for method,source in [('vector','\n'.join(documents[i] for i in ids)),('graph','\n'.join(summaries))]:
answer=generate(q,source)
results.append({'kind':kind,'method':method,'question':q,'ids':ids if method=='vector' else None,'source':source,'answer':answer})
with open(root+'graph_compare.json','w',encoding='utf-8') as f:json.dump(results,f,ensure_ascii=False,indent=2)
print(kind,method,repr(answer['text']),flush=True)npm run lab and open the connection link.This cell uses the three cited answers saved by the previous lesson. Qwen2.5-1.5B on CPU proposes claims and NLI checks them against the first cited source. In the real run it produced three claims; NLI labeled two entailment and one neutral. Decomposition, chosen source and verdict can fail; review each output. First run the previous generation laboratory to create rag-lab/generation.json.
import json,re,torch
from transformers import AutoTokenizer,AutoModelForCausalLM,AutoModelForSequenceClassification
torch.set_num_threads(8)
root='rag-eval/'
answers=json.load(open('rag-lab/generation.json',encoding='utf-8'))
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.float32).eval()
decomposed=[]
for r in answers:
prompt=('Rewrite the answer to the question as a list of independently checkable statements. '
'Use only facts in the answer; output one statement per line.\nQuestion: '+r['question']+'\nAnswer: '+r['answer'])
chat=tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=False,add_generation_prompt=True)
t=tok(chat,return_tensors='pt')
with torch.no_grad():out=model.generate(**t,max_new_tokens=64,do_sample=False,pad_token_id=tok.eos_token_id)
text=tok.decode(out[0,t['input_ids'].shape[1]:],skip_special_tokens=True).strip()
claims=[re.sub(r'^\s*(?:[-*]|\d+[.)])\s*','',s).strip() for s in text.splitlines() if s.strip()]
decomposed.append({'question':r['question'],'answer':r['answer'],'source':r['texts'][r['citations'][0]-1],'raw':text,'claims':claims})
print('decomposition',repr(text),flush=True)
del model
name='cross-encoder/nli-deberta-v3-small';rev='fa2804872c3b4bd748f38c0185cc85775361e735'
nt=AutoTokenizer.from_pretrained(name,revision=rev);nli=AutoModelForSequenceClassification.from_pretrained(name,revision=rev).eval()
for r in decomposed:
for claim in r['claims']:
t=nt(r['source'],claim,return_tensors='pt',truncation=True,max_length=512)
with torch.no_grad():p=torch.softmax(nli(**t).logits,dim=1)[0].tolist()
r.setdefault('verdicts',[]).append({'claim':claim,'probabilities':p,'label':['contradiction','entailment','neutral'][max(range(3),key=lambda i:p[i])]})
with open(root+'decomposition.json','w',encoding='utf8') as f:json.dump(decomposed,f,ensure_ascii=False,indent=2)
print('claims',sum(len(r['claims']) for r in decomposed),'labels',[[v['label'] for v in r['verdicts']] for r in decomposed],flush=True)npm run lab and open the connection link.The next cell reproduces the four completeness and support judgments. It retains the model’s original verdict and assistant’s manual reference: a truncated answer counts as incomplete. This is a binary criterion for this example, not exhaustive topic-coverage evaluation.
import json,torch
from pathlib import Path
from transformers import AutoTokenizer,AutoModelForCausalLM,BitsAndBytesConfig
graph=json.loads(Path('rag-eval/graph_compare.json').read_text(encoding='utf8'))
name='Qwen/Qwen2.5-7B-Instruct';rev='a09a35458c702b33eeacc393d103063234e8bc28'
tok=AutoTokenizer.from_pretrained(name,revision=rev)
cfg=BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type='nf4',bnb_4bit_compute_dtype=torch.float16)
judge=AutoModelForCausalLM.from_pretrained(name,revision=rev,quantization_config=cfg,device_map={'':0},dtype=torch.float16).eval()
evaluated=[]
for r in graph:
prompt=('Is the answer complete for the question and fully supported by the evidence? '
'An unfinished answer is not complete. Reply only YES or NO.\nEvidence: '+r['source']+
'\nQuestion: '+r['question']+'\nAnswer: '+r['answer']['text']+'\nVerdict:')
chat=tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=False,add_generation_prompt=True)
batch=tok(chat,return_tensors='pt').to('cuda')
with torch.no_grad(): out=judge.generate(**batch,max_new_tokens=4,do_sample=False,pad_token_id=tok.eos_token_id)
raw=tok.decode(out[0,batch['input_ids'].shape[1]:],skip_special_tokens=True).strip()
verdict=1 if raw.upper().startswith('YES') else 0 if raw.upper().startswith('NO') else None
evaluated.append({'kind':r['kind'],'method':r['method'],'judge_raw':raw,'judge':verdict,
'assistant_reference':0 if r['kind']=='global' else 1,
'reason':'truncada' if r['kind']=='global' else 'respuesta apoyada por el pasaje'})
Path('rag-eval/graph_assessment.json').write_text(json.dumps(evaluated,ensure_ascii=False,indent=2),encoding='utf8')
print(evaluated)
del judge
torch.cuda.empty_cache()npm run lab and open the connection link.Exercises
def context_recall(retrieved, gold):
pass
def context_precision_at_k(retrieved, grades, k):
pass
def faithfulness(claims, verdicts):
passdef iterative(question, retrieve, step, max_steps, k):
pass