Reranking, cited generation and faithfulness
Add a local cross-encoder to rerank candidates, design a generation prompt requiring citations and abstention, and evaluate answer correctness against the reference and faithfulness to context with an LLM judge calibrated against manual annotations.
After this lesson you can
- Integrate a cross-encoder and measure its nDCG gain against its latency cost.
- Design the prompt and citation format, including abstention without evidence.
- Implement claim-level faithfulness evaluation with an LLM judge and an NLI model.
- Measure judge agreement with 50 manually annotated answers.
Before you start
A citation is not yet proof
A search returns ten chunks and the model writes an answer with a citation. There are at least four distinct questions: was evidence among candidates, did it reach the context seen by the generator, is the answer correct, and is the claim supported by the cited passage? An answer can be true from the model’s prior knowledge without being supported by context. A citation can point to an existing document yet fail to justify the claim.
The previous lesson built retrievers and evaluated them on SciFact train, an external human-judged battery. Here we add the next system stage and evaluate it on the same battery and synthetic cards whose answers are known by construction. Once you have frozen the development set of your own collection, the protocol is the same: question source and judgments change, not measurement. You will calibrate the judge by manually annotating 50 answers with the lab tool.
The path has three boundaries. First a reranker scores query-passage pairs within a bounded set. Then a generator returns claims and references to visible chunks. Finally an evaluator checks each claim and we measure how closely its judgment matches a person’s. Each boundary has its own metric and failure mode.
From candidates to ranking: the cross-encoder
In an encoder such as BERT, query and passage are concatenated with separators and tokens from both can interact through self-attention. This joint interaction does not require a cross-attention layer between an encoder and decoder: cross-encoder here means processing the pair jointly. The potential advantage is that the model can compare specific words and relationships across both texts; the cost is rerunning the network for every pair. Reranking is therefore placed after cheaper initial retrieval.
Call the initial search’s first candidates . The reranker produces a permutation of that set and returns the first . If no chunk with evidence is in , changing order cannot introduce it. Candidate retrieval therefore sets a ceiling for any reranking that adds no documents. For a query with one relevant document, final hit is necessarily zero if that document is missing from the initial set. With multiple pieces of evidence, final recall cannot exceed candidate-set recall either, provided the same universe and relevance judgment are used.
Proof
Let be the relevant document set and the reranked result. Then , so for . The argument does not say initial order is optimal or that the cross-encoder will improve nDCG: it only bounds what cannot be retrieved if absent from candidates.
∎Cost and quality are measured together. Freeze the same candidate set and compare its initial order with cross-encoder order on the same questions and judgments. Report nDCG@10 before and after, per-query difference distribution, and latency per stage: retrieval, pair scoring, and context assembly. Request latency is not necessarily times a single pair’s measured latency: batching, lengths, and device change execution. Increasing can improve the coverage ceiling but also add work and distractors. The right budget depends on measurement in the deployment environment, not a fixed rule.
Truncation matters twice. If a candidate’s evidence is at a passage’s end and the cross-encoder tokenizer cuts it off, the model scores a different pair from the one you think you sent. If the query is truncated, the task also changes. Record maximum length, truncation policy, and model version. Do not interpret reranker score as a calibrated probability of truth: it only establishes an order under its model and training distribution. Ties need a stable rule for reproducible comparisons.
Where to put evidence
A good rank does not guarantee the generator uses evidence. When chunks are concatenated, a passage’s position changes with ordering and the length of every preceding chunk. A document near the start of the ranking can land in the middle of tokenized input if the prompt has long instructions; a chunk near the end can even fall outside the window. Position effects belong to a particular model, template, task, and length, not to RAG as a constant.
Liu and colleagues studied multi-document questions and key-value retrieval. In their experiments performance was often higher when relevant information appeared at the beginning or end than in the middle. This motivates your own test; it does not guarantee a U-shaped curve for this model, every distractor count, or every task. If local measurement does not show that shape, report what was observed.
In table 6 of the paper, for questions with 20 retrieved documents, GPT-3.5-Turbo achieved 75.8% accuracy when the answer document was first, 53.8% when it was tenth, and 63.2% when last. The table uses zero-based indices, so index 9 corresponds to tenth position. These figures belong to that model and evaluation, not Phi-3 or your corpus.
To isolate position, keep question, evidence, distractors, template, generation parameters, and budget constant, changing only the relevant passage’s location. Use multiple questions and permute distractors with a recorded seed. Count formatting errors, failures, and abstentions as well as wrong answers. Distractor count and total length should be recorded as separate variables: adding one can also increase prompt tokens. If both change, you cannot attribute a difference to position alone. Check token count and absence of truncation before interpreting the curve.
For each position divide correct answers by scheduled requests and retain the denominator and individual results. One repetition does not separate task and generation variation. Context position can interact with length, instructions, and distractors; report uncertainty intervals or at least counts and dispersion. Ranking by relevance, reducing redundancy, and reserving space for output are decisions evaluated against that battery, without turning a published average effect into a universal law.
A contract for citations and abstention
A practical format separates abstencion from a list of claims. Each claim contains its text and one or more citations with fragmento_id and a literal excerpt. The application assigns unique identifiers to chunks after selecting context and retains document version, page, and source offsets. The model does not invent paths or decide which tool may open them. A citation to an identifier outside the received context is invalid even if it exists elsewhere in the corpus: the generator did not have that passage as evidence in that request.
The contract must also resolve empty cases. An abstaining answer can return an empty claim list and a reason; an answer that asserts something must associate each claim with evidence. A JSON schema can require keys and types, as in the local service, but semantic checking comes afterward. The client validates that the answer is not truncated, citations point to existing IDs, and each literal quote is nonempty and appears exactly in its corresponding chunk. If you normalize whitespace or Unicode, retain a documented transformation and map to the original; otherwise you may accept a quote that does not match displayed text.
Consider an answer citing a real paragraph about an experiment and adding “the method always wins.” A literal checker can confirm the excerpt exists, but not that the generalization follows from the experiment. The claim-evidence link must be judged, including negations, units, temporal scope, and conditions. Two passages may be jointly required; checking each separately is not always enough. A reference text can itself be wrong or outdated: faithfulness to it does not guarantee external truth.
A working prompt separates instructions from documents and says: answer only based on chunks, cite every claim, and abstain if they are insufficient. Include the schema and usage examples where useful, but measure whether examples change behavior. Documents are data, not authoritative instructions. A delimiter helps present content but is not a security barrier: the application must separately validate permissions and tools. Answer faithfulness does not authorize an action either.
Claim-level faithfulness
Decomposition changes the metric. “The method is faster and more accurate” contains two claims: evidence may support only one. If a sentence contains a negation or date, do not remove it to make judging easier. Save claim, examined passages, label, and reason. An answer without evaluable claims has no denominator for ; record abstentions and extraction errors separately instead of automatically assigning perfect faithfulness. Per-answer average and the global fraction of supported claims also answer different questions: the latter weights long answers more heavily.
Faithfulness and correctness are two axes. A correct answer without contextual evidence may come from parametric memory; an answer faithful to a false document can be wrong in the world; a wrong unsupported answer fails both. Correctness evaluation needs an appropriate reference or external procedure. Faithfulness uses only context defined for that request. Do not change that context afterward by searching for a passage to justify an answer already generated.
The Ragas work proposes separate evaluation of retrieval and generation dimensions, including faithful use of context. This also connects to trustworthiness dimensions: one score does not summarize every failure mode. Automating a metric without a reference answer does not prove the automatic judge accurate: decomposition and support decisions can also fail. In particular, citing a real source and producing valid JSON are preliminary checks, not substitutes for an entailment judgment.
A natural language inference model, NLI, takes a premise and hypothesis. Here the premise is selected context or passage and the hypothesis is the claim. Its output can distinguish entailment, contradiction, and neutrality; neutral means the premise is insufficient, not that the claim is false. Check model-card labels and token limit because output indices vary by checkpoint. A model trained in another domain or language can get quantities, relationships, and references wrong. For evidence distributed across multiple chunks, evaluate the necessary set without exceeding the window and retain what the NLI actually saw after truncation.
An LLM judge can receive the same pair and return a structured label with the passage supporting its decision. Require format validation and log both full text and label; the judge must not execute instructions present in documents. The judge’s explanation is an audit clue, not proof of correctness. Compare NLI and judge on the same claims and inspect disagreements: a high mean can hide frequent errors on negations or numbers. Do not average their labels as if they were independent observations of truth.
Calibration against human review
Before using an LLM judge as a metric, prepare at least 50 answers for human annotation, selected without looking at which the judge fails. For every answer retain the question, exact context, output and version, and list of claims to judge. A person annotates support using guidelines fixed before seeing the judge’s verdict. Record disagreements, ambiguous claims, and guideline changes. If several claims come from the same answer, they are related observations: do not present them as independent samples for uncertainty estimation.
Annotation must define whether a reasonable conclusion needs external knowledge, whether a conflicting source within context invalidates support, and how to handle compound claims. For binary calibration fix beforehand how to map implicada, contradicha, and no determinable: for example, only implicada is supported. You can retain three classes if you have enough examples and clear guidelines; do not change the rule after seeing the result. A second independent review and disagreement-resolution procedure help distinguish judge error from task ambiguity.
Cohen’s kappa compares observed agreement with expected agreement under the two raters’ marginal proportions. If counts units with human label and judge label , , then
The formula requires and . If both raters always assign the same single category, and kappa is undefined even though observed agreement is complete. A frequent label can produce high raw agreement with modest kappa: report the matrix, proportions, and disagreements, not just one number. Kappa corrects according to a marginal expected-agreement model; it does not prove independence or absolute accuracy. Human annotation can contain errors and uncertainty can be considerable with 50 answers.
matrix = [[18, 12], [4, 16]] # filas: humano; columnas: juez
n = sum(sum(row) for row in matrix)
observed = (matrix[0][0] + matrix[1][1]) / n
expected = sum(sum(matrix[i]) * sum(row[i] for row in matrix) for i in range(2)) / n**2
print("n:", n, "acuerdo:", observed, "esperado:", expected)
print("kappa:", (observed - expected) / (1 - expected))Judge biases must be tested with paired controls. Zheng and colleagues describe position, length, and self-preference biases in answer judgments; their abstract reports over 80% agreement for strong judges in their preference comparisons. That result does not automatically calibrate a local citation-faithfulness judge. Swap two answers while holding the rest fixed and check whether preference changes; compare equivalent answers of different length without adding evidence; and record the model producing each answer. For a single-claim support judge, passage position is tested by permuting context, a different experiment from swapping two answers.
Deciding to publish a metric requires inspecting the confusion matrix and examples of false positives and negatives. A false support positive can hide an incorrect citation; a false negative can penalize valid evidence. Separate answers used to design and tune the judge prompt from those used to evaluate agreement. If judge, prompt, schema, or context changes, previous calibration does not automatically transfer. Do not report human kappa until real annotations exist.
Lab: rerank, generate, and audit
For every question the lab must retain previous candidates, ranks, cross-encoder scores, final context in order, stage times, structured answer, and evaluation decisions. Claims, citations, and labels must trace to the same document version. Position analysis is a separate paired test from reranking comparison. Faithfulness evaluation needs real answers and context; an artificial battery can test the validator but does not replace human annotation of 50 answers.
Rerank candidates and compare NLI
This first cell reconstructs the previous lesson’s protocol from official BEIR SciFact and original SciFact files, independent of files generated there. It uses only train. It retains 5183 documents and 505 queries with at least one human evidence item, excluding another 304 from relevance metrics. Both supporting and contradicting documents count as relevant because we seek evidence. This is an external training experiment, not your development set or an independent test.
First it obtains lexical and dense lists and fuses them by RRF with depth 100 and constant 60. Then the BGE cross-encoder reranks the first 20 candidates. It saves IDs, ranks, logits, lengths, and truncation indicators; for truncated pairs it also retains effective unpadded input IDs. The top-20 coverage printed counts queries with at least one annotated evidence item among those candidates; it is not recall@20 of all evidence. The cell records predict times for 20 pairs including tokenization; they exclude retrieval and sorting. They depend on GPU, load, and batch size: they are reranking-stage latency, not total request latency.
For NLI it takes annotated evidence sentences from original SciFact as premise and the corresponding claim as hypothesis. It uses nli-deberta-v3-small with pinned labels and revision. These pairs are not project-generated answers and do not calibrate an LLM judge. Reranker text comes from BEIR and NLI text from original SciFact; they do not always match character for character. Python with requests, numpy, CUDA PyTorch, sentence-transformers, and faiss-cpu is needed. Versions and hashes are saved; GPU memory is released between models and each stage prints peak memory. All files are written to a new directory within ~/atlas-lab/p05-l04 (change with ATLAS_LAB_DIR), whose path the cell prints at startup. The first run downloads both datasets, a few megabytes, and three model weights, about 2.1 GB in Hugging Face cache (0.47 GB embeddings, 1.1 GB reranker, and 0.55 GB NLI).
"""RRF, reranking y NLI en SciFact train, sin usar datos de p05-l02.
Reproduce el protocolo de p05-l03 a partir de fuentes oficiales. Solo lee
train; las anotaciones no son evaluaciones humanas del proyecto. Requiere
requests, numpy, torch CUDA, sentence-transformers y faiss-cpu.
"""
import csv
import gc
import hashlib
import importlib.metadata
import io
import json
import math
import os
from pathlib import Path
import re
import tarfile
import tempfile
import time
import traceback
import zipfile
from collections import Counter, defaultdict
import requests
import numpy as np
import torch
import faiss
from sentence_transformers import SentenceTransformer, CrossEncoder
from huggingface_hub import hf_hub_download
def lab_dir():
"""Directorio de trabajo del lector: ATLAS_LAB_DIR o ~/atlas-lab, subcarpeta p05-l04."""
base = Path(os.environ.get('ATLAS_LAB_DIR', Path.home() / 'atlas-lab')).expanduser()
folder = base / 'p05-l04'
folder.mkdir(parents=True, exist_ok=True)
return folder
OUT = Path(tempfile.mkdtemp(prefix='experimento-', dir=str(lab_dir())))
print('SALIDA', OUT, flush=True)
os.environ.setdefault('TOKENIZERS_PARALLELISM', 'false')
BEIR = 'https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/scifact.zip'
SCIFACT = 'https://scifact.s3-us-west-2.amazonaws.com/release/latest/data.tar.gz'
MODELS = {
'embedding': ('intfloat/multilingual-e5-small', '614241f622f53c4eeff9890bdc4f31cfecc418b3'),
'reranker': ('BAAI/bge-reranker-base', '2cfc18c9415c912f9d8155881c133215df768a70'),
'nli': ('cross-encoder/nli-deberta-v3-small', 'fa2804872c3b4bd748f38c0185cc85775361e735'),
}
def sha(data):
return hashlib.sha256(data).hexdigest()
def download(url):
r = requests.get(url, timeout=120)
r.raise_for_status()
return r.content
def tokens(text):
return re.findall(r'\w+', text.casefold(), flags=re.UNICODE)
class BM25:
def __init__(self, docs):
self.k1, self.b = 1.5, 0.75
self.lengths = [len(x) for x in docs]
self.avgdl = sum(self.lengths) / len(docs)
self.postings = defaultdict(list)
for i, doc in enumerate(docs):
for term, count in Counter(doc).items():
self.postings[term].append((i, count))
raw = {term: math.log(len(docs) - len(rows) + .5) - math.log(len(rows) + .5)
for term, rows in self.postings.items()}
avg = sum(raw.values()) / len(raw)
self.idf = {term: val if val >= 0 else .25 * avg for term, val in raw.items()}
def scores(self, query):
out = np.zeros(len(self.lengths), dtype=np.float64)
for term in query:
for i, frequency in self.postings.get(term, ()):
norm = self.k1 * (1 - self.b + self.b * self.lengths[i] / self.avgdl)
out[i] += self.idf[term] * frequency * (self.k1 + 1) / (frequency + norm)
return out
def rrf(first, second):
scores = defaultdict(float)
for ranking in (first[:100], second[:100]):
for rank, doc in enumerate(ranking, 1):
scores[doc] += 1 / (60 + rank)
return sorted(scores, key=lambda doc: (-scores[doc], doc))
def evaluate(order, relevant):
hits = [1 if doc in relevant else 0 for doc in order[:10]]
recall = sum(hits) / len(relevant)
dcg = sum(x / math.log2(i + 2) for i, x in enumerate(hits))
ideal = sum(1 / math.log2(i + 2) for i in range(min(10, len(relevant))))
return recall, dcg / ideal
def run_gpu(label, operation):
"""Ejecuta una etapa en GPU, informa su pico de memoria y libera la caché al terminar."""
torch.cuda.reset_peak_memory_stats()
try:
value = operation()
print('CUDA', label, 'pico de memoria (bytes):', torch.cuda.max_memory_allocated(), flush=True)
return value
finally:
gc.collect()
torch.cuda.empty_cache()
def main():
if not torch.cuda.is_available():
raise RuntimeError('Se requiere CUDA')
faiss.omp_set_num_threads(1)
torch.set_num_threads(1)
beir_bytes = download(BEIR)
original_bytes = download(SCIFACT)
with zipfile.ZipFile(io.BytesIO(beir_bytes)) as z:
def zread(suffix):
matches = [name for name in z.namelist() if name.endswith('/' + suffix)]
if len(matches) != 1:
raise ValueError('Fichero ausente o ambiguo: ' + suffix)
return z.read(matches[0])
train_bytes = zread('qrels/train.tsv')
all_qrels = defaultdict(dict)
for row in csv.DictReader(io.StringIO(train_bytes.decode('utf-8')), delimiter='\t'):
all_qrels[row['query-id']][row['corpus-id']] = int(row['score'])
corpus = [json.loads(line) for line in zread('corpus.jsonl').splitlines()]
queries = {}
for line in zread('queries.jsonl').splitlines():
item = json.loads(line)
if item['_id'] in all_qrels:
queries[item['_id']] = item['text']
with tarfile.open(fileobj=io.BytesIO(original_bytes), mode='r:gz') as t:
def tread(suffix):
found = [m for m in t.getmembers() if m.name.endswith('/' + suffix)]
if len(found) != 1:
raise ValueError('Fichero ausente o ambiguo: ' + suffix)
return t.extractfile(found[0]).read()
train_original = tread('claims_train.jsonl')
claims = {str(x['id']): x for x in (json.loads(line) for line in train_original.splitlines())}
source_corpus = {str(x['doc_id']): x for x in (json.loads(line) for line in tread('corpus.jsonl').splitlines())}
qrels = {qid: {doc for doc, score in docs.items() if score > 0 and claims[qid]['evidence'].get(doc)}
for qid, docs in all_qrels.items()}
qrels = {qid: relevant for qid, relevant in qrels.items() if relevant}
qids = sorted(qrels)
corpus.sort(key=lambda x: x['_id'])
ids = [x['_id'] for x in corpus]
texts = [(x.get('title', '') + '\n' + x.get('text', '')).strip() for x in corpus]
text_by_id = dict(zip(ids, texts))
if not all(q in queries for q in qids) or any(not rel.issubset(ids) for rel in qrels.values()):
raise ValueError('Falta consulta o documento')
print('Datos', len(ids), 'documentos y', len(qids), 'consultas con evidencia humana', flush=True)
lexical_index = BM25([tokens(x) for x in texts])
lexical = {}
for qid in qids:
score = lexical_index.scores(tokens(queries[qid]))
lexical[qid] = [ids[i] for i in np.lexsort((np.asarray(ids), -score))[:100]]
def embeddings():
model = None
try:
name, rev = MODELS['embedding']
model = SentenceTransformer(name, revision=rev, device='cuda')
docs = model.encode(['passage: ' + x for x in texts], batch_size=8, show_progress_bar=False,
normalize_embeddings=True, convert_to_numpy=True)
qs = model.encode(['query: ' + queries[q] for q in qids], batch_size=8, show_progress_bar=False,
normalize_embeddings=True, convert_to_numpy=True)
return np.ascontiguousarray(docs, dtype='float32'), np.ascontiguousarray(qs, dtype='float32')
finally:
if model is not None:
model.to('cpu')
del model
vectors, query_vectors = run_gpu('embedding', embeddings)
np.savez_compressed(OUT / 'vectores.npz', documentos=vectors, consultas=query_vectors)
exact = faiss.IndexFlatIP(vectors.shape[1]); exact.add(vectors)
_, neighbors = exact.search(query_vectors, 100)
initial = {q: rrf(lexical[q], [ids[i] for i in indices]) for q, indices in zip(qids, neighbors)}
del exact, vectors, query_vectors
def reranker():
model = None
try:
name, rev = MODELS['reranker']
model = CrossEncoder(name, revision=rev, max_length=512, device='cuda')
output = {}
audit = {}
elapsed = []
for query_number, qid in enumerate(qids, 1):
candidates = initial[qid][:20]
pairs = [(queries[qid], text_by_id[doc]) for doc in candidates]
encoded = model.tokenizer([p[0] for p in pairs], [p[1] for p in pairs],
padding=False, truncation=False)
lengths = [len(x) for x in encoded['input_ids']]
truncated_indices = [i for i, length in enumerate(lengths) if length > model.max_length]
effective_ids = {}
if truncated_indices:
effective = model.tokenizer([pairs[i][0] for i in truncated_indices],
[pairs[i][1] for i in truncated_indices],
padding=False, truncation=True, max_length=model.max_length)
effective_ids = dict(zip(truncated_indices, effective['input_ids']))
torch.cuda.synchronize(); begin = time.perf_counter_ns()
scores = model.predict(pairs, batch_size=8, show_progress_bar=False,
activation_fn=torch.nn.Identity())
torch.cuda.synchronize(); elapsed.append((time.perf_counter_ns() - begin) / 1e6)
ranked = sorted(zip(candidates, map(float, scores)), key=lambda item: (-item[1], item[0]))
output[qid] = [d for d, _ in ranked] + initial[qid][20:]
positions = {doc: rank for rank, (doc, _) in enumerate(ranked, 1)}
audit[qid] = [{'document_id': doc, 'rrf_position': i + 1, 'score_logit': float(score),
'rerank_position': positions[doc], 'pair_tokens': lengths[i],
'truncated': lengths[i] > model.max_length,
'effective_input_ids': effective_ids.get(i)}
for i, (doc, score) in enumerate(zip(candidates, scores))]
if query_number % 25 == 0:
print('Reranking', query_number, 'de', len(qids), flush=True)
return output, elapsed, audit
finally:
if model is not None:
model.model.to('cpu')
del model
reranked, rerank_ms, audit = run_gpu('cross_encoder_reranker', reranker)
rows = []
for qid in qids:
baseline_recall, baseline_ndcg = evaluate(initial[qid], qrels[qid])
rerank_recall, rerank_ndcg = evaluate(reranked[qid], qrels[qid])
rows.append({'query_id': qid, 'positives': len(qrels[qid]),
'baseline_recall10': baseline_recall, 'baseline_ndcg10': baseline_ndcg,
'rerank_recall10': rerank_recall, 'rerank_ndcg10': rerank_ndcg,
'positive_in_top20': bool(set(initial[qid][:20]) & qrels[qid]),
'candidates': audit[qid],
'rerank_ms': rerank_ms[len(rows)]})
with (OUT / 'reranking-por-consulta.jsonl').open('w', encoding='utf-8', newline='\n') as f:
for row in rows:
f.write(json.dumps(row, ensure_ascii=False) + '\n')
nli_examples = []
for qid in qids:
for docid in sorted(qrels[qid]):
evidence = claims[qid]['evidence'][docid]
indices = sorted({i for x in evidence for i in x['sentences']})
labels = {x['label'] for x in evidence}
if len(labels) != 1 or any(i >= len(source_corpus[docid]['abstract']) for i in indices):
raise ValueError('Anotación ambigua o índice fuera del abstract')
premise = ' '.join(source_corpus[docid]['abstract'][i] for i in indices)
nli_examples.append({'query_id': qid, 'doc_id': docid, 'premise': premise,
'claim': claims[qid]['claim'], 'human_label': next(iter(labels))})
def nli():
model = None
try:
name, rev = MODELS['nli']
model = CrossEncoder(name, revision=rev, max_length=512, device='cuda')
mapping = {int(i): label.lower() for i, label in model.model.config.id2label.items()}
pairs = [(x['premise'], x['claim']) for x in nli_examples]
tokenized = model.tokenizer([x[0] for x in pairs], [x[1] for x in pairs],
padding=False, truncation=False)
lengths = [len(x) for x in tokenized['input_ids']]
logits = model.predict(pairs, batch_size=8, show_progress_bar=False, apply_softmax=False,
activation_fn=torch.nn.Identity())
predictions = [mapping[int(i)] for i in np.argmax(logits, axis=1)]
return predictions, mapping, lengths, logits, model.max_length
finally:
if model is not None:
model.model.to('cpu')
del model
predictions, mapping, nli_lengths, nli_logits, nli_limit = run_gpu('nli', nli)
confusion = defaultdict(Counter)
nli_rows = []
for item, pred, length, logits in zip(nli_examples, predictions, nli_lengths, nli_logits):
confusion[item['human_label']][pred] += 1
nli_rows.append({'query_id': item['query_id'], 'doc_id': item['doc_id'],
'human_label': item['human_label'], 'nli_prediction': pred,
'pair_tokens': length, 'truncated': length > nli_limit,
'logits': [float(x) for x in logits]})
with (OUT / 'nli-por-par.jsonl').open('w', encoding='utf-8', newline='\n') as f:
for row in nli_rows:
f.write(json.dumps(row, ensure_ascii=False) + '\n')
model_metadata = {}
for label, (name, revision) in MODELS.items():
path = hf_hub_download(name, 'model.safetensors', revision=revision, local_files_only=True)
model_metadata[label] = {'model': name, 'revision': revision, 'weights_sha256': sha(Path(path).read_bytes())}
versions = {name: importlib.metadata.version(name) for name in
('numpy', 'torch', 'transformers', 'sentence-transformers', 'faiss-cpu')}
result = {'beir_sha256': sha(beir_bytes), 'scifact_sha256': sha(original_bytes),
'train_qrels_sha256': sha(train_bytes), 'claims_train_sha256': sha(train_original),
'corpus_documents': len(ids), 'questions_with_human_evidence': len(qids),
'excluded_without_human_evidence': len(all_qrels) - len(qids),
'relevant_pairs': len(nli_examples), 'models': model_metadata, 'versions': versions,
'candidate_depth': 20, 'rrf_depth': 100, 'rrf_offset': 60,
'rerank_truncated_pairs': sum(c['truncated'] for r in rows for c in r['candidates']),
'nli_truncated_pairs': sum(r['truncated'] for r in nli_rows),
'pair_token_limit': 512, 'truncation': 'tokenizer longest_first',
'rerank_score': 'logit sin activación; empate por ID ascendente',
'baseline_recall10': float(np.mean([r['baseline_recall10'] for r in rows])),
'baseline_ndcg10': float(np.mean([r['baseline_ndcg10'] for r in rows])),
'rerank_recall10': float(np.mean([r['rerank_recall10'] for r in rows])),
'rerank_ndcg10': float(np.mean([r['rerank_ndcg10'] for r in rows])),
'candidate_positive_coverage': float(np.mean([r['positive_in_top20'] for r in rows])),
'rerank_median_ms': float(np.median(rerank_ms)), 'rerank_p95_ms': float(np.percentile(rerank_ms, 95)),
'nli_label_mapping': mapping, 'nli_confusion': {k: dict(v) for k, v in confusion.items()},
'note': 'SciFact train externa; evidencia SUPPORT y CONTRADICT. No son respuestas generadas ni anotaciones de p05-l02; NLI es un predictor falible. Los tiempos dependen de la GPU y de su carga.'}
(OUT / 'resultado.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps(result, ensure_ascii=False, indent=2), flush=True)
if __name__ == '__main__':
try:
main()
except BaseException:
(OUT / 'error.txt').write_text(traceback.format_exc(), encoding='utf-8')
raisenpm run lab and open the connection link.Here is what you should obtain. In five runs of this cell on an 8 GB consumer GPU, metrics were identical: RRF order achieved recall@10 0.944554 and nDCG@10 0.863801; after reranking the first 20 with BGE, 0.956436 and 0.883678 respectively were observed. The nDCG improvement was 0.019877 absolute points over these 505 queries. At least one annotated positive occurred in the first 20 for 494 of 505 queries, so no reranking could succeed on the other 11. For 2175 of 10100 reranked pairs the tokenizer truncated input to the 512-token limit: we do not know how many cuts removed evidence. The result therefore combines model quality with this truncation policy.
Cost did vary between runs: median per-query predict for 20 pairs ranged from 667 to 847 ms and the 95th percentile from 738 to 905 ms, depending on card load. That is about 33 to 42 ms per pair with inputs up to 512 tokens and batches of 8. Your GPU’s figures will differ; compare the gain of about two hundredths of nDCG@10 against nearly a second added per query, which may not pay off for an interactive agent. Reranking fewer candidates, shortening passages to the relevant region, or using a smaller reranker are the levers; each is measured with the same table.
There was no NLI truncation in the 564 human-evidence pairs. The table shows observed counts, not probabilities:
| Human label | NLI entailment | NLI neutral | NLI contradiction |
|---|---|---|---|
| SUPPORT | 112 | 228 | 30 |
| CONTRADICT | 13 | 73 | 108 |
If matches are SUPPORT → entailment and CONTRADICT → contradiction, there are 220 matches out of 564; neutral predictions count as disagreement under that rule. SciFact human judgment and NLI classification are not identical tasks in every nuance. The result shows why NLI should not be treated as automatic truth for the agent.
Measure card position
The next probe creates fictional cards with unique identifiers and codes. For each distractor count it generates 12 cases and repeats each with the relevant card at the beginning, middle, and end, keeping other texts and question fixed. The 108 requests are ordered with a fixed seed. The model returns a code in JSON, compared with the pregenerated code; incidents count as failures in the proportion over scheduled requests and are recorded separately.
The cell uses phi3:mini through local Ollama. It requests context 4096, temperature 0, and server version 0.17.7, whose implementation allows truncate=false and shift=false: input exceeding the window is rejected or generation ends by length rather than silently shifting context. The cell classifies that ending as incomplete. prompt_eval_count may omit a cached prefix and is not alone proof of total size. Version, digest, conditions, every response, and stop reason are retained in a posicion-* directory within the same lab directory. With a later Ollama version the cell warns: check its source to confirm those parameters retain their meaning before comparing your figures with those below.
"""Sonda sintética reproducible de posición en phi3:mini; no es el corpus del proyecto.
Necesita requests y un servidor Ollama local con phi3:mini. Cada ficha es ficticia;
el código esperado se genera antes de llamar al modelo. Se conservan las respuestas,
errores y contadores de tokens para distinguir aciertos, fallos y ejecuciones inválidas.
"""
import datetime
import hashlib
import json
import math
import os
import random
from pathlib import Path
import tempfile
import requests
BASE = 'http://127.0.0.1:11434'
MODEL = 'phi3:mini'
DISTRACTORS = (4, 12, 24)
POSITIONS = ('principio', 'medio', 'final')
REPEATS = 12
CTX = 4096
PREDICT = 32
SEED = 20261028
MIN_OLLAMA = (0, 17, 7)
def lab_dir():
"""Directorio de trabajo del lector: ATLAS_LAB_DIR o ~/atlas-lab, subcarpeta p05-l04."""
base = Path(os.environ.get('ATLAS_LAB_DIR', Path.home() / 'atlas-lab')).expanduser()
folder = base / 'p05-l04'
folder.mkdir(parents=True, exist_ok=True)
return folder
def check_ollama(version):
"""Exige una versión con truncate y shift en /api/chat; avisa si no es la verificada."""
parts = tuple(int(x) for x in version.split('-')[0].split('.')[:3])
if parts < MIN_OLLAMA:
raise RuntimeError('Ollama ' + version + ' es anterior a 0.17.7: actualízalo antes de medir.')
if parts != MIN_OLLAMA:
print('Aviso: el código se verificó con Ollama 0.17.7; comprueba que truncate=false '
'y shift=false conservan su semántica en', version, flush=True)
def wilson(hits, n):
if not n:
return None
z = 1.959963984540054
p = hits / n
denominator = 1 + z*z/n
center = (p + z*z/(2*n))/denominator
margin = z*math.sqrt(p*(1-p)/n + z*z/(4*n*n))/denominator
return [center-margin, center+margin]
def make_prompt(case, distractors, position):
rng = random.Random(SEED + 1000*case + distractors)
identifiers = rng.sample(range(10000, 99999), distractors + 1)
codes = rng.sample(range(1000, 9999), distractors + 1)
entries = []
for ident, code in zip(identifiers, codes):
entries.append(
f'Registro {ident}. Código de archivo: {code}. '
'Esta ficha ficticia pertenece a una colección de ensayo. '
'Estado de revisión: cerrado. Área: archivo documental. '
'La identificación y el código son independientes del orden de las fichas. '
'No hay información sobre otros registros en esta ficha.'
)
target = entries.pop(0)
slot = {'principio': 0, 'medio': distractors // 2, 'final': distractors}[position]
entries.insert(slot, target)
prompt = ('Lee las fichas ficticias. Devuelve solo un objeto JSON con la clave "codigo" '
'y el código de archivo como cadena de cuatro dígitos. No adivines.\n\n' +
'\n\n'.join(entries) +
f'\n\n¿Cuál es el código de archivo del registro {identifiers[0]}?')
return prompt, str(codes[0]), slot + 1
def main():
session = requests.Session()
version = session.get(BASE + '/api/version', timeout=10).json()
check_ollama(version.get('version', '0'))
tags = session.get(BASE + '/api/tags', timeout=10).json()['models']
model = next((m for m in tags if m.get('name') == MODEL), None)
if model is None:
raise RuntimeError('Falta phi3:mini: instálalo con «ollama pull phi3:mini» antes de ejecutar')
show = session.post(BASE + '/api/show', json={'model': MODEL}, timeout=30)
show.raise_for_status()
model_info = show.json()
output = Path(tempfile.mkdtemp(prefix='posicion-', dir=str(lab_dir())))
print('Salida:', output, flush=True)
schema = {'type': 'object', 'properties': {'codigo': {'type': 'string'}},
'required': ['codigo'], 'additionalProperties': False}
metadata = {'timestamp_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(),
'ollama_version': version, 'tag': model, 'model_details': model_info.get('details'),
'model_info': model_info.get('model_info'),
'context': CTX, 'num_predict': PREDICT, 'temperature': 0,
'seed': SEED, 'repeats': REPEATS, 'distractors': DISTRACTORS,
'positions': POSITIONS, 'schema': schema,
'truncation_policy': 'truncate=false y shift=false en Ollama 0.17.7; prompt_eval_count puede excluir prefijos cacheados.',
'method': 'Fichas sintéticas; para cada número de distractores, 12 casos emparejados entre posiciones. Las incidencias no se consideran aciertos.'}
(output / 'meta.json').write_text(json.dumps(metadata, ensure_ascii=False, indent=2), encoding='utf-8')
rows = []
conditions = [(c, d, p) for c in range(REPEATS) for d in DISTRACTORS for p in POSITIONS]
random.Random(SEED + 1).shuffle(conditions)
for case, distractors, position in conditions:
prompt, expected, slot = make_prompt(case, distractors, position)
body = {'model': MODEL, 'stream': False, 'keep_alive': '2m', 'format': schema,
'truncate': False, 'shift': False,
'messages': [{'role': 'user', 'content': prompt}],
'options': {'temperature': 0, 'seed': SEED, 'num_ctx': CTX,
'num_batch': 128, 'num_predict': PREDICT}}
row = {'case': case, 'distractors': distractors, 'position': position,
'slot': slot, 'expected': expected,
'prompt_sha256': hashlib.sha256(prompt.encode('utf-8')).hexdigest()}
try:
response = session.post(BASE + '/api/chat', json=body, timeout=300)
response.raise_for_status()
result = response.json()
content = result.get('message', {}).get('content', '')
row.update({'response': content, 'done': result.get('done'),
'done_reason': result.get('done_reason'),
'prompt_eval_count': result.get('prompt_eval_count'),
'eval_count': result.get('eval_count')})
try:
parsed = json.loads(content)
except json.JSONDecodeError:
parsed = None
if not isinstance(parsed, dict) or set(parsed) != {'codigo'} or not isinstance(parsed['codigo'], str):
row.update(status='formato_invalido', hit=False)
elif result.get('done_reason') != 'stop':
row.update(status='salida_incompleta', hit=False)
elif not isinstance(result.get('prompt_eval_count'), int):
row.update(status='contador_ausente', hit=False)
else:
row.update(status='ok', hit=parsed['codigo'] == expected)
except (requests.RequestException, ValueError, KeyError) as exc:
row.update(status='error', hit=False, error=str(exc))
rows.append(row)
with (output / 'casos.jsonl').open('a', encoding='utf-8', newline='\n') as file:
file.write(json.dumps(row, ensure_ascii=False) + '\n')
print(f'{len(rows)}/{len(conditions)} {distractors} {position}: {row["status"]}, acierto={row["hit"]}', flush=True)
summary = []
for d in DISTRACTORS:
for p in POSITIONS:
group = [r for r in rows if r['distractors'] == d and r['position'] == p]
valid = [r for r in group if r['status'] == 'ok']
hits = sum(r['hit'] for r in valid)
summary.append({'distractors': d, 'position': p, 'attempts': len(group),
'valid': len(valid), 'invalid': len(group)-len(valid),
'hits': hits, 'accuracy_valid': hits / len(valid) if valid else None,
'accuracy_programmed': hits / len(group) if group else None,
'wilson_95_programmed': wilson(hits, len(group)),
'wilson_95_valid': wilson(hits, len(valid))})
report = {'metadata': metadata, 'summary': summary, 'cases_sha256': hashlib.sha256((output / 'casos.jsonl').read_bytes()).hexdigest()}
(output / 'resumen.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print('Salida:', output, flush=True)
print(json.dumps(report, ensure_ascii=False, indent=2), flush=True)
if __name__ == '__main__':
main()npm run lab and open the connection link.In a reference run with the phi3:mini digest shown in the figure, there were no incidents and hits over 12 requests per position were as follows. With temperature 0 and the same seed you should obtain equal or very close figures; differences of one or two answers are possible because GPU generation is not exactly deterministic.
| Distractor cards | Beginning | Middle | End |
|---|---|---|---|
| 4 | 12/12 | 5/12 | 8/12 |
| 12 | 12/12 | 12/12 | 12/12 |
| 24 | 12/12 | 12/12 | 11/12 |
With four distractors the middle performed worse in this sample; with 12 that difference did not appear and with 24 only one answer at the end failed. There is no general U-curve for all conditions. These are few synthetic cases with one model, template, and seed; the Wilson intervals shown describe each proportion under a binomial model and do not themselves prove differences between paired positions. Distractor count also changes length, and does not show longer context improves retrieval.
Generate citations and prepare annotation
This cell generates 50 questions about fictional cards; in ten the card that would answer the question is omitted by construction. It uses the same phi3:mini to generate and judge, so errors can be correlated. The specific schema calls each citation identifier id, equivalent to fragmento_id above. The validator checks the complete schema, termination, abstention consistency, and literal occurrence of each quote. It does not demonstrate semantic entailment.
For every string the generator presents as a claim, the LLM judge and NLI receive the full context and that string. The program does not guarantee the string is atomic or separately check that each particular citation supports it. It saves results, including decisions on contract-violating answers for diagnosis, and separates comparisons on accepted answers. NLI uses CPU and a model trained in English on Spanish strings: its labels are exploratory, not human judgment. Effective NLI tokens and truncations are logged. The cell needs requests, jsonschema, numpy, PyTorch, and sentence-transformers, plus Ollama 0.17.7 or later with local phi3:mini. It writes to a citas-* directory in the lab directory.
"""Generación y juez local en 50 casos sintéticos; nunca fabrica anotaciones humanas.
El archivo para revisión humana omite deliberadamente los veredictos del juez.
La anotación y el cálculo de kappa se ejecutan después, como operaciones separadas:
python citas.py anotar RUTA (herramienta de anotación en terminal)
python citas.py evaluar-anotaciones RUTA (matriz, acuerdo y kappa)
"""
import csv
import datetime
import hashlib
import json
import os
import random
import sys
import tempfile
from pathlib import Path
import requests
from jsonschema import ValidationError, validate
BASE = 'http://127.0.0.1:11434'
MODEL = 'phi3:mini'
NLI_MODEL = 'cross-encoder/nli-deberta-v3-small'
NLI_REVISION = 'fa2804872c3b4bd748f38c0185cc85775361e735'
SEED = 20261028
MIN_OLLAMA = (0, 17, 7)
def lab_dir():
"""Directorio de trabajo del lector: ATLAS_LAB_DIR o ~/atlas-lab, subcarpeta p05-l04."""
base = Path(os.environ.get('ATLAS_LAB_DIR', Path.home() / 'atlas-lab')).expanduser()
folder = base / 'p05-l04'
folder.mkdir(parents=True, exist_ok=True)
return folder
def check_ollama(version):
"""Exige una versión con truncate y shift en /api/chat; avisa si no es la verificada."""
parts = tuple(int(x) for x in version.split('-')[0].split('.')[:3])
if parts < MIN_OLLAMA:
raise RuntimeError('Ollama ' + version + ' es anterior a 0.17.7: actualízalo antes de medir.')
if parts != MIN_OLLAMA:
print('Aviso: el código se verificó con Ollama 0.17.7; comprueba que truncate=false '
'y shift=false conservan su semántica en', version, flush=True)
def citation_check(claims, contexts):
if not isinstance(claims, list) or not claims:
return False
for claim in claims:
if not isinstance(claim, dict) or not isinstance(claim.get('text'), str) or not claim['text'].strip():
return False
citations = claim.get('citations')
if not isinstance(citations, list) or not citations:
return False
for citation in citations:
if not isinstance(citation, dict):
return False
ident, quote = citation.get('id'), citation.get('quote')
if not isinstance(ident, str) or ident not in contexts:
return False
if not isinstance(quote, str) or not quote.strip() or quote not in contexts[ident]:
return False
return True
def chat(session, prompt, schema):
body = {'model': MODEL, 'stream': False, 'format': schema, 'keep_alive': '2m',
'truncate': False, 'shift': False,
'messages': [{'role': 'user', 'content': prompt}],
'options': {'temperature': 0, 'seed': SEED, 'num_ctx': 4096,
'num_batch': 128, 'num_predict': 192}}
response = session.post(BASE + '/api/chat', json=body, timeout=300)
response.raise_for_status()
result = response.json()
content = result.get('message', {}).get('content', '')
data = json.loads(content)
return {'text': content, 'parsed': data, 'done_reason': result.get('done_reason'),
'prompt_tokens': result.get('prompt_eval_count'), 'output_tokens': result.get('eval_count'),
'total_duration_ns': result.get('total_duration'), 'load_duration_ns': result.get('load_duration'),
'prompt_eval_duration_ns': result.get('prompt_eval_duration'), 'eval_duration_ns': result.get('eval_duration')}
def sample_cases():
rng = random.Random(SEED)
ids = rng.sample(range(10000, 99999), 150)
codes = rng.sample(range(1000, 9999), 150)
for i in range(50):
records = list(zip(ids[3*i:3*i+3], codes[3*i:3*i+3]))
withheld = i % 5 == 0
question_id = records[0][0]
visible = records[1:] if withheld else records
rng.shuffle(visible)
contexts = {f'f{j+1}': f'Ficha ficticia {ident}: código de archivo {code}.'
for j, (ident, code) in enumerate(visible)}
yield {'id': f'caso-{i+1:03d}', 'question': f'¿Cuál es el código de la ficha {question_id}?',
'contexts': contexts, 'answerable_by_construction': not withheld}
def kappa(pairs):
n = len(pairs)
if n == 0:
return None
matrix = [[0, 0], [0, 0]]
for human, judge in pairs:
matrix[human][judge] += 1
observed = (matrix[0][0] + matrix[1][1]) / n
expected = sum(sum(matrix[i]) * (matrix[0][i] + matrix[1][i]) for i in (0, 1)) / n**2
return {'n': n, 'matrix_rows_human_columns_judge': matrix,
'category_order': ['no respaldada', 'respaldada'], 'observed': observed,
'expected': expected, 'kappa': (observed - expected) / (1 - expected) if expected < 1 else None}
def fingerprint(row):
encoded = json.dumps(row, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode('utf-8')
return hashlib.sha256(encoded).hexdigest()
def as_contexts(record):
"""Fragmentos como diccionario id -> texto: dict en las fichas, lista de dicts en el pipeline."""
contexts = record['contexts']
return contexts if isinstance(contexts, dict) else {c['id']: c['text'] for c in contexts}
def response_label(row):
"""Etiqueta del juez por respuesta: 1 si respalda todas sus cadenas, 0 si alguna no, None si falta un juicio válido."""
if 'judge_response_label' in row:
return row['judge_response_label']
claims = row.get('claims') or []
if not claims or not all(c.get('valid') for c in claims):
return None
return int(all(c['generation']['parsed']['respaldo'] for c in claims))
def evaluate_manual(folder):
folder = Path(folder)
public = [json.loads(line) for line in (folder / 'para-anotar.jsonl').read_text(encoding='utf-8').splitlines()]
public_by_id = {r['id']: r for r in public}
human = {}
with (folder / 'anotaciones.csv').open(encoding='utf-8', newline='') as f:
for row in csv.DictReader(f):
ident, label = row['id'], row['humano'].strip()
if (ident in human or label not in ('0', '1', 'NA') or not row['revisor'].strip() or
ident not in public_by_id or row['huella'] != fingerprint(public_by_id[ident])):
raise ValueError('Cada ID y huella deben coincidir, y revisor y etiqueta 0, 1 o NA deben estar completos.')
human[ident] = label
if len(public) < 50 or len(public_by_id) != len(public) or set(human) != set(public_by_id):
raise ValueError('Se requieren al menos 50 respuestas (en el pipeline, CASES_PER_LABEL = 25) '
'y una anotación humana por cada ID.')
automatic_rows = [json.loads(line) for line in (folder / 'juicios.jsonl').read_text(encoding='utf-8').splitlines()]
automatic = {r['id']: r for r in automatic_rows}
if len(automatic) != len(automatic_rows) or set(automatic) != set(public_by_id):
raise ValueError('Los juicios y respuestas deben pertenecer a la misma ejecución.')
if any(automatic[i].get('response_sha256') != fingerprint(public_by_id[i]) for i in public_by_id):
raise ValueError('Una huella del juicio no coincide con su respuesta.')
pairs = []
for ident, label in human.items():
verdict = response_label(automatic[ident])
if label != 'NA' and verdict in (0, 1) and public_by_id[ident].get('literal_contract_valid') is True:
pairs.append((int(label), verdict))
files = ['para-anotar.jsonl', 'juicios.jsonl', 'anotaciones.csv']
hashes = {name: hashlib.sha256((folder / name).read_bytes()).hexdigest() for name in files}
return {'responses_reviewed': len(human), 'eligible_pairs': len(pairs), 'sha256': hashes,
'excluded_na_judge_error_or_invalid_contract': len(human)-len(pairs), 'agreement': kappa(pairs)}
def annotate(folder):
"""Anotación ciega en terminal: muestra pregunta, fragmentos y respuesta, nunca juicios.jsonl.
Sirve para las carpetas citas-* de esta celda y pipeline-* de la siguiente.
Guarda tras cada decisión, de modo que puedes interrumpir y continuar más tarde.
"""
folder = Path(folder)
guide = json.loads((folder / 'meta.json').read_text(encoding='utf-8'))['manual_guide']
public = [json.loads(line) for line in (folder / 'para-anotar.jsonl').read_text(encoding='utf-8').splitlines()]
path = folder / 'anotaciones.csv'
with path.open(encoding='utf-8', newline='') as f:
rows = list(csv.DictReader(f))
reviewer = input('Tu nombre o iniciales: ').strip()
print('\nGuía:', guide)
for row, record in zip(rows, public):
if row['humano'].strip():
continue
if row['id'] != record['id'] or row['huella'] != fingerprint(record):
raise ValueError('anotaciones.csv no corresponde a para-anotar.jsonl')
print('\n' + '=' * 60, '\n' + record['id'], record.get('question') or record.get('claim'))
for key, text in as_contexts(record).items():
print(f' [{key}] {text}')
parsed = record.get('generation', {}).get('parsed')
print('Respuesta:', json.dumps(parsed, ensure_ascii=False, indent=1))
label = ''
while label not in ('0', '1', 'NA', 'q'):
label = input('Etiqueta (1 respaldada, 0 no respaldada, NA, q para salir): ').strip()
if label == 'q':
break
row.update(revisor=reviewer, humano=label, nota=input('Nota (opcional): ').strip())
with path.open('w', encoding='utf-8', newline='') as f:
writer = csv.DictWriter(f, fieldnames=['id', 'huella', 'revisor', 'humano', 'nota'])
writer.writeheader()
writer.writerows(rows)
print('Anotadas', sum(bool(r['humano'].strip()) for r in rows), 'de', len(rows))
def main():
session = requests.Session()
version = session.get(BASE + '/api/version', timeout=10).json()
check_ollama(version.get('version', '0'))
tags = session.get(BASE + '/api/tags', timeout=10).json()['models']
model = next((m for m in tags if m.get('name') == MODEL), None)
if model is None:
raise RuntimeError('Instala phi3:mini en Ollama («ollama pull phi3:mini») antes de ejecutar.')
output = Path(tempfile.mkdtemp(prefix='citas-', dir=str(lab_dir())))
print('Salida:', output, flush=True)
citation = {'type': 'object', 'properties': {'id': {'type': 'string'}, 'quote': {'type': 'string'}},
'required': ['id', 'quote'], 'additionalProperties': False}
claim = {'type': 'object', 'properties': {'text': {'type': 'string'},
'citations': {'type': 'array', 'items': citation}},
'required': ['text', 'citations'], 'additionalProperties': False}
answer_schema = {'type': 'object', 'properties': {'abstencion': {'type': 'boolean'},
'afirmaciones': {'type': 'array', 'items': claim}},
'required': ['abstencion', 'afirmaciones'], 'additionalProperties': False}
judge_schema = {'type': 'object', 'properties': {'respaldo': {'type': 'boolean'}, 'motivo': {'type': 'string'}},
'required': ['respaldo', 'motivo'], 'additionalProperties': False}
meta = {'model': MODEL, 'model_tag': model, 'version': version, 'seed': SEED,
'created_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(),
'scenario': '50 fichas sintéticas, de las cuales 10 carecen de evidencia por construcción',
'judge': 'mismo modelo que genera; sin calibración humana',
'manual_guide': 'Para cada respuesta: NA si se abstiene sin afirmaciones, si alguna cadena no es declarativa o si no puede juzgarse; en otro caso 1 si todas las afirmaciones están respaldadas por el contexto y 0 si alguna no lo está. No consultar juicios.jsonl antes de anotar.'}
(output / 'meta.json').write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding='utf-8')
annotation_rows = []
for case in sample_cases():
contexts = case['contexts']
material = '\n'.join(f'[{k}] {v}' for k, v in contexts.items())
prompt = ('Responde solo con JSON. Usa exclusivamente los fragmentos, sin conocimiento externo. '
'Cada afirmación debe tener citations con id y quote copiado literalmente del fragmento. '
'Si no hay evidencia, devuelve abstencion=true y afirmaciones=[].\n\n'
f'Fragmentos:\n{material}\n\nPregunta: {case["question"]}')
response_record = {'id': case['id'], 'question': case['question'], 'contexts': contexts}
judge_record = {'id': case['id'], 'claim_judgments': [], 'judge_response_label': None}
try:
answer = chat(session, prompt, answer_schema)
response_record['generation'] = answer
parsed = answer['parsed']
try:
validate(instance=parsed, schema=answer_schema)
schema_valid = True
except ValidationError:
schema_valid = False
claims = parsed.get('afirmaciones') if isinstance(parsed, dict) else None
abstention = parsed.get('abstencion') if isinstance(parsed, dict) else None
complete = answer['done_reason'] == 'stop'
contract = (complete and schema_valid and isinstance(abstention, bool) and isinstance(claims, list) and
((abstention and not claims) or (not abstention and citation_check(claims, contexts))))
response_record['literal_contract_valid'] = bool(contract)
if complete and isinstance(claims, list):
for item in claims:
if not isinstance(item, dict) or not isinstance(item.get('text'), str):
judge_record['claim_judgments'].append({'status': 'afirmacion_invalida'})
continue
judge_prompt = ('Juzga si el contexto respalda la afirmación por completo. '
'No uses conocimiento externo. Devuelve JSON con respaldo booleano y motivo.\n\n'
f'Contexto:\n{material}\n\nAfirmación: {item["text"]}')
try:
result = chat(session, judge_prompt, judge_schema)
verdict = result['parsed']
try:
validate(instance=verdict, schema=judge_schema)
judge_schema_valid = True
except ValidationError:
judge_schema_valid = False
valid = (result['done_reason'] == 'stop' and judge_schema_valid)
judge_record['claim_judgments'].append({'status': 'ok' if valid else 'invalido', 'result': result})
except (requests.RequestException, ValueError, KeyError) as exc:
judge_record['claim_judgments'].append({'status': 'error', 'error': str(exc)})
decisions = judge_record['claim_judgments']
if decisions and all(x['status'] == 'ok' for x in decisions):
judge_record['judge_response_label'] = int(all(x['result']['parsed']['respaldo'] for x in decisions))
except (requests.RequestException, ValueError, KeyError) as exc:
response_record['generation_error'] = str(exc)
judge_record['response_sha256'] = fingerprint(response_record)
with (output / 'para-anotar.jsonl').open('a', encoding='utf-8', newline='\n') as f:
f.write(json.dumps(response_record, ensure_ascii=False) + '\n')
with (output / 'juicios.jsonl').open('a', encoding='utf-8', newline='\n') as f:
f.write(json.dumps(judge_record, ensure_ascii=False) + '\n')
annotation_rows.append({'id': case['id'], 'huella': fingerprint(response_record),
'revisor': '', 'humano': '', 'nota': ''})
print(f'{len(annotation_rows)}/50 {case["id"]}: contrato literal={response_record.get("literal_contract_valid")}', flush=True)
with (output / 'anotaciones.csv').open('w', encoding='utf-8', newline='') as f:
writer = csv.DictWriter(f, fieldnames=['id', 'huella', 'revisor', 'humano', 'nota'])
writer.writeheader()
writer.writerows(annotation_rows)
responses = [json.loads(line) for line in (output / 'para-anotar.jsonl').read_text(encoding='utf-8').splitlines()]
judged = [json.loads(line) for line in (output / 'juicios.jsonl').read_text(encoding='utf-8').splitlines()]
pairs, pair_ids = [], []
for row in responses:
generation = row.get('generation', {})
answer = generation.get('parsed', {}) if isinstance(generation, dict) else {}
claims = answer.get('afirmaciones', []) if isinstance(answer, dict) else []
if generation.get('done_reason') != 'stop' or not isinstance(claims, list):
continue
premise = '\n'.join(row['contexts'].values())
for index, claim_item in enumerate(claims):
if isinstance(claim_item, dict) and isinstance(claim_item.get('text'), str):
pairs.append((premise, claim_item['text']))
pair_ids.append((row['id'], index, row.get('literal_contract_valid') is True))
nli_rows = []
if pairs:
import numpy as np
import torch
from sentence_transformers import CrossEncoder
torch.set_num_threads(1)
nli = CrossEncoder(NLI_MODEL, revision=NLI_REVISION, max_length=512, device='cpu')
labels = nli.model.config.id2label
print('Etiquetas NLI:', labels, flush=True)
token_counts = [len(nli.tokenizer(a, b, truncation=False)['input_ids']) for a, b in pairs]
effective_ids = [nli.tokenizer(a, b, truncation=True, max_length=512)['input_ids'] for a, b in pairs]
logits = np.asarray(nli.predict(pairs, batch_size=8, apply_softmax=False, show_progress_bar=False))
if logits.shape != (len(pairs), 3) or any(str(labels.get(i, '')).lower() != name for i, name in enumerate(('contradiction', 'entailment', 'neutral'))):
raise ValueError('La salida o el orden de etiquetas NLI no coincide con el contrato esperado.')
for (ident, index, accepted), values, token_count, input_ids in zip(pair_ids, logits, token_counts, effective_ids):
label = str(labels[int(np.argmax(values))]).lower()
nli_rows.append({'id': ident, 'claim_index': index, 'logits': values.tolist(), 'label': label,
'input_tokens_before_truncation': token_count, 'truncated': token_count > 512,
'effective_input_ids': input_ids, 'truncation_policy': 'longest_first, max_length=512',
'response_contract_valid': accepted,
'supported_binary': int(label == 'entailment')})
del nli, logits
with (output / 'nli.jsonl').open('w', encoding='utf-8', newline='\n') as f:
for row in nli_rows:
f.write(json.dumps(row, ensure_ascii=False) + '\n')
judge_by_id = {row['id']: row['claim_judgments'] for row in judged}
comparable, matching, accepted_comparable, accepted_matching = 0, 0, 0, 0
for row in nli_rows:
entries = judge_by_id.get(row['id'], [])
if row['claim_index'] < len(entries) and entries[row['claim_index']].get('status') == 'ok':
comparable += 1
same = int(int(entries[row['claim_index']]['result']['parsed']['respaldo']) == row['supported_binary'])
matching += same
if row['response_contract_valid']:
accepted_comparable += 1
accepted_matching += same
summary = {'cases': len(responses), 'without_evidence_by_construction': sum(not x['answerable_by_construction'] for x in sample_cases()),
'literal_contract_valid': sum(x.get('literal_contract_valid') is True for x in responses),
'generation_errors': sum('generation_error' in x for x in responses),
'responses_with_judge_label': sum(x['judge_response_label'] in (0, 1) for x in judged),
'accepted_responses_with_judge_label': sum(x.get('literal_contract_valid') is True and y['judge_response_label'] in (0, 1) for x, y in zip(responses, judged)),
'nli_claims': len(nli_rows), 'nli_model': NLI_MODEL, 'nli_revision': NLI_REVISION,
'nli_truncated_pairs': sum(x['truncated'] for x in nli_rows),
'nli_vs_judge_comparable_claims': comparable, 'nli_vs_judge_matching_claims': matching,
'nli_vs_judge_accepted_claims': accepted_comparable, 'nli_vs_judge_accepted_matching': accepted_matching,
'nli_warning': 'Modelo entrenado en inglés aplicado a frases en español: exploración, no validación humana.',
'human_annotations': 0,
'note': 'No hay kappa humana hasta que una persona complete anotaciones.csv.'}
(output / 'resumen.json').write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding='utf-8')
print('Salida:', output, flush=True)
print(json.dumps(summary, ensure_ascii=False, indent=2), flush=True)
if __name__ == '__main__':
if len(sys.argv) == 3 and sys.argv[1] == 'anotar':
annotate(sys.argv[2])
elif len(sys.argv) == 3 and sys.argv[1] == 'evaluar-anotaciones':
print(json.dumps(evaluate_manual(sys.argv[2]), ensure_ascii=False, indent=2))
else:
main()npm run lab and open the connection link.In five reference runs, all 50 literal contracts were valid, no generation errors occurred, and the model abstained exactly on the ten questions without a card. The other 40 answers each contained one string. In four runs the judge labeled all 40 and agreed with NLI on 27; in the fifth it returned an invalid label and agreed on 26 of 39. This reminds us temperature 0 does not guarantee identical outputs. That NLI-judge agreement is neither accuracy nor human agreement. Inspecting outputs reveals an instructive failure: in cases 032 and 033 the model returned the question itself, “¿Cuál es el código de la ficha 91119?”, as a supposed claim, with a correct literal quote; they passed literal checking and the judge marked them supported. Satisfying the contract does not guarantee a relevant answer or declarative claim, so the annotation guide assigns NA to nondeclarative strings.
The para-anotar.jsonl file contains question, context, and answer without the automatic verdict. CSV anotaciones.csv is created with blank labels and reviewer, one fingerprint per answer, and space for notes. The annotation tool is the cell itself run in a terminal: copy it to citas.py and run python citas.py anotar RUTA, using the path printed by the run. It displays each question, its chunks, and answer, never juicios.jsonl, applies the meta.json guide, saves after each decision, and allows stopping and resuming. Annotate all 50 before seeing any judge verdict. Then python citas.py evaluar-anotaciones RUTA requires all 50 annotations, verifies IDs and fingerprints, records file hashes, and prints the matrix, observed and expected agreement, and kappa. It excludes NA cases, judge errors, and invalid-contract responses and reports remaining pairs: 50 reviewed answers do not guarantee 50 eligible pairs.
What to expect: on these cards the task is almost trivial. The ten abstentions will be NA, as will the two questions returned as claims. In all five reference runs the judge marked all labeled answers supported, whereas NLI, trained in English and applied to Spanish strings, returned 27 entailments, 12 contradictions, and 1 neutral over the same 40 strings. If your judge behaves likewise, its matrix column is constant: then , expected agreement is , and kappa is exactly 0 if you annotate any answer as unsupported, or undefined () if all are supported, even with high raw agreement. This is not an annotation failure: a judge that never says “no” discriminates nothing, and useful calibration needs real errors, such as the next cell’s SciFact pipeline or your development set. Declaring a reviewer in the file does not itself prove who annotated; if possible, ask a second person to independently annotate the same 50.
Connect reranker to generator
This cell links candidates and logits saved by the first cell of this lesson with the local generator. Run it after that cell: it uses the directory created there in OUT, checks source fingerprints, and reconstructs official text. If run separately, P05_L04_RERANK_OUTPUT must point to the directory printed by reranking. It needs no files from another lesson.
Before generation, it uses a seed to select 20 SciFact train claims: ten with human SUPPORT and ten CONTRADICT labels (CASES_PER_LABEL fixes each class count). For each it passes the model full BEIR representations, title and abstract, of the three top reranked documents in that order; these are not full papers. Evidence presence is checked by an annotated SciFact document ID; this does not verify that every annotated sentence literally matches BEIR. It retains question, context, prompt, output, stop reasons, citations, judgments, and hashes. The model chooses between apoya, contradice, and no_suficiente, and must abstain without evidence.
The verdict is compared with the original label only when an annotated document is in context and the answer satisfies the contract without abstaining. The cell reports matches over eligible answers and hits over all 20 scheduled, with incidents separate. Agreement with an external label does not prove context or citation supports the answer. Judge and NLI evaluate each generated string against context, not verdict correctness or individual citations. NLI records effective tokens and may see truncated context. requests and jsonschema are needed; NLI also needs numpy, PyTorch, and sentence-transformers. Ollama 0.17.7 or later must have phi3:mini, and access to official sources is needed to check fingerprints. Output goes to a pipeline-* directory in the lab directory. Initial constants PREDICT and MAX_QUOTE control output budget and maximum quote length.
"""Reranking real, generación con citas y referencia humana de SciFact train.
Usa la carpeta OUT de la primera celda de esta lección. En una ejecución
independiente, fija P05_L04_RERANK_OUTPUT a la ruta que imprimió esa celda.
P05_L04_DRY_RUN=1 construye los casos y no llama a Ollama ni usa GPU.
Los juicios automáticos no sustituyen la calibración con anotaciones humanas.
"""
import csv
import datetime
import hashlib
import io
import json
import os
from pathlib import Path
import random
import tarfile
import tempfile
import zipfile
import requests
from jsonschema import ValidationError, validate
SEED = 20261028
BASE = 'http://127.0.0.1:11434'
MODEL = 'phi3:mini'
BEIR = 'https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/scifact.zip'
SCIFACT = 'https://scifact.s3-us-west-2.amazonaws.com/release/latest/data.tar.gz'
MIN_OLLAMA = (0, 17, 7)
PREDICT = 384 # tokens máximos de salida; prueba 240 para ver cuántas respuestas se cortan
MAX_QUOTE = 120 # caracteres máximos por cita; None quita el límite
CASES_PER_LABEL = 10 # afirmaciones por etiqueta; 25 da las 50 respuestas de la calibración del juez
GUIDE = ('Para cada respuesta: NA si el veredicto es no_suficiente sin afirmaciones, si alguna cadena no es '
'declarativa o si no puede juzgarse; en otro caso 1 si todas las afirmaciones están respaldadas por '
'los resúmenes del contexto y 0 si alguna no lo está. No consultar juicios.jsonl antes de anotar.')
def lab_dir():
"""Directorio de trabajo del lector: ATLAS_LAB_DIR o ~/atlas-lab, subcarpeta p05-l04."""
base = Path(os.environ.get('ATLAS_LAB_DIR', Path.home() / 'atlas-lab')).expanduser()
folder = base / 'p05-l04'
folder.mkdir(parents=True, exist_ok=True)
return folder
def check_ollama(version):
"""Exige una versión con truncate y shift en /api/chat; avisa si no es la verificada."""
parts = tuple(int(x) for x in version.split('-')[0].split('.')[:3])
if parts < MIN_OLLAMA:
raise RuntimeError('Ollama ' + version + ' es anterior a 0.17.7: actualízalo antes de medir.')
if parts != MIN_OLLAMA:
print('Aviso: el código se verificó con Ollama 0.17.7; comprueba que truncate=false '
'y shift=false conservan su semántica en', version, flush=True)
def sha(data):
return hashlib.sha256(data).hexdigest()
def canonical(item):
return json.dumps(item, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode('utf-8')
def get(url):
response = requests.get(url, timeout=120)
response.raise_for_status()
return response.content
def load_inputs(folder):
summary_bytes = (folder / 'resultado.json').read_bytes()
rows_bytes = (folder / 'reranking-por-consulta.jsonl').read_bytes()
summary = json.loads(summary_bytes)
rows = [json.loads(line) for line in rows_bytes.splitlines()]
if len(rows) != summary['questions_with_human_evidence'] or len({x['query_id'] for x in rows}) != len(rows):
raise ValueError('Faltan consultas o hay identificadores repetidos en el reranking')
if summary['candidate_depth'] != 20:
raise ValueError('El experimento debe disponer de los 20 candidatos reordenados')
for row in rows:
candidates = row['candidates']
expected = list(range(1, 21))
if len(candidates) != 20 or sorted(x['rrf_position'] for x in candidates) != expected or sorted(x['rerank_position'] for x in candidates) != expected:
raise ValueError('Rangos inválidos en ' + row['query_id'])
score_sorted = sorted(candidates, key=lambda c: (-c['score_logit'], c['document_id']))
if any(c['rerank_position'] != i for i, c in enumerate(score_sorted, 1)):
raise ValueError('Los rangos y puntuaciones no coinciden en ' + row['query_id'])
beir = get(BEIR)
original = get(SCIFACT)
if sha(beir) != summary['beir_sha256'] or sha(original) != summary['scifact_sha256']:
raise ValueError('Las fuentes actuales no coinciden con las huellas de la primera celda')
with zipfile.ZipFile(io.BytesIO(beir)) as z:
def read(suffix):
names = [n for n in z.namelist() if n.endswith('/' + suffix)]
if len(names) != 1:
raise ValueError('Entrada ausente o ambigua: ' + suffix)
return z.read(names[0])
if sha(read('qrels/train.tsv')) != summary['train_qrels_sha256']:
raise ValueError('Los qrels train no coinciden')
corpus = {x['_id']: (x.get('title', '') + '\n' + x.get('text', '')).strip()
for x in (json.loads(line) for line in read('corpus.jsonl').splitlines())}
wanted = {x['query_id'] for x in rows}
questions = {}
for line in read('queries.jsonl').splitlines():
item = json.loads(line)
if item['_id'] in wanted:
questions[item['_id']] = item['text']
with tarfile.open(fileobj=io.BytesIO(original), mode='r:gz') as t:
found = [m for m in t.getmembers() if m.name.endswith('/claims_train.jsonl')]
if len(found) != 1:
raise ValueError('No se encuentra claims_train.jsonl')
train = t.extractfile(found[0]).read()
if sha(train) != summary['claims_train_sha256']:
raise ValueError('La referencia SciFact train no coincide')
claims = {str(x['id']): x for x in (json.loads(line) for line in train.splitlines())}
if set(questions) != wanted or not wanted.issubset(claims):
raise ValueError('Faltan afirmaciones de train')
by_label = {'SUPPORT': [], 'CONTRADICT': []}
for row in rows:
qid = row['query_id']
if questions[qid] != claims[qid]['claim']:
raise ValueError('La afirmación BEIR difiere del original: ' + qid)
all_labels = {a['label'] for items in claims[qid]['evidence'].values() for a in items}
if len(all_labels) != 1 or next(iter(all_labels)) not in by_label:
raise ValueError('Afirmación sin etiqueta humana única: ' + qid)
by_label[next(iter(all_labels))].append(qid)
rng = random.Random(SEED)
selected = (rng.sample(sorted(by_label['SUPPORT']), CASES_PER_LABEL) +
rng.sample(sorted(by_label['CONTRADICT']), CASES_PER_LABEL))
rng.shuffle(selected)
rows_by_id = {x['query_id']: x for x in rows}
cases = []
for qid in selected:
top3 = sorted(rows_by_id[qid]['candidates'], key=lambda c: c['rerank_position'])[:3]
contexts = []
for c in top3:
docid = c['document_id']
if docid not in corpus:
raise ValueError('Falta documento: ' + docid)
contexts.append({'id': docid, 'text': corpus[docid], 'rerank_position': c['rerank_position'],
'rrf_position': c['rrf_position'], 'score_logit': c['score_logit']})
expected = next(iter({a['label'] for items in claims[qid]['evidence'].values() for a in items}))
matched = {c['id']: [x['label'] for x in claims[qid]['evidence'].get(c['id'], [])] for c in contexts}
visible_labels = {v for values in matched.values() for v in values}
if visible_labels and visible_labels != {expected}:
raise ValueError('Las etiquetas visibles discrepan en ' + qid)
cases.append({'id': qid, 'claim': questions[qid], 'contexts': contexts,
'human_reference': expected, 'annotated_evidence_in_context': bool(visible_labels),
'human_evidence_by_document': matched})
return cases, {'source_summary_sha256': sha(summary_bytes), 'source_rankings_sha256': sha(rows_bytes),
'beir_sha256': summary['beir_sha256'], 'scifact_sha256': summary['scifact_sha256'],
'claims_train_sha256': summary['claims_train_sha256'],
'selection_seed': SEED, 'candidate_depth': 3, 'eligible_original_queries': len(rows),
'class_counts_original': {k: len(v) for k, v in by_label.items()}}
def schema():
quote = {'type': 'string'} if MAX_QUOTE is None else {'type': 'string', 'maxLength': MAX_QUOTE}
citation = {'type': 'object', 'properties': {'id': {'type': 'string'}, 'quote': quote},
'required': ['id', 'quote'], 'additionalProperties': False}
statement = {'type': 'object', 'properties': {'text': {'type': 'string'},
'citations': {'type': 'array', 'items': citation}},
'required': ['text', 'citations'], 'additionalProperties': False}
return {'type': 'object', 'properties': {'veredicto': {'type': 'string', 'enum': ['apoya', 'contradice', 'no_suficiente']},
'afirmaciones': {'type': 'array', 'items': statement}},
'required': ['veredicto', 'afirmaciones'], 'additionalProperties': False}
def contract_diagnostic(answer, contexts):
try:
validate(answer, schema())
except ValidationError:
return 'esquema_invalido'
statements = answer['afirmaciones']
if answer['veredicto'] == 'no_suficiente':
return None if not statements else 'abstencion_incoherente'
if not statements:
return 'sin_afirmaciones'
for item in statements:
if not item['text'].strip():
return 'afirmacion_vacia'
if not item['citations']:
return 'sin_citas'
for cite in item['citations']:
if cite['id'] not in contexts:
return 'id_fuera_de_contexto'
if not cite['quote'].strip():
return 'cita_vacia'
if cite['quote'] not in contexts[cite['id']]:
return 'cita_no_literal'
return None
def contract(answer, contexts):
return contract_diagnostic(answer, contexts) is None
def response_incident(public):
if 'generation_error' in public:
return 'error_generacion'
reply = public['generation']
if reply['done_reason'] != 'stop':
return 'salida_incompleta'
if reply['parse_error'] is not None:
return 'json_invalido'
return contract_diagnostic(reply['parsed'], {c['id']: c['text'] for c in public['contexts']})
def prompt_for(case):
pieces = '\n\n'.join('[' + c['id'] + ']\n' + c['text'] for c in case['contexts'])
limit = '' if MAX_QUOTE is None else f', con un máximo de {MAX_QUOTE} caracteres'
brevity = '' if MAX_QUOTE is None else 'No copies el resumen completo: usa una afirmación breve y una cita breve. '
return ('Decide solo con los resúmenes si respaldan o contradicen la afirmación. '
'Devuelve JSON con veredicto apoya, contradice o no_suficiente. '
'Para apoya o contradice incluye afirmaciones con citas: cada cita tiene id y quote '
'copiado exactamente del texto indicado' + limit + '. ' + brevity +
'Si no hay evidencia suficiente, '
'usa no_suficiente y afirmaciones vacías. No uses información externa.\n\n'
'Afirmación:\n' + case['claim'] + '\n\nResúmenes:\n' + pieces)
def judge_schema():
return {'type': 'object', 'properties': {'respaldo': {'type': 'boolean'}, 'motivo': {'type': 'string'}},
'required': ['respaldo', 'motivo'], 'additionalProperties': False}
def generate(session, prompt, output_schema):
payload = {'model': MODEL, 'stream': False, 'format': output_schema, 'keep_alive': '2m',
'truncate': False, 'shift': False, 'messages': [{'role': 'user', 'content': prompt}],
'options': {'temperature': 0, 'seed': SEED, 'num_ctx': 4096,
'num_batch': 128, 'num_predict': PREDICT}}
response = session.post(BASE + '/api/chat', json=payload, timeout=300)
response.raise_for_status()
data = response.json()
content = data.get('message', {}).get('content', '')
try:
parsed, parse_error = json.loads(content), None
except (ValueError, TypeError) as exc:
parsed, parse_error = None, str(exc)
return {'raw': content, 'parsed': parsed, 'parse_error': parse_error, 'done_reason': data.get('done_reason'),
'prompt_tokens_reported': data.get('prompt_eval_count'), 'output_tokens': data.get('eval_count')}
def main():
raw = os.environ.get('P05_L04_RERANK_OUTPUT') or globals().get('OUT')
if not raw:
raise RuntimeError('Ejecuta primero la celda de reranking o fija P05_L04_RERANK_OUTPUT a su ruta')
input_folder = Path(raw).resolve()
cases, provenance = load_inputs(input_folder)
output = Path(tempfile.mkdtemp(prefix='pipeline-', dir=str(lab_dir())))
print('Salida:', output, flush=True)
refs = [{'id': c['id'], 'human_reference': c['human_reference'],
'annotated_evidence_in_context': c['annotated_evidence_in_context'],
'human_evidence_by_document': c['human_evidence_by_document']} for c in cases]
(output / 'referencias.jsonl').write_text(''.join(json.dumps(x, ensure_ascii=False) + '\n' for x in refs), encoding='utf-8')
metadata = {'created_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(),
'provenance': provenance, 'manual_guide': GUIDE,
'sample': f'{CASES_PER_LABEL} SUPPORT y {CASES_PER_LABEL} CONTRADICT, seleccionados antes de generar',
'source_scope': 'SciFact train externo; no es el conjunto propio ni test independiente',
'reference_rule': 'Coincidencia con la etiqueta humana condicionada a una salida válida no abstencionista y a un documento anotado en el contexto; no es exactitud sobre todas las peticiones.',
'reference_scope': 'La evidencia se comprueba por ID de documento; el abstract BEIR y las frases SciFact originales pueden diferir en caracteres.',
'faithfulness': 'La coincidencia con la referencia y las citas literales no prueban respaldo semántico.',
'judge': 'El mismo phi3:mini juzga cada cadena frente al contexto completo; no está calibrado con humanos.',
'nli': 'Diagnóstico en CPU con un modelo entrenado en inglés; el idioma depende de la salida. Dominio limitado y pareja recortada a 512 tokens.',
'maximum_quote_characters': MAX_QUOTE, 'num_predict': PREDICT}
(output / 'meta.json').write_text(json.dumps(metadata, ensure_ascii=False, indent=2), encoding='utf-8')
if os.environ.get('P05_L04_DRY_RUN') == '1':
preview = {'selected': len(cases), 'classes': {label: sum(c['human_reference'] == label for c in cases)
for label in ('SUPPORT', 'CONTRADICT')},
'with_annotated_evidence_in_top3': sum(c['annotated_evidence_in_context'] for c in cases),
'output': str(output), 'note': 'Solo preparación; no se llamó a Ollama ni se usó GPU.'}
(output / 'preparacion.json').write_text(json.dumps(preview, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps(preview, ensure_ascii=False, indent=2), flush=True)
return
session = requests.Session()
version_response = session.get(BASE + '/api/version', timeout=10)
version_response.raise_for_status()
version = version_response.json()
check_ollama(version.get('version', '0'))
tags_response = session.get(BASE + '/api/tags', timeout=10)
tags_response.raise_for_status()
model = next((x for x in tags_response.json()['models'] if x.get('name') == MODEL), None)
if model is None:
raise RuntimeError('El modelo phi3:mini de la primera lección no está instalado')
metadata.update({'ollama_version': version, 'model': model})
(output / 'meta.json').write_text(json.dumps(metadata, ensure_ascii=False, indent=2), encoding='utf-8')
comparisons = []
nli_pairs = []
annotation = []
for index, case in enumerate(cases, 1):
request_text = prompt_for(case)
public = {'id': case['id'], 'claim': case['claim'], 'contexts': case['contexts'],
'prompt': request_text, 'prompt_sha256': sha(request_text.encode('utf-8'))}
try:
reply = generate(session, request_text, schema())
public['generation'] = reply
contexts = {c['id']: c['text'] for c in case['contexts']}
public['literal_contract_valid'] = (reply['done_reason'] == 'stop' and contract(reply['parsed'], contexts))
except (requests.RequestException, ValueError, KeyError) as exc:
public['generation_error'] = str(exc)
public['literal_contract_valid'] = False
public['incident'] = response_incident(public)
digest = sha(canonical(public))
with (output / 'para-anotar.jsonl').open('a', encoding='utf-8', newline='\n') as f:
f.write(json.dumps(public, ensure_ascii=False) + '\n')
annotation.append({'id': case['id'], 'huella': digest, 'revisor': '', 'humano': '', 'nota': ''})
is_valid = public['literal_contract_valid']
verdict = public.get('generation', {}).get('parsed', {}).get('veredicto') if is_valid else None
judgments = []
if is_valid:
material = '\n\n'.join('[' + c['id'] + ']\n' + c['text'] for c in case['contexts'])
for item in public['generation']['parsed']['afirmaciones']:
nli_pairs.append({'id': case['id'], 'response_sha256': digest,
'claim_index': len(judgments), 'context': material, 'claim': item['text']})
judge_prompt = ('Juzga si el contexto respalda por completo la afirmación. '
'No uses conocimiento externo y devuelve JSON con respaldo y motivo.\n\n'
'Contexto:\n' + material + '\n\nAfirmación:\n' + item['text'])
judgment = {'statement': item['text'], 'prompt': judge_prompt,
'prompt_sha256': sha(judge_prompt.encode('utf-8'))}
try:
result = generate(session, judge_prompt, judge_schema())
judgment['generation'] = result
try:
validate(result['parsed'], judge_schema())
judgment['valid'] = result['done_reason'] == 'stop'
except ValidationError:
judgment['valid'] = False
except (requests.RequestException, ValueError, KeyError) as exc:
judgment.update(valid=False, error=str(exc))
judgments.append(judgment)
with (output / 'juicios.jsonl').open('a', encoding='utf-8', newline='\n') as f:
f.write(json.dumps({'id': case['id'], 'response_sha256': digest, 'claims': judgments}, ensure_ascii=False) + '\n')
eligible = bool(case['annotated_evidence_in_context'] and verdict in ('apoya', 'contradice'))
expected = {'SUPPORT': 'apoya', 'CONTRADICT': 'contradice'}[case['human_reference']]
comparisons.append({'id': case['id'], 'response_sha256': digest, 'literal_contract_valid': is_valid,
'generation_error': 'generation_error' in public,
'incident': public['incident'],
'annotated_evidence_in_context': case['annotated_evidence_in_context'],
'human_reference': case['human_reference'], 'verdict': verdict,
'eligible_for_reference_comparison': eligible,
'matches_reference': (verdict == expected) if eligible else None,
'judge_valid_claims': sum(j['valid'] for j in judgments),
'judge_supported_claims': sum(j['valid'] and j['generation']['parsed']['respaldo'] for j in judgments)})
print(f'{index}/{len(cases)} {case["id"]}: contrato={is_valid}, veredicto={verdict}', flush=True)
with (output / 'anotaciones.csv').open('w', encoding='utf-8', newline='') as f:
writer = csv.DictWriter(f, fieldnames=['id', 'huella', 'revisor', 'humano', 'nota'])
writer.writeheader(); writer.writerows(annotation)
(output / 'comparaciones.jsonl').write_text(''.join(json.dumps(x, ensure_ascii=False) + '\n' for x in comparisons), encoding='utf-8')
nli_output = []
nli_error = None
if nli_pairs:
try:
import numpy as np
import torch
from sentence_transformers import CrossEncoder
torch.set_num_threads(1)
nli = CrossEncoder('cross-encoder/nli-deberta-v3-small',
revision='fa2804872c3b4bd748f38c0185cc85775361e735',
max_length=512, device='cpu')
labels = {int(i): str(label).lower() for i, label in nli.model.config.id2label.items()}
if labels != {0: 'contradiction', 1: 'entailment', 2: 'neutral'}:
raise ValueError('La correspondencia de etiquetas NLI cambió')
pairs = [(x['context'], x['claim']) for x in nli_pairs]
token_counts = [len(nli.tokenizer(a, b, truncation=False)['input_ids']) for a, b in pairs]
tokens = [nli.tokenizer(a, b, truncation=True, max_length=512)['input_ids'] for a, b in pairs]
scores = np.asarray(nli.predict(pairs, batch_size=8, apply_softmax=False, show_progress_bar=False))
if scores.shape != (len(pairs), 3):
raise ValueError('La salida NLI no tiene tres clases por pareja')
for pair, length, ids, logits in zip(nli_pairs, token_counts, tokens, scores):
label = labels[int(np.argmax(logits))]
nli_output.append({'id': pair['id'], 'response_sha256': pair['response_sha256'],
'claim_index': pair['claim_index'], 'label': label,
'logits': logits.tolist(), 'input_tokens_before_truncation': length,
'truncated': length > 512, 'effective_input_ids': ids,
'supported_binary': int(label == 'entailment')})
del nli, scores
except Exception as exc:
nli_error = str(exc)
(output / 'nli.jsonl').write_text(''.join(json.dumps(x, ensure_ascii=False) + '\n' for x in nli_output), encoding='utf-8')
judged = {x['id']: x for x in (json.loads(line) for line in
(output / 'juicios.jsonl').read_text(encoding='utf-8').splitlines())}
nli_labels = {}
comparable = matching = 0
for row in nli_output:
nli_labels[row['label']] = nli_labels.get(row['label'], 0) + 1
entries = judged[row['id']]['claims']
if row['claim_index'] < len(entries) and entries[row['claim_index']]['valid']:
comparable += 1
decision = entries[row['claim_index']]['generation']['parsed']['respaldo']
matching += int(bool(row['supported_binary']) == decision)
eligible = [x for x in comparisons if x['eligible_for_reference_comparison']]
hits = sum(x['matches_reference'] for x in eligible)
incidents = {}
for row in comparisons:
if row['incident']:
incidents[row['incident']] = incidents.get(row['incident'], 0) + 1
report = {'planned': len(cases), 'valid_literal_contracts': sum(x['literal_contract_valid'] for x in comparisons),
'abstentions': sum(x['verdict'] == 'no_suficiente' for x in comparisons),
'invalid_or_failed_contracts': sum(not x['literal_contract_valid'] for x in comparisons),
'generation_errors': sum(x['generation_error'] for x in comparisons),
'incidents_by_type': incidents,
'with_annotated_evidence_in_context': sum(x['annotated_evidence_in_context'] for x in comparisons),
'without_annotated_evidence_in_context': sum(not x['annotated_evidence_in_context'] for x in comparisons),
'eligible_answered_comparisons': len(eligible), 'matches_reference': hits,
'matches_per_eligible_answer': hits / len(eligible) if eligible else None,
'matches_per_planned': hits / len(cases) if cases else None,
'planned_denominator_note': 'Abstenciones, errores, contratos inválidos y casos sin evidencia anotada en contexto cuentan como no aciertos.',
'judge_valid_claims': sum(x['judge_valid_claims'] for x in comparisons),
'judge_supported_claims': sum(x['judge_supported_claims'] for x in comparisons),
'nli_pairs': len(nli_output), 'nli_label_counts': nli_labels,
'nli_truncated_pairs': sum(x['truncated'] for x in nli_output),
'nli_judge_comparable': comparable, 'nli_judge_matching': matching,
'nli_error': nli_error,
'human_annotations': 0,
'note': 'Muestra balanceada SciFact train; juicio automático no calibrado, sin kappa humana.'}
(output / 'resumen.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print('Salida:', output, flush=True)
print(json.dumps(report, ensure_ascii=False, indent=2), flush=True)
if __name__ == '__main__':
main()npm run lab and open the connection link.This is what a reference run obtained with cell values PREDICT = 384 and MAX_QUOTE = 120. All 20 queries had an annotated document among the top three reranked. Only 7 of 20 answers met the contract: 3 ended by length and another 10 ended but contained a nonliteral quote. None abstained. Of the 7 valid answers, 2 matched the original label: 2/7 conditional on a valid answer and 2/20 over scheduled requests. The 3.8-billion-parameter model, with English scientific abstracts and a Spanish prompt, mainly fails on verifiable format rather than finding the document.
One experiment is worth repeating: set PREDICT = 240 and MAX_QUOTE = None, leaving the prompt without the request for short quotes. In one such run on the same 20 cases and documents, only 2 answers met the contract and 17 ended by length: the model copied whole abstracts as quotes and exhausted the budget. Because two parameters change at once, this comparison cannot identify which causes the difference; separating them is a useful ablation exercise with the same cell.
The reference run had nine valid string judgments and seven indicated support. NLI processed those nine pairs, truncating all nine to 512 tokens because context consists of three full abstracts, and classified all nine neutral; binary mapping agreed with the judge on 2 of 9. These are uncalibrated diagnostics, not human faithfulness. Case 883 is a useful annotation example: the SciFact claim is “Omnivores produce more trimethylamine N-oxide from dietary I-carnitine than vegans” (the “I” in place of “L” is present in the dataset), labeled SUPPORT. The model returned verdict contradice, but its only string repeated the original claim with a literal supporting quote; the judge considered that string supported and attributed the fact in its reason to a different document from the one containing it. A favorable judge label does not check verdict correctness or that its explanation cites evidence correctly.
These answers are natural material for calibrating the judge: they have real format, verdict, and citation errors. The lab’s last step, and the figure this lesson asks you to measure, is judge kappa against your annotation:
- Set
CASES_PER_LABEL = 25and rerun the cell. You obtain 50 requests; this is another sample with the same seed, not the 20 cases above expanded, so counts do not compare one-to-one with the reference run. - With
citas.pyfrom the previous cell, runpython citas.py anotar RUTAon the printedpipeline-*folder. The tool accepts both formats: here records useclaimrather thanquestionand contexts are a list, and annotation guidelines are saved by the cell inmeta.json. - Run
python citas.py evaluar-anotaciones RUTA. Since this cell’s judge labels each string, the function aggregates per answer: 1 if all its strings have a valid support judgment, 0 if any does not, and excluded from comparison if any valid judgment is missing. If the reference-run proportion held, 7 valid contracts out of 20, about 17 of 50 answers would enter the comparison, and fewer after excludingNA: always report that number with kappa because uncertainty is large with so few pairs.
The sample is small, balanced, and from train; it does not estimate population performance. For a figure applicable to your agent, repeat the protocol with frozen questions from your development set.
Common mistakes
Exercises
def citation_check(answer, contexts):
passSummary
The reranker only orders what retrieval finds; a valid citation locates text; and faithfulness requires that text to support the claim. An automatic judge needs calibration against real annotations before becoming a trusted metric.
- A cross-encoder processes query and passage together and can rank better than a bi-encoder, at the cost of one network pass per pair. It cannot exceed candidate recall. On SciFact train, reranking 20 candidates with BGE raised nDCG@10 from 0.864 to 0.884 and added 0.67 to 0.85 s median per query on an 8 GB GPU.
- Relevant passage position in the prompt matters, but its effect depends on model, template, and length: Liu and colleagues measured a U-curve with GPT-3.5-Turbo; with
phi3:minion synthetic cards a middle drop appeared only with four distractors. - The answer contract separates abstention and claims and ties each claim to context chunk IDs with literal excerpts. The client validates schema, termination, IDs, and excerpts; semantic entailment is judged separately.
- Faithfulness is measured by claim with an LLM judge or NLI model and is distinct from correctness. Abstentions and extraction errors are reported separately, without assigning perfect faithfulness.
- Cohen’s kappa, , corrects agreement for that expected under marginals. A judge that always says “supported” has kappa 0 or undefined even when raw agreement is high.