最終檢查點性能評測、困惑度核算與生成連貫性審計
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.