最終チェックポイント検証、パープレキシティと生成品質評価
Agent支援エンジニアリングチェック
前提条件
第59日クラウド事前学習実行および第53日検証評価メトリクス。
学習目標
留保検証データセット上で最終チェックポイントを評価し、検証損失とパープレキシティを算出し、自己回帰サンプリングでテキストの一貫性を検証する。
手順
1. 最終チェックポイントを map_location='cpu'(または GPU)で読み込み、新しく構築したモデルにその 'model' 状態を読み込んで model.eval() を呼ぶ。
2. 保持しておいた検証バッチの固定リストを作り、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 でサンプルを 5 つ生成し、それぞれについて退化したループ(1 つのトークンの長い連続、または異なるトークンが少なすぎる)を調べる。
6. サンプルを自分で読み、チェックポイントのステップ、L_val、PPL、サンプル、デコード設定、シードを記録する。
時間配分(120 分):読解 20 + 演習 70 + 確認 30。 読解:nanoGPT の estimate_loss とサンプリングのコード、CS336 の評価に関するノート。演習:最終チェックポイントで手順 1-6。確認:L_val と PPL の閾値を ln(V) からノートなしで説明する。
演習と予測記録
最終チェックポイントで評価スクリプトを実行せよ。検証損失がランダム初期化より低いこと(Shakespeare では L_val < 4.0、または PPL < 50)と、生成文に単一トークンの反復ループが含まれないことを assert する。
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.