Evaluating the base model
Evaluate the pretrained model through validation loss and perplexity, HellaSwag completion likelihood, and qualitative samples under different sampling parameters. Compare everything with public 124M GPT-2 evaluated by the same script, with intervals and an honest discussion of data and compute differences.
After this lesson you can
- Implement HellaSwag evaluation by mean completion loss and validate it with public GPT-2.
- Evaluate the custom model and GPT-2 with the same script and calculate confidence intervals.
- Implement temperature, top-k, and top-p sampling and compare samples.
- Write the comparison explaining data, token, and compute differences.
Before you start
Three questions, three measurements
After long pretraining, you have a folder of checkpoints and a falling loss curve. That answers one question: how much probability the model assigns to text similar to training data. It does not say whether the model chooses a sensible continuation of an everyday scene or whether its writing makes sense. Lower validation loss does not guarantee success on a commonsense question, and fluent text does not establish factual correctness.
We therefore evaluate from three angles, each with its own protocol:
- Held-out text probability: loss, perplexity, and bits per byte.
- Choice among continuations: HellaSwag scored by likelihood, with a confidence interval and paired comparison to public 124-million-parameter GPT-2.
- Generated samples: qualitative inspection with temperature, top-k, and top-p fixed in advance.
The common rule is to fix data, tokenizer, and protocol before seeing results. First validate the evaluator on a model with a known result, public GPT-2, before trusting what it says about yours.
Start with the most intuitive view. The panel shows the actual next-token distribution of public GPT-2 after “Once upon a time”, computed from its 50257 logits, and a continuation generated under each configuration. Increase temperature to flatten the distribution; lower top-p to cut off the tail and redistribute remaining mass among survivors.
Try three things. With temperature 0.4, “,” gets 98% of the mass and top-p 0.8 or 0.95 retains one candidate: sampling is nearly greedy and the continuation becomes repetitive (“the river… the river”). At temperature 1.3 with no filters, all 50257 tokens remain possible, the tail receives appreciable mass, and text derails within a few words. Add top-k 40 and the same temperature produces sentences again. Compare samples from neighboring configurations: they share a seed yet diverge as soon as the distribution changes. One sample is not a measurement.
This lesson evaluates checkpoints from the long run with the same code used for GPT-2, whose weights were loaded in the parity check.
Text probability and perplexity
For a sequence of valid targets, mean loss in natural logarithms is
and per-token perplexity is . Since , perplexity is the inverse geometric mean of target probabilities: a model with perplexity 20 is, on average geometrically, as uncertain as if choosing uniformly among 20 tokens. Two implementation details change the number. First, accumulate total loss and target count and divide at the end; averaging means of different-sized batches weights tokens differently. Second, text must be separate from training, with version, selection, and segmentation rules recorded.
Perplexity depends on the unit. Suppose two models with different tokenizers read the same bytes. The first splits it into tokens and the second into . Total string log-probability, , is comparable if both model the same byte sequence under the same beginning and ending policy. Perplexity divides by or : a model with a finer vocabulary distributes the same total surprise across more tokens and appears to have lower perplexity without being better. This pathway’s tokenizer has 512 ordinary tokens versus GPT-2’s 50257 and therefore splits the same text into many more pieces. Comparing per-token perplexities would compare different units.
The denominator is tokenizer-independent, so bits per byte of two models on the same bytes with the same document policy can be compared. Here each text begins after its vocabulary’s end-of-document token. For example, nats per token, tokens, and bytes give bits per byte. Comparison still has limits: it measures probability of the chosen text rather than general quality, and documents, special tokens, truncation, and context boundaries must be documented equally for both.
HellaSwag: score only the ending
HellaSwag presents a short context from ActivityNet video descriptions or WikiHow articles and four candidate endings. Incorrect endings were language-model generated and selected by adversarial filtering: those that fooled classifiers of the time survived. The paper reports over 95% human accuracy while the best models then were below 48%. Each validation row has ctx, an endings list, label as a string from '0' to '3', an ind identifier, and split_type, distinguishing activities seen in training (indomain) from new activities (zeroshot).
A base model does not know how to answer “the answer is C”, but it can assign probabilities. HellaSwag likelihood evaluation converts the multiple-choice question into four language-modeling problems, as in likelihood scoring. For each tokenized continuation it computes
and selects the candidate with lowest mean loss. No text is generated.
Index shift. If context occupies positions and the ending occupies , logits at position predict token . The first ending token at is predicted by logits at , the final context position; the last ending token at by logits at . Logits at the ending’s last position predict something that does not exist and are discarded. The scoring mask excludes context and padding, never the first ending token: this is the most common and silent error because the evaluator still returns plausible accuracy.
Tokenization boundary. Results also depend on pretokenizing the context and space before the ending. Here ctx and " " + ending are encoded separately and IDs concatenated, as in the build-nanogpt evaluator. Tokenizing the complete string ctx + " " + ending can merge pieces across the boundary; that is a different protocol and produces a different result.
Length normalization. Summing losses penalizes longer endings when their per-token losses are similar because each token adds a positive term. Dividing by token count, as in length-normalized scoring, answers a different question, which ending is more probable per token, and does not eliminate all biases: a long ending with many predictable final tokens such as punctuation or split words lowers its mean. Other implementations normalize by characters or bytes, or present lettered choices in a template. These are different metrics. Our evaluator computes the two reported by build-nanogpt: acc using the sum and acc_norm using the mean; the latter is primary.
Context too long. If context and continuation do not fit the model window, code retains the whole continuation and truncates only the context beginning. If the continuation does not fit with at least one context token, it is rejected. This does not happen for GPT-2 on HellaSwag validation, but the rule must be documented and identical for both models. The four rows of an example are right-padded: because attention is causal, padding tokens do not affect earlier-position logits and the mask ignores them.
With four options, a random classifier would obtain 25% accuracy in expectation. Exceed this baseline with a confidence interval, not just a point estimate.
Validate the evaluator with public GPT-2
Before evaluating your model, the evaluator must reproduce a known result. The build-nanogpt evaluator, using this exact protocol on all 10042 validation examples, reports acc 0.2859 and acc_norm 0.2955 for 124M GPT-2 in its comments. That is what the lab should obtain on the complete set. A discrepancy of more than a few tenths of a percentage point suggests a mask, boundary, or data error rather than noise, since computation is deterministic apart from floating-point rounding differences.
The same file records another result for the same model: the EleutherAI evaluation harness reports acc 28.92% and acc_norm 31.14% with a different multiple-choice format. The llm.c GPT-2 reproduction cites 29.4% for GPT-2 (124M) versus 29.9% for its 124M model trained on 10 billion FineWeb tokens. Three numbers for the same weights: accuracy is a property of model and protocol together.
A comparison with uncertainty
Comparison with a reference model requires exactly the same examples, text, scoring rule, and tie-breaking rule, here the lowest index, although each model uses its own tokenizer. Also record all four losses for each example, its index, and correct answer: aggregate accuracy cannot audit a mask shift, whereas per-example details can. If choosing the best of several evaluation configurations after seeing results, make that choice on a development set distinct from the reported set.
Interval for one accuracy. With successes in examples and , the simplest model treats successes as independent Bernoulli trials with probability . The Wilson interval, one of the binomial proportion intervals, inverts the score test.
Proof
Squaring, the condition is equivalent to , or
The leading coefficient is positive, so the set is the interval between roots. The discriminant is
and roots yield the stated formula after dividing numerator and denominator by 2. Both roots lie in because the polynomial equals at and at , with vertex , a weighted average of and , inside .
∎Unlike the Wald interval , Wilson never leaves and does not degenerate when is 0 or 1. With , it is an approximate 95% interval. For the full set, and , half-width is about 0.009. To claim a model exceeds chance under this criterion, its lower endpoint must exceed 0.25, requiring at least 2596 successes, accuracy 0.2585. With 32 examples, half-width is about 0.14 and little can be concluded.
The interval rests on two assumptions worth stating. Examples are treated as a sample from a population of questions, and a sample selected by order, the first rows in the file, does not itself represent the full benchmark. The interval addresses sampling variation, not contamination. If training data contain HellaSwag text, accuracy is inflated by memorization and no interval detects that. Benchmark contamination is investigated separately, for example by searching for n-gram overlap between corpus and examples.
Paired comparison. Two separate intervals are not the right way to compare models answering the same questions: they ignore correlated errors, since hard questions are hard for both. For each example , let be the difference between custom-model correctness and GPT-2 correctness . Let count examples only the custom model gets right and those only GPT-2 gets right. The accuracy difference is , and since exactly on the discordant examples,
Examples both get right or both miss do not inform the difference. Under the null hypothesis of equal accuracy, conditional on , the count follows : the exact McNemar test with two-sided p-value . For a hypothetical , , and , the difference is 0.0050 with interval [0.0004, 0.0096] and McNemar p-value 0.037. Separate marginal accuracies would have Wilson half-widths near 0.009 and overlap widely; paired analysis detects what unpaired analysis misses.
import math
Z95 = 1.959963984540054
def wilson(k, n, z=Z95):
p = k / n
d = 1 + z*z/n
centro = (p + z*z/(2*n)) / d
semi = z * math.sqrt(p*(1-p)/n + z*z/(4*n*n)) / d
return centro - semi, centro + semi
def emparejada(b, c, n, z=Z95):
"""b: solo acierta A; c: solo acierta B; n: ejemplos comunes."""
dif = (b - c) / n
se = math.sqrt(((b + c)/n - dif*dif) / n)
m = b + c
cola = sum(math.comb(m, i) for i in range(min(b, c) + 1)) / 2**m
return dif, (dif - z*se, dif + z*se), min(1.0, 2*cola)
n = 10042
print('Wilson con 0.30 de 10042:', [round(x, 6) for x in wilson(0.30*n, n)])
print('Wilson con 7 de 32: ', [round(x, 4) for x in wilson(7, 32)])
k = next(k for k in range(n) if wilson(k, n)[0] > 0.25)
print('Aciertos mínimos para superar el 25 %:', k, round(k/n, 4))
# Ejemplo hipotético: A acierta 3000 y B 2950; discrepan en 550 ejemplos
dif, ic, p = emparejada(300, 250, n)
print('Diferencia emparejada:', round(dif, 4), [round(x, 4) for x in ic], 'McNemar p =', round(p, 4))
print('Wilson de A y de B:', [round(x, 4) for x in wilson(3000, n)], [round(x, 4) for x in wilson(2950, n)])Output confirms the text’s figures: A and B’s marginal intervals overlap almost entirely, yet the paired interval excludes zero.
Sampling is not likelihood evaluation
For qualitative evaluation by sampling, choose prompts before generation and save configuration, seed, and software version. Apply the three next-token distribution transformations in this order, which must be declared because changing it can change the retained set:
- Temperature : , with the logits. At the model is recovered; as mass concentrates on argmax, greedy decoding with ties shared, and as it tends to uniform. Temperature changes distribution sharpness, not token ordering.
- Top-k: retain the highest-logit tokens, including ties with the th in our implementation, and assign zero probability to the rest, as in top-k sampling.
- Top-p, or nucleus sampling: sort probabilities descending and retain the shortest prefix whose sum reaches at least . The last token is included even if mass exceeds . This is nucleus sampling from Holtzman and colleagues: size adapts to distribution shape, small when the model is confident and large when it is not.
Renormalize after each filter. The panel shows top-k versus top-p. After “Once upon a time”, at temperature 0.7, top-p 0.8 retains 2 tokens; at temperature 1 it retains 23, and top-p 0.95 retains 1810, because GPT-2’s tail is long and flat. Top-k 40 retains 40 regardless: too many when the model is confident and too few when it is not. Combined, top-k 40 and top-p 0.95 at temperature 1 retain 21.
import numpy as np
def filtrar(logits, tau=1.0, top_k=0, top_p=1.0):
"""Temperatura, después top-k y después top-p. Devuelve probabilidades renormalizadas."""
z = np.asarray(logits, dtype=float) / tau
if top_k:
umbral = np.sort(z)[-top_k]
z = np.where(z < umbral, -np.inf, z)
p = np.exp(z - z.max())
p /= p.sum()
if top_p < 1.0:
orden = np.argsort(-p, kind='stable')
antes = np.cumsum(p[orden]) - p[orden] # masa estrictamente anterior a cada token
p[orden[antes >= top_p]] = 0.0
p /= p.sum()
return p
logits = np.array([3.0, 2.2, 1.5, 0.3, -0.5, -1.0])
for tau, k, q in [(1.0, 0, 1.0), (0.5, 0, 1.0), (2.0, 0, 1.0), (1.0, 3, 1.0), (1.0, 0, 0.9)]:
p = filtrar(logits, tau, k, q)
print(f'tau={tau} top_k={k} top_p={q}: soporte {int((p > 0).sum())}, probs {np.round(p, 3)}')
# Control: el núcleo es el prefijo mínimo con masa >= p
p0 = filtrar(logits)
masa = np.cumsum(np.sort(p0)[::-1])
minimo = int(np.searchsorted(masa, 0.9) + 1)
assert int((filtrar(logits, top_p=0.9) > 0).sum()) == minimo
# La misma semilla no fija la muestra si cambia la distribución
u = np.random.default_rng(2026).random(8)
for tau in (0.5, 1.0, 2.0):
acumulada = np.cumsum(filtrar(logits, tau))
print('tau', tau, 'tokens', np.searchsorted(acumulada, u, side='right'))The last block samples by inverse CDF with the same eight uniform numbers: changing changes the selected tokens. Real implementations consume the generator differently, but the phenomenon is the same, and the full chain diverges from the first differing token. Thus “same seed” guarantees the same sample only with the same distribution, operation order, and software.
Lower temperature concentrates the distribution but does not make one sample an objective evaluation. Holtzman and colleagues study how decoding changes text, such as repetition with greedy search and incoherence with pure sampling. This does not mean a top-p value fixes knowledge errors. Use several prompts fixed in advance and publish complete samples, including failures.
Honest comparison: tokens, data, and compute
A statement like “my model reaches 95% of GPT-2” has no meaning without explanatory context. For the final comparison, collect what is known and unknown for each model:
- Data. GPT-2 trained on WebText, about 8 million documents and 40 GB of text according to its paper, which does not publish token or step counts. Your model uses the p06-l02 FineWeb-Edu sample, filtered educational text: a different distribution, closer to some questions and farther from others.
- Tokens seen. Read yours from the checkpoint. Do not compare them one-for-one with GPT-2: with 512 ordinary tokens each token covers fewer bytes, so the same token budget represents less text. The common unit is the byte.
- Compute. For a dense transformer, training costs on the order of floating-point operations for parameters and tokens, as estimated by Kaplan and colleagues. Calculate with actual and and record GPU hours and sustained rate.
- Tokenizer and context. A small vocabulary consumes more context positions per sentence and leaves more model capacity in the embedding table relative to the rest.
With that table you can write a defensible comparison: each model’s accuracy and bits per byte measured with the same script, paired difference with interval, and data, token, and compute differences explaining context. You cannot attribute the gap to one cause: data, compute, tokenizer, and possible contamination are confounded. Separating them requires controlled experiments such as the next lesson’s ablations.
What should we expect? Published GPT-2-tokenizer references provide guidance: in the llm.c reproduction, a 124M model trained on 10 billion FineWeb tokens slightly exceeds GPT-2 on HellaSwag. For a model using this pathway’s 512-token vocabulary and a single-GPU budget, there is no published figure to compare against. The objective interval criterion is that the model exceeds chance if Wilson’s lower endpoint is above 0.25, and approaches GPT-2 according to the paired interval.
Lab: evaluator, GPT-2, and your checkpoints
The lab provides the complete evaluator and runs it in three steps: public GPT-2 on all 10042 validation examples, each checkpoint from your long run on the same examples, and the final comparison with samples from both models. It uses a GPU if available.
Requirements are torch, transformers==5.20.2, and matplotlib, plus regex, tiktoken, and hypothesis, imported by the p06-l01 tokenizer cell. Run from the project root, or set P06_PROJECT_ROOT, because code reads the p06-l03 GPT class and p06-l01 tokenizer from the lessons themselves, as before. Environment variables:
| Variable | Default | Use |
|---|---|---|
P06_EVAL_DIR | p06_eval | HellaSwag cache and all results. |
P06_CKPT_DIR | p06_pretrain/runs/full/snapshots | Recursive folder containing model-*.pt copies saved by p06-l06. |
P06_DATA_DIR | p06_data | p06-l02 manifest and vocabulary. |
P06_HS_LIMIT | 10042 | Number of examples; fewer only for tests. |
P06_TRUST_CKPT | unset | Set to 1 only if your checkpoints contain objects other than tensors. |
Checkpoints load with torch.load(..., weights_only=True), which reconstructs only tensors and basic types. A .pt file loaded without this protection is deserialized with pickle and can execute arbitrary code when opened, so full loading is restricted to files you generated yourself and explicitly enabled. From each checkpoint, code takes weights (model or the dictionary itself), step (step), and tokens seen (tokens or tokens_seen). Architecture is inferred from weight shapes except the number of heads, read from config if present, otherwise 12. If vocab_sha256 is saved, it checks agreement with the manifest.
"""Evaluación del modelo base: HellaSwag por verosimilitud, bits por byte, comparación emparejada y muestreo."""
import hashlib
import json
import math
import os
import time
import urllib.error
import urllib.request
from pathlib import Path
import torch
import torch.nn.functional as F
REV = '607a30d783dfa663caf39e06633721c8d4cfcd7e' # revisión fijada de gpt2 en Hugging Face
HERE = Path(os.environ.get('P06_EVAL_DIR', 'p06_eval')).resolve()
HERE.mkdir(parents=True, exist_ok=True)
CKPT_DIR = Path(os.environ.get('P06_CKPT_DIR', 'p06_pretrain/runs/full/snapshots')).resolve()
LIMIT = int(os.environ.get('P06_HS_LIMIT', '10042'))
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
HS_TOTAL = 10042
Z95 = 1.959963984540054
def fetch(url, path):
if not path.exists():
for attempt in range(8):
try:
with urllib.request.urlopen(url, timeout=90) as response:
payload = response.read()
break
except urllib.error.HTTPError as error:
if error.code not in (429, 500, 502, 503, 504) or attempt == 7:
raise
time.sleep(min(60, 5 * 2**attempt))
tmp = path.with_suffix('.tmp')
tmp.write_bytes(payload)
os.replace(tmp, path)
return path.read_bytes()
def hellaswag_rows(limit=LIMIT):
"""Primeras `limit` filas de validación, en orden, con una huella de su contenido."""
limit = min(limit, HS_TOTAL)
rows, digest = [], hashlib.sha256()
for offset in range(0, limit, 100):
count = min(100, HS_TOTAL - offset)
url = ('https://datasets-server.huggingface.co/rows?dataset=Rowan%2Fhellaswag'
f'&config=default&split=validation&offset={offset}&length={count}')
payload = json.loads(fetch(url, HERE / f'hellaswag-{offset:05d}-{count}.json'))
assert payload['num_rows_total'] == HS_TOTAL
assert [r['row_idx'] for r in payload['rows']] == list(range(offset, offset + count))
rows.extend(r['row'] for r in payload['rows'])
rows = rows[:limit]
assert len({r['ind'] for r in rows}) == len(rows), 'identificadores repetidos'
for r in rows:
assert len(r['endings']) == 4 and r['label'] in ('0', '1', '2', '3')
digest.update(json.dumps(r, sort_keys=True, ensure_ascii=False).encode('utf-8'))
return rows, digest.hexdigest()
def logits_of(model, ids):
out = model(ids)
return out.logits if hasattr(out, 'logits') else out
def context_size(model):
return model.context if hasattr(model, 'context') else model.config.n_positions
@torch.no_grad()
def scores(model, ctx, ends):
"""Suma y media de la pérdida de cada final; el contexto no se puntúa."""
assert ctx and all(ends)
max_len = context_size(model)
rows, start = [], []
for ending in ends:
if len(ending) >= max_len:
raise ValueError('el final no cabe con al menos un token de contexto')
prefix = ctx[-(max_len - len(ending)):] # recorta solo el comienzo del contexto
rows.append(prefix + ending)
start.append(len(prefix))
tokens = torch.zeros((len(rows), max(map(len, rows))), dtype=torch.long)
for i, row in enumerate(rows):
tokens[i, :len(row)] = torch.tensor(row) # relleno a la derecha: no afecta a lo anterior
logits = logits_of(model, tokens.to(DEVICE)).float()
out = []
for i, row in enumerate(rows):
segment = logits[i, start[i]-1:len(row)-1] # la posición t predice el token t+1
labels = tokens[i, start[i]:len(row)].to(DEVICE)
total = F.cross_entropy(segment, labels, reduction='sum').item()
out.append((total, total / len(labels)))
return out
def evaluate_examples(model, encode, rows, log_every=1000):
model.eval()
correct = correct_sum = 0
details = []
for idx, row in enumerate(rows):
ctx = encode(row['ctx'])
ends = [encode(' ' + e) for e in row['endings']]
values = scores(model, ctx, ends)
means = [m for _, m in values]
sums = [s for s, _ in values]
pred = min(range(4), key=means.__getitem__) # empate: el menor índice
pred_sum = min(range(4), key=sums.__getitem__)
label = int(row['label'])
correct += pred == label
correct_sum += pred_sum == label
details.append({'ind': row['ind'], 'split_type': row['split_type'], 'label': label,
'prediction': pred, 'prediction_sum': pred_sum, 'mean_losses': means})
if (idx + 1) % log_every == 0:
print(f' {idx+1} ejemplos, acc_norm {correct/(idx+1):.4f}', flush=True)
return correct, correct_sum, details
def wilson(k, n, z=Z95):
p = k / n
d = 1 + z*z/n
center = (p + z*z/(2*n)) / d
half = z * math.sqrt(p*(1-p)/n + z*z/(4*n*n)) / d
return center - half, center + half
def paired(details_a, details_b, z=Z95):
"""Diferencia emparejada de acc_norm (A menos B), intervalo normal y McNemar exacto."""
assert [d['ind'] for d in details_a] == [d['ind'] for d in details_b], 'ejemplos distintos'
n = len(details_a)
hit_a = [d['prediction'] == d['label'] for d in details_a]
hit_b = [d['prediction'] == d['label'] for d in details_b]
b = sum(x and not y for x, y in zip(hit_a, hit_b))
c = sum(y and not x for x, y in zip(hit_a, hit_b))
diff = (b - c) / n
se = math.sqrt(max(0.0, (b + c)/n - diff*diff) / n)
m = b + c
p_value = 1.0 if m == 0 else min(1.0, 2 * sum(math.comb(m, i) for i in range(min(b, c) + 1)) / 2**m)
return {'n': n, 'only_a': b, 'only_b': c, 'difference': diff,
'ci95': [diff - z*se, diff + z*se], 'mcnemar_p': p_value}
@torch.no_grad()
def bits_per_byte(model, encode, texts, eot_id):
"""Cada texto empieza tras el fin de documento de su vocabulario; se suman nats y bytes."""
nats, n_bytes, n_tokens = 0.0, 0, 0
for text in texts:
ids = [eot_id] + encode(text)
if len(ids) > context_size(model):
raise ValueError('texto más largo que el contexto')
x = torch.tensor([ids], device=DEVICE)
logits = logits_of(model, x)[0, :-1].float()
nats += F.cross_entropy(logits, x[0, 1:], reduction='sum').item()
n_bytes += len(text.encode('utf-8'))
n_tokens += len(ids) - 1
return {'bits_per_byte': nats / (n_bytes * math.log(2)), 'tokens': n_tokens, 'bytes': n_bytes,
'loss_per_token': nats / n_tokens, 'ppl_per_token': math.exp(nats / n_tokens)}
def filter_logits(logits, temp, top_k=0, top_p=1.0):
"""Temperatura, después top-k, después top-p; devuelve índices ordenados y probabilidades."""
z = logits.float() / temp
if top_k:
threshold = torch.topk(z, min(top_k, z.numel())).values[-1]
z = z.masked_fill(z < threshold, -torch.inf)
values, indices = torch.sort(z, descending=True, stable=True)
probs = torch.softmax(values, dim=-1)
if top_p < 1.0:
values = values.masked_fill(probs.cumsum(-1) - probs >= top_p, -torch.inf)
return indices, torch.softmax(values, dim=-1)
@torch.no_grad()
def generate(model, encode, decode, prompt, temp, top_k, top_p, eot_id, seed=2026, count=32):
ids = encode(prompt)
generator = torch.Generator(device='cpu').manual_seed(seed)
for _ in range(count):
window = torch.tensor([ids[-context_size(model):]], device=DEVICE)
indices, p = filter_logits(logits_of(model, window)[0, -1], temp, top_k, top_p)
choice = torch.multinomial(p.cpu(), 1, generator=generator).item()
next_id = int(indices[choice].item())
if next_id == eot_id:
break
ids.append(next_id)
return decode(ids)
TEMPS, TOP_KS, TOP_PS = (0.4, 0.7, 1.0, 1.3), (0, 40), (0.8, 0.95, 1.0)
@torch.no_grad()
def sampling_snapshot(model, encode, decode, label, revision, eot_id, prompt='Once upon a time'):
"""Logits del siguiente token y una muestra por configuración, en el formato del panel."""
logits = logits_of(model, torch.tensor([encode(prompt)], device=DEVICE))[0, -1].float().cpu()
top_ids = torch.topk(logits, 8).indices.tolist()
samples = {}
for t in TEMPS:
for k in TOP_KS:
for p in TOP_PS:
samples[f'{t}|{k}|{p}'] = generate(model, encode, decode, prompt, t, k, p, eot_id)
return {'model': label, 'revision': revision, 'prompt': prompt, 'seed': 2026,
'max_new_tokens': 32, 'grid': {'temps': TEMPS, 'top_k': TOP_KS, 'top_p': TOP_PS},
'top_ids': top_ids, 'top_text': [decode([i]) for i in top_ids],
'all_logits': [round(float(x), 4) for x in logits], 'samples': samples}
def write_json(name, data, **kw):
(HERE / name).write_text(json.dumps(data, ensure_ascii=False, **kw), encoding='utf-8')
# ---------- modelo y tokenizador propios, leídos de las lecciones anteriores ----------
def find_project_root():
configured = os.environ.get('P06_PROJECT_ROOT')
candidates = [Path(configured).resolve()] if configured else [Path.cwd(), *Path.cwd().parents]
for candidate in candidates:
if (candidate / 'src/content/lessons/p06/l03-modelo-gpt-y-paridad.mdx').is_file():
return candidate
raise FileNotFoundError('No se encontró la raíz del proyecto; fija P06_PROJECT_ROOT')
def lesson_cell(root, filename, title):
text = (root / 'src/content/lessons/p06' / filename).read_text(encoding='utf-8')
marker = f'```python run runtime=local title="{title}"\n'
return text.split(marker, 1)[1].split('\n```', 1)[0]
def own_assets():
root = find_project_root()
data = Path(os.environ.get('P06_DATA_DIR', 'p06_data')).resolve()
os.environ.setdefault('BPE_DATA_DIR', str(HERE / 'bpe_cache'))
bpe = {'__name__': 'bpe_p06_l01'}
exec(compile(lesson_cell(root, 'l01-tokenizador-bpe.mdx', 'Codificador y entrenador BPE incremental'),
'p06-l01.mdx', 'exec'), bpe)
gpt_cell = lesson_cell(root, 'l03-modelo-gpt-y-paridad.mdx', 'GPT propio y controles')
gpt = {'__name__': 'modelo_p06_l03'}
exec(compile(gpt_cell.split('\nattention_test()\nbehavior_test()', 1)[0], 'p06-l03.mdx', 'exec'), gpt)
manifest = json.loads((data / 'manifest.json').read_text(encoding='utf-8'))
vocab_raw = (data / manifest['vocab_file']).read_bytes()
assert hashlib.sha256(vocab_raw).hexdigest() == manifest['vocab_sha256']
payload = json.loads(vocab_raw)
assert payload['pretokenization'] == bpe['PAT'].pattern
ranks = {bytes.fromhex(k): v for k, v in payload['vocab_hex'].items()}
eot = manifest['eot_id']
encode = bpe['make_text_encoder'](ranks, special_id=eot)
pieces = {v: k for k, v in ranks.items()}
pieces[eot] = payload['special_literal'].encode('utf-8')
decode = lambda ids: b''.join(pieces[i] for i in ids).decode('utf-8', errors='replace')
return gpt['GPT'], encode, decode, eot, manifest['vocab_sha256']
def load_checkpoint(path, GPT, vocab_sha256):
try:
state = torch.load(path, map_location='cpu', weights_only=True)
except Exception as error:
if os.environ.get('P06_TRUST_CKPT') != '1':
raise RuntimeError(f'{path.name} guarda objetos que no son tensores. Si es un fichero '
'tuyo, fija P06_TRUST_CKPT=1; nunca lo hagas con ficheros ajenos.') from error
state = torch.load(path, map_location='cpu', weights_only=False)
if state.get('vocab_sha256', vocab_sha256) != vocab_sha256:
raise ValueError(f'{path.name} se entrenó con otro vocabulario')
weights = state.get('model', state)
weights = {k.removeprefix('_orig_mod.'): v for k, v in weights.items() if torch.is_tensor(v)}
vocab, d = weights['transformer.wte.weight'].shape
layers = 1 + max(int(k.split('.')[2]) for k in weights if k.startswith('transformer.h.'))
config = state.get('config') or {}
heads = int(config.get('heads', config.get('n_head', 12)))
model = GPT(vocab=vocab, context=weights['transformer.wpe.weight'].shape[0],
layers=layers, heads=heads, d=d, dropout=0.0)
model.load_state_dict(weights)
tokens = state.get('tokens', state.get('tokens_seen'))
return model.to(DEVICE).eval(), {'checkpoint': path.name, 'step': state.get('step'),
'tokens': None if tokens is None else int(tokens)}
def plot_curve(curve, reference, path):
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
has_tokens = all(c['tokens'] is not None for c in curve)
x = [c['tokens'] if has_tokens else c['step'] for c in curve]
y = [c['acc_norm'] for c in curve]
low = [c['wilson95'][0] for c in curve]
high = [c['wilson95'][1] for c in curve]
fig, ax = plt.subplots(figsize=(7, 4))
ax.fill_between(x, low, high, alpha=0.25, label='Wilson 95 %')
ax.plot(x, y, marker='o', label='Modelo propio (acc_norm)')
ax.axhline(reference['acc_norm'], color='tab:orange', label='GPT-2 124M, mismo script')
ax.axhline(0.25, color='gray', linestyle='--', label='Azar (25 %)')
ax.set_xlabel('Tokens vistos' if has_tokens else 'Paso')
ax.set_ylabel('Exactitud HellaSwag')
ax.legend()
fig.tight_layout()
fig.savefig(path, dpi=150)
plt.close(fig)
print('Dispositivo:', DEVICE, '| ejemplos:', min(LIMIT, HS_TOTAL), '| resultados en', HERE)npm run lab and open the connection link.The first run downloads GPT-2 weights, about 550 MB, and 101 HellaSwag pages; subsequent runs use cache. The mask control recalculates loss for the first ending without batching or padding, with log_softmax and gather, and requires agreement with the evaluator.
from transformers import GPT2LMHeadModel, GPT2TokenizerFast
tokenizer = GPT2TokenizerFast.from_pretrained('gpt2', revision=REV)
gpt2 = GPT2LMHeadModel.from_pretrained('gpt2', revision=REV).to(DEVICE).eval()
rows, rows_sha256 = hellaswag_rows()
print('Filas:', len(rows), 'huella del contenido:', rows_sha256)
start = time.perf_counter()
correct, correct_sum, gpt2_details = evaluate_examples(gpt2, tokenizer.encode, rows)
n = len(rows)
# Control independiente de la máscara: primer final, sin lote ni relleno
context = tokenizer.encode(rows[0]['ctx'])
ending = tokenizer.encode(' ' + rows[0]['endings'][0])
with torch.no_grad():
raw = gpt2(torch.tensor([context + ending], device=DEVICE)).logits[0].float()
log_p = F.log_softmax(raw[len(context)-1:-1], dim=-1)
direct = -log_p.gather(1, torch.tensor(ending, device=DEVICE)[:, None]).mean().item()
assert abs(direct - gpt2_details[0]['mean_losses'][0]) < 1e-4, (direct, gpt2_details[0])
texts = [r['ctx'] + ' ' + r['endings'][int(r['label'])] for r in rows]
gpt2_bpb = bits_per_byte(gpt2, tokenizer.encode, texts, tokenizer.eos_token_id)
gpt2_summary = {'model': 'gpt2', 'revision': REV, 'n': n, 'rows_sha256': rows_sha256,
'acc': correct_sum / n, 'acc_norm': correct / n, 'correct': correct,
'wilson95': wilson(correct, n), **gpt2_bpb,
'seconds': round(time.perf_counter() - start, 1),
'protocol': 'ctx y espacio+final por separado; acc_norm con la pérdida media del final'}
write_json('hellaswag-gpt2.json', {'summary': gpt2_summary, 'details': gpt2_details}, indent=1)
print(json.dumps(gpt2_summary, ensure_ascii=False, indent=1))
snapshot = sampling_snapshot(gpt2, tokenizer.encode, tokenizer.decode, 'GPT-2 público (124M)', REV,
tokenizer.eos_token_id)
write_json('sampling-gpt2.json', snapshot, separators=(',', ':'))
for key in ('0.4|0|1.0', '1.0|0|0.95', '1.3|0|1.0'):
print(key, repr(snapshot['samples'][key]))npm run lab and open the connection link.With the full set you should see acc_norm near 0.2955 and acc near 0.2859, build-nanogpt’s figures for the same protocol, with Wilson interval around ±0.009. In short verification with P06_HS_LIMIT=32, GPT-2 got 7 of 32 correct, acc_norm 0.21875, Wilson [0.1102, 0.3875]. That interval includes both 25% chance and the 29.55% reference and therefore establishes nothing, precisely the interval’s lesson. In that same short run, text from the 32 rows, context and correct ending, totaled 5136 bytes: GPT-2 encoded them as 1106 tokens with 1.224 bits per byte and per-token perplexity 51.4. Panel samples come from this cell: sampling-gpt2.json uses the format read by the interactive.
The third cell traverses your checkpoints. For each it calculates acc and acc_norm on the same rows and saves per-example details; then it plots the curve against tokens seen, compares the latest checkpoint with GPT-2 in a paired analysis, calculates both models’ bits per byte on the same texts, and generates custom-model samples under the same configurations.
paths = sorted(CKPT_DIR.rglob('*.pt'))
if not paths:
print('No hay checkpoints en', CKPT_DIR, '; fija P06_CKPT_DIR con la carpeta de p06-l06.')
else:
GPT, own_encode, own_decode, own_eot, vocab_sha256 = own_assets()
curve, last = [], None
for path in paths:
model, meta = load_checkpoint(path, GPT, vocab_sha256)
print('Evaluando', meta, flush=True)
k, k_sum, details = evaluate_examples(model, own_encode, rows)
point = {**meta, 'acc': k_sum / n, 'acc_norm': k / n, 'correct': k, 'wilson95': wilson(k, n)}
write_json(f'hellaswag-{path.stem}.json', {'summary': point, 'details': details}, indent=1)
curve.append(point)
if last is None or (point['step'] or 0) >= (last[0]['step'] or 0):
last = (point, details, path)
del model
curve.sort(key=lambda c: (c['tokens'] if c['tokens'] is not None else -1, c['step'] or 0))
write_json('curve.json', {'reference': gpt2_summary, 'curve': curve}, indent=1)
plot_curve(curve, gpt2_summary, HERE / 'curve.png')
final, final_details, final_path = last
comparison = paired(final_details, gpt2_details)
model, _ = load_checkpoint(final_path, GPT, vocab_sha256)
own_bpb = bits_per_byte(model, own_encode, texts, own_eot)
report = {'own': final, 'gpt2': gpt2_summary, 'paired_own_minus_gpt2': comparison,
'bpb_own': own_bpb, 'bpb_gpt2': gpt2_bpb,
'above_chance': final['wilson95'][0] > 0.25}
write_json('comparison.json', report, indent=1)
print(json.dumps(report, ensure_ascii=False, indent=1))
own = sampling_snapshot(model, own_encode, own_decode, f'Modelo propio ({final_path.name})',
vocab_sha256, own_eot)
write_json('sampling-own.json', own, separators=(',', ':'))
print('Curva en', HERE / 'curve.png', '| muestras en', HERE / 'sampling-own.json')npm run lab and open the connection link.How to check the result:
- The evaluator is validated if GPT-2 reaches
acc_normaround 0.2955 on all 10042 examples and passes the mask check. To test the custom-model path before useful checkpoints exist, use a freshly initialized one: per-token loss should be near , counting the end-of-document ID, accuracy should be compatible with 25%, and the same 5136 bytes occupy about 2500 custom tokens versus GPT-2’s 1106. This is how the cell was verified with two random two-layer checkpoints. - Your model exceeds chance if
above_chanceis true: the latest checkpoint’s Wilson lower endpoint exceeds 0.25. - The curve makes sense if
acc_normrises noisily across checkpoints as p06-l06 validation loss falls. A flat 0.25 curve with decreasing loss usually means the model has not yet learned what HellaSwag measures, or there is a tokenizer error. A sharp upward jump warrants a contamination search. - The comparison is honest if you report paired difference with interval and McNemar p-value, both models’ bits per byte on the same texts, and the preceding section’s data, token, and compute table.
To display your model in the panel above, copy sampling-own.json over src/widgets/p06/l07/sampling.json: the interactive reads model name, prompt, logits, and samples from that file. Compare samples from early and final checkpoints. The transition from nonsense to grammatical sentences usually occurs long before HellaSwag separates from chance, and this gap between fluency and understanding summarizes the lesson.
Exercises
import numpy as np
def score_completion(model, context_ids, ending_ids):
pass