最终检查点性能评测、困惑度核算与生成连贯性审计
Agent 辅助工程检查
前置要求
第 59 天云端预训练执行经验与第 53 天验证指标计算。
学习目标
在留出验证集(Held-out Validation Set)上系统评估最终收敛检查点,测算验证损失与困惑度(Perplexity),执行温度受控自回归采样审计生成连贯性。
操作指引
1. 用 map_location='cpu'(或你的 GPU)加载最终检查点,把其中的 'model' 状态加载到新构建的模型中,并调用 model.eval()。
2. 构建一个固定的留出验证批次列表,使两个检查点总在相同的词元上比较。
3. 在 torch.no_grad() 中把 L_val 计算为这些批次的平均交叉熵,再得 PPL = exp(L_val)。
4. 与均匀基线 ln(V) 比较:字符级 Shakespeare 的 V = 65,ln(65) = 4.1744,所以 L_val 低于 4.0 说明模型胜过瞎猜。
5. 用同一提示以 temperature=0.8、top_k=40 生成五个样本,并逐个检查退化循环(同一词元长串重复,或不同词元过少)。
6. 亲自阅读样本,并记录检查点步数、L_val、PPL、样本、解码设置和随机种子。
时间安排(120 分钟):阅读 20 + 练习 70 + 检查 30。 阅读:nanoGPT 中的 estimate_loss 与采样代码,以及 CS336 关于评估的笔记。练习:在最终检查点上完成第 1-6 步。检查:不看笔记,从 ln(V) 解释 L_val 和 PPL 的阈值。
自主演练与记录
运行最终模型评测脚本。断言验证损失低于随机初始化水平(Shakespeare 上 L_val < 4.0,或 PPL < 50),且生成文本中没有重复的单 Token 死循环。
利用 math.exp(val_loss) 输出困惑度指标并断言其数值合理性。
import math
import torch
@torch.no_grad()
def estimate_loss(model, val_batches):
# Mean cross-entropy over a FIXED list of held-out (x, y) batches, so two checkpoints are
# compared on identical tokens. model(x, y) returns (logits, loss) as in the Day 48 model.
model.eval()
losses = [model(x, y)[1].item() for x, y in val_batches]
return sum(losses) / len(losses)
@torch.no_grad()
def generate_sample(model, idx, max_new_tokens=100, temperature=0.8, top_k=40, block_size=256):
model.eval()
for _ in range(max_new_tokens):
logits, _ = model(idx[:, -block_size:])
logits = logits[:, -1, :] / temperature
kth = torch.topk(logits, top_k).values[:, [-1]]
logits[logits < kth] = float('-inf') # keep only the top_k candidates
idx = torch.cat([idx, torch.multinomial(torch.softmax(logits, dim=-1), 1)], dim=1)
return idx
def has_token_loop(tokens, max_run=8, min_distinct_ratio=0.3):
# Degenerate output: one token repeated more than max_run times in a row,
# or too few distinct tokens overall (e.g. 'the the the ...').
longest = run = 1
for a, b in zip(tokens, tokens[1:]):
run = run + 1 if a == b else 1
longest = max(longest, run)
return longest > max_run or len(set(tokens)) / len(tokens) < min_distinct_ratio
ckpt = torch.load('ckpt.pt', map_location='cpu')
model.load_state_dict(ckpt['model'])
model.eval()
val_loss = estimate_loss(model, val_batches)
ppl = math.exp(val_loss)
print(f'L_val={val_loss:.4f} PPL={ppl:.2f} uniform baseline ln(V)={math.log(vocab_size):.4f}')
prompt = torch.tensor([encode('Once upon a time')])
samples = [generate_sample(model, prompt)[0, prompt.size(1):].tolist() for _ in range(5)]
# Why these thresholds: an untrained model guesses uniformly, so its loss is ln(V).
# For character-level Shakespeare V = 65 and ln(65) = 4.1744, so L_val < 4.0 means the model beats
# guessing; PPL < 50 is the same check for a larger vocabulary (ln(50) = 3.9120).
assert val_loss < math.log(vocab_size)
assert ppl < 50.0
assert not any(has_token_loop(s) for s in samples)
for s in samples:
print(repr(decode(s))) # read them: grammatical fragments, names, line breaks; not one token
# Record: checkpoint step, L_val, PPL, the five samples, temperature=0.8, top_k=40 and the seed.
能够以客观的困惑度指标与文本多样性度量,全面证实预训练模型的收敛质量。
权威源资源与权利证明
nanoGPT: train.py pretraining loop
对应章节 / 时间戳: train.py: estimate_loss() averages eval_iters batches per split; run every eval_interval; best_val_loss decides when a checkpoint is saved
验证版本与日期: Git master commit 71c3905 (Verified: 2026-10-30)
Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.
Python, PyTorch, and Day 46-48 Transformer model architecture.
Runnable pretraining scripts and step-by-step tensor mechanics are fully self-contained in the curriculum lessons.
对比候选资源与选型分析 (2)
Heavy abstraction layer wrapping distributed training; nanoGPT exposes raw PyTorch loops without framework overhead.
High-performance enterprise distributed framework; unsuitable for local educational first-principles comprehension.
CS336 Assignment 1: Basics (Spring 2025 tagged release)
对应章节 / 时间戳: README setup; tests/adapters.py; tests/test_optimizer.py; tests/test_nn_utils.py; tests/test_serialization.py
验证版本与日期: spring2025 tag; README, tests and MIT LICENSE checked 2026-11-01
Lead assignment-driven source for pretraining component practice and tests. nanoGPT remains a compact historical code-reading companion, not the current recommended training curriculum.
Fluent Python, PyTorch, and linear algebra
Local self-contained pretraining scripts run on standard local CPUs or budget GPUs without Stanford cluster dependency.
对比候选资源与选型分析 (2)
Simpler code layout, useful complementary reference for minimal PyTorch Transformer.
High-level API focus rather than building from raw tensor fundamentals.