Now also available as a video workshop:
We will be working towards a 14,585,856 model:
GPT(
(embed_tokens): Embedding(10000, 384)
(embed_positions): Embedding(256, 384)
(drop): Dropout(p=0.1, inplace=False)
(blocks): ModuleList(
(0-5): 6 x Block(
(attn_norm): LayerNorm((384,), eps=1e-05, elementwise_affine=True)
(attn): CausalSelfAttention(
(q_proj): Linear(in_features=384, out_features=384, bias=True)
(k_proj): Linear(in_features=384, out_features=384, bias=True)
(v_proj): Linear(in_features=384, out_features=384, bias=True)
(o_proj): Linear(in_features=384, out_features=384, bias=True)
(attn_dropout): Dropout(p=0.1, inplace=False)
(resid_dropout): Dropout(p=0.1, inplace=False)
)
(mlp_norm): LayerNorm((384,), eps=1e-05, elementwise_affine=True)
(mlp): MLP(
(up_proj): Linear(in_features=384, out_features=1536, bias=True)
(down_proj): Linear(in_features=1536, out_features=384, bias=True)
(dropout): Dropout(p=0.1, inplace=False)
)
)
)
(norm): LayerNorm((384,), eps=1e-05, elementwise_affine=True)
(lm_head): Linear(in_features=384, out_features=10000, bias=False)
)The data is from TinyStories, and the bulk of the architecture and methods come from Attention Is All You Need and Direct Preference Optimization.
Setting Up + Data
import math
import os
import re
import time
from collections import Counter
from dataclasses import dataclass
import pandas as pd
import ast
import copy
import numpy as np
import requests
import torch
import torch.nn as nn
from torch.nn import functional as F
import matplotlib.pyplot as plt
device = "cpu"
if torch.cuda.is_available():
device = "cuda"
if torch.backends.mps.is_available():
device = "mps"
torch.manual_seed(42)
np.random.seed(42)
rng = np.random.default_rng(0)
BASE_PATH = "./"
HF = "https://huggingface.co/datasets/roneneldan"
FILES = [ # (url, filename, capped?)
(f"{HF}/TinyStories/resolve/main/TinyStoriesV2-GPT4-train.txt", "pretrain_train.txt", True),
(f"{HF}/TinyStories/resolve/main/TinyStoriesV2-GPT4-valid.txt", "pretrain_valid.txt", False),
(f"{HF}/TinyStoriesInstruct/resolve/main/TinyStories-Instruct-train.txt", "instruct_train.txt", True),
(f"{HF}/TinyStoriesInstruct/resolve/main/TinyStories-Instruct-valid.txt", "instruct_valid.txt", False),
]
EOT = "<|endoftext|>"
MAX_TRAIN_BYTES = 80 * 1024 * 1024 # ~80 MB per large train file
data_dir = os.path.join(BASE_PATH, "data")
os.makedirs(data_dir, exist_ok=True)
for url, name, capped in FILES:
path = os.path.join(data_dir, name)
with requests.get(url, stream=True, timeout=60) as r:
buf = bytearray()
for chunk in r.iter_content(chunk_size=1 << 20):
buf.extend(chunk)
if capped and len(buf) >= MAX_TRAIN_BYTES:
break
text = buf.decode("utf-8", errors="ignore")
if capped:
text = text[: text.rfind(EOT) + len(EOT)]
with open(path, "w", encoding="utf-8") as f:
f.write(text)
print(f"{name}: {len(text) / 1e6:.1f} MB, ~{text.count(EOT)} stories")The Model
@dataclass
class GPTConfig:
vocab_size: int = 10000
block_size: int = 256 # max context length
n_layer: int = 6
n_head: int = 6
n_embd: int = 384 # must be divisible by n_head
dropout: float = 0.1
bias: bool = True # bias in Linear/LayerNorm, like GPT-2
# Multi-head causal self-attention: the only layer where tokens exchange
# information, and only backward (token t sees tokens 0..t).
class CausalSelfAttention(nn.Module):
def __init__(self, cfg: GPTConfig):
super().__init__()
self.n_head = cfg.n_head
# Each position emits a query ("what am I looking for"), a key ("what
# do I contain") and a value ("what do I pass along if attended to").
self.q_proj = nn.Linear(cfg.n_embd, cfg.n_embd, bias=cfg.bias) # 384*384 + 384 = 147,840
self.k_proj = nn.Linear(cfg.n_embd, cfg.n_embd, bias=cfg.bias) # 147,840
self.v_proj = nn.Linear(cfg.n_embd, cfg.n_embd, bias=cfg.bias) # 147,840
self.o_proj = nn.Linear(cfg.n_embd, cfg.n_embd, bias=cfg.bias) # 147,840 -> attention total 591,360 - mixes heads back
self.attn_dropout = nn.Dropout(cfg.dropout) # on the attention weights
self.resid_dropout = nn.Dropout(cfg.dropout) # on the output
# Lower-triangular boolean mask: True where attention is allowed.
# A buffer moves with .to(device) but is not a trainable parameter.
self.register_buffer(
"mask", torch.tril(torch.ones(cfg.block_size, cfg.block_size, dtype=torch.bool))
)
def forward(self, x): # x: (B, T, 384)
B, T, C = x.shape
q = self.q_proj(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
k = self.k_proj(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
v = self.v_proj(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
att = (q @ k.transpose(-2, -1)) / math.sqrt(k.size(-1)) # (B, nh, T, T)
att = att.masked_fill(~self.mask[:T, :T], float("-inf")) # plain lower triangle
att = self.attn_dropout(F.softmax(att, dim=-1))
y = att @ v
y = y.transpose(1, 2).contiguous().view(B, T, C)
return self.resid_dropout(self.o_proj(y)) # one return value, no (k, v)
def gelu(x):
# x * P(N(0,1) <= x): pass x in proportion to how "typically positive" it is.
# Big positive x -> ~x (like identity), big negative -> ~0 (like ReLU), with
# a smooth dip around 0 instead of ReLU's hard corner.
return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
# Position-wise feed-forward: attention moves info between tokens, this
# processes each token independently. Expand 4x, nonlinearity, project back.
class MLP(nn.Module):
def __init__(self, cfg: GPTConfig):
super().__init__()
self.up_proj = nn.Linear(cfg.n_embd, 4 * cfg.n_embd, bias=cfg.bias) # 384*1536 + 1536 = 591,360
self.down_proj = nn.Linear(4 * cfg.n_embd, cfg.n_embd, bias=cfg.bias) # 1536*384 + 384 = 590,208
self.dropout = nn.Dropout(cfg.dropout)
def forward(self, x):
# GELU = smooth ReLU; the standard transformer activation
return self.dropout(self.down_proj(gelu(self.up_proj(x))))
# One transformer block. Pre-norm (LayerNorm before each sublayer, not after)
# keeps a clean identity path through the residuals, which is what makes
# stacking many blocks trainable: each block adds a small correction to the
# running representation instead of replacing it.
class Block(nn.Module):
def __init__(self, cfg: GPTConfig):
super().__init__()
self.attn_norm = nn.LayerNorm(cfg.n_embd, bias=cfg.bias) # 384 + 384 = 768
self.attn = CausalSelfAttention(cfg) # 591,360
self.mlp_norm = nn.LayerNorm(cfg.n_embd, bias=cfg.bias) # 768
self.mlp = MLP(cfg) # 1,181,568 -> block total 1,774,464
def forward(self, x):
x = x + self.attn(self.attn_norm(x)) # residual add: keep x, add attention's correction
x = x + self.mlp(self.mlp_norm(x))
return x
# Cross-entropy with ignore_index=-1, written out: per-token loss is
# -log p(true next token); positions with target -1 (prompt/padding) are
# masked out, and we average over the supervised positions only.
def _cross_entropy(logits, targets):
logp = F.log_softmax(logits, dim=-1) # stable log-probs (never log(softmax(...)))
valid = targets != -1
safe = targets.clamp(min=0) # -1 is an invalid gather index; value irrelevant, masked below
nll = -logp.gather(1, safe.unsqueeze(1)).squeeze(1)
return (nll * valid).sum() / valid.sum()
class GPT(nn.Module):
def __init__(self, cfg: GPTConfig):
super().__init__()
self.cfg = cfg
self.embed_tokens = nn.Embedding(cfg.vocab_size, cfg.n_embd) # 10000*384 = 3,840,000
self.embed_positions = nn.Embedding(cfg.block_size, cfg.n_embd) # 256*384 = 98,304
self.drop = nn.Dropout(cfg.dropout)
self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg.n_layer)]) # 6 * 1,774,464 = 10,646,784
self.norm = nn.LayerNorm(cfg.n_embd, bias=cfg.bias) # 768
self.lm_head = nn.Linear(cfg.n_embd, cfg.vocab_size, bias=False) # 3,840,000, tied -> +0
self.embed_tokens.weight = self.lm_head.weight # weight tying: same matrix both ways
self._init_weights()
# GPT-2 init: weights ~ N(0, 0.02), biases zero. Residual output projections
# (o_proj, down_proj) are scaled down by sqrt(2*n_layer) because each block
# adds two residual contributions and we want the stream's variance flat with depth.
def _init_weights(self):
residual_projs = ("o_proj", "down_proj")
for name, m in self.named_modules():
if isinstance(m, (nn.Linear, nn.Embedding)):
std = 0.02 / math.sqrt(2 * self.cfg.n_layer) if name.endswith(residual_projs) else 0.02
nn.init.normal_(m.weight, mean=0.0, std=std)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.zeros_(m.bias)
def num_params(self):
return sum(p.numel() for p in self.parameters()) # tied weight counted once
def forward(self, idx, targets=None):
B, T = idx.shape
pos = torch.arange(T, device=idx.device) # always 0..T-1, no offset
x = self.drop(self.embed_tokens(idx) + self.embed_positions(pos))
for block in self.blocks: # plain loop, nothing collected
x = block(x)
x = self.norm(x)
logits = self.lm_head(x)
loss = None
if targets is not None:
loss = _cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
return logits, loss
@torch.no_grad()
def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None, eos_id=None):
for _ in range(max_new_tokens):
idx_cond = idx[:, -self.cfg.block_size:] # whole context, cropped to the window
logits, _ = self(idx_cond) # re-run EVERY token through all 6 blocks
logits = logits[:, -1, :] / max(temperature, 1e-6)
if top_k is not None:
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
logits[logits < v[:, [-1]]] = -float("inf")
next_id = torch.multinomial(F.softmax(logits, dim=-1), 1)
idx = torch.cat([idx, next_id], dim=1)
if eos_id is not None and (next_id == eos_id).all():
break
return idx
Sampling
The model is untrained, so random results:
cfg = GPTConfig()
model = GPT(cfg).to(device)
def sample_story(model, prompt="Once", n=80, temperature=0.8, top_k=50, eos_id=None):
model.eval()
ids = tok.encode(prompt)
out = model.generate(torch.tensor([ids], device=device), max_new_tokens=n,
temperature=temperature, top_k=top_k, eos_id=eos_id)
model.train()
return tok.decode(out[0].tolist()[len(ids):]) # continuation only, prompt sliced off
for i in range(3):
print(f"\n--- sample {i} ---\n{sample_story(model, 'Once upon a time', n=160, eos_id=EOT_ID)}")--- sample 0 ---
juggling tried inquisitive salad milk howling milk bits Terry preventing questioned lack pressing pressing Pete stars cop zoo stars milk Gary Chair warms Fun information denied safaris managed cleared stitches relaxed annoying lot Sparkle carving commotion Luckily preventing Touch litter blasted arrived shouts lemon tugging sensible helicopters or pack shorter disagree Especially Spot department ending bathtub knobs medal syrup syrup Adventure popsicle managed raven helpfulness Forky Gill Fragile dip mustn tingle carefree mosquito practices Twinkle Flash Betty porcupine ants screwdriver ruled hotel splattered flashing cop haircuts pressing eagle unlucky unlucky shorter Shiny scribble anyway Maureen oohed hunter unpacks unpacks cooled meowed meowed cleanest boldly Jennie 2 Rod possible Lucas yoga rely headphones birds Flap solutions Water acrobats neighborhood benches shadows flashing lack jogs jogs disagrees Boys taped sled Poor alert sleepover cop loopy reasons Gill caw vendor crash Boo preventing lot clothing resists villagers screwdriver shoots lantern trimmed morning morning scenery represents Granddaughter flips keeper keeper digger baker smarts Carrots
--- sample 1 ---
saddle shells ditch Matches parts twig sugary bits ballet basement preventing Bury Crazy basement disagreeing vehicle worst girl Bury cleanest ditch freezes cork cork neighbour herb wood notebook Old pretended ahead Fragile shops once blessing blessing dumb cork very conquer bother spends warms rainbow unison helping pleased recognized cartwheels stopped puzzle or endings Louie oneself wobble Flash cop rather cartwheels snatches gazes cartwheels step leans represents Circle Frog pressing scatters groaned 50 turns taped boos raven thermometer accused m porcupine sang Together preventing monster customer freshly preventing monster unhealthy knobs video increases sunset silk demand recognized jumps devoured steaks Adventure tiara second cells There There refused Winky spirits helicopters performing tippy lava clumsiness Chairy tumbling stalls Terry Glenda shaping values scribble Water echoed driver driver Ding directions snowed Coco " toes intentions befriends join reasons thirty conflicts Strawberry Puff tiara fold catch apples Voice holidays Jonny whimpering haircuts 5 bringing go Rod Rod strike activity over figures Lucas wand carousel
--- sample 2 ---
poison accessories progress nearer ramp correct correct germs Joy oneself Adventure reunited tickle rats rhymes condition echoed But section porcupine each prettiest robber ghost 5 radio radio afford Puddles raven puzzle boos Because accessories unpacks cleans bustling snowing France intentions thirty warms girl pigeons Yield scolded Nikki slime fives Rod beyond Enough lit improving laugh laugh filled person sounded knobs clues pets cracked re re imagine calm why ballet wander petal wicked watering Days achieved vendor disagreed Fuzzy Ken Ken milk tiger shuts salty blasted Lucas blow Dare far unpacks porcupine Good walker lack plop phones Looks tugging mesmerised mommies Crab dipped dentist relationship Subway James both both tugging directions raven boldly rack ghost no logs presents accepting organised Was accessories interest legs soon hammers yawned cooed honey sleepover earthquake earthquake deer Knives Knives tangy limp loosen represents projects loosen thirty Jennie tiptoed locks heal Because hippo wheelchair threatening unsuccessful moved Blu squeaked cop language poured surface radio Jennifer turnsPretraining
def encode_file(src_path, dst_path, tokenizer):
with open(src_path, encoding="utf-8") as f:
text = f.read()
arr = np.asarray(tokenizer.encode(text), dtype=np.uint16)
arr.tofile(dst_path)
print(f"{os.path.basename(src_path)}: {len(arr):,} tokens -> {os.path.basename(dst_path)} ({arr.nbytes / 1e6:.1f} MB)")
data = os.path.join(BASE_PATH, "data")
encode_file(os.path.join(data, "pretrain_train.txt"), os.path.join(data, "pretrain_train.bin"), tok)
encode_file(os.path.join(data, "pretrain_valid.txt"), os.path.join(data, "pretrain_val.bin"), tok)
def make_batch_fn(bin_path, block_size, batch_size, device):
data = np.memmap(bin_path, dtype=np.uint16, mode="r")
def get_batch():
ix = torch.randint(len(data) - block_size - 1, (batch_size,))
x = torch.stack([torch.from_numpy(data[i:i + block_size].astype(np.int64)) for i in ix])
# target = same window shifted one right: position t learns token t+1
y = torch.stack([torch.from_numpy(data[i + 1:i + 1 + block_size].astype(np.int64)) for i in ix])
return x.to(device), y.to(device)
return get_batch
@torch.no_grad()
def estimate_loss(model, iters=20):
model.eval()
out = {}
for split, fn in {"train": get_train_batch, "val": get_val_batch}.items():
out[split] = sum(model(*fn())[1].item() for _ in range(iters)) / iters
model.train()
return out
batch_size = 48
data_dir = os.path.join(BASE_PATH, "data")
get_train_batch = make_batch_fn(os.path.join(data_dir, "pretrain_train.bin"), cfg.block_size, batch_size, device)
get_val_batch = make_batch_fn(os.path.join(data_dir, "pretrain_val.bin"), cfg.block_size, batch_size, device)
lr = 6e-4
weight_decay = 0.1
betas = (0.9, 0.95) # beta2 below the 0.999 default — standard for noisy LM gradients
sched_iters = 8000 # cosine reaches its floor here
# Average loss over many batches with dropout off; a single batch is too noisy
# to compare train vs val.
@torch.no_grad()
def estimate_loss(model, iters=20):
model.eval()
out = {}
for split, fn in {"train": get_train_batch, "val": get_val_batch}.items():
out[split] = sum(model(*fn())[1].item() for _ in range(iters)) / iters
model.train()
return out
batch_size = 48
data_dir = os.path.join(BASE_PATH, "data")
get_train_batch = make_batch_fn(os.path.join(data_dir, "pretrain_train.bin"), cfg.block_size, batch_size, device)
get_val_batch = make_batch_fn(os.path.join(data_dir, "pretrain_val.bin"), cfg.block_size, batch_size, device)
lr = 6e-4
weight_decay = 0.1
betas = (0.9, 0.95) # beta2 below the 0.999 default — standard for noisy LM gradients
sched_iters = 8000 # cosine reaches its floor here
# Decay the weight matrices (dim >= 2), not biases/LayerNorm params — decaying
# those toward zero fights normalization instead of regularizing.
params = [p for p in model.parameters() if p.requires_grad]
opt = torch.optim.AdamW([
{"params": [p for p in params if p.dim() >= 2], "weight_decay": weight_decay},
{"params": [p for p in params if p.dim() < 2], "weight_decay": 0.0},
], lr=lr, betas=betas)
# LR schedule: linear warmup, then cosine decay.
# Warmup: Adam's per-parameter step sizes are garbage for the first ~100 steps
# (moment estimates are still mostly zeros), so ramp the lr up from ~0.
# Cosine: decay smoothly to lr/10 so late steps make small, careful updates.
min_lr = lr / 10
warmup = 100
scheduler = torch.optim.lr_scheduler.SequentialLR(opt, [
torch.optim.lr_scheduler.LinearLR(opt, start_factor=1e-8, total_iters=warmup),
torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=sched_iters - warmup, eta_min=min_lr),
], milestones=[warmup])
minutes = 10.0
eval_interval = 500
t0 = last_log = time.time()
deadline = t0 + minutes * 60
it = tok_seen = 0
while time.time() < deadline:
x, y = get_train_batch()
opt.zero_grad(set_to_none=True) # gradients accumulate by default — clear last step's
_, loss = model(x, y) # forward: mean next-token cross-entropy over B*T positions
loss.backward() # backward: dL/dp for every parameter
# cap total gradient norm at 1.0 — a rare bad batch can't blow up the weights
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step() # AdamW update
scheduler.step() # then advance lr (order matters)
it += 1
tok_seen += x.numel()
if it % 50 == 0:
now = time.time()
tps = 50 * batch_size * cfg.block_size / (now - last_log)
last_log = now
print(f"iter {it:5d} | loss {loss.item():.3f} | lr {opt.param_groups[0]['lr']:.2e} | "
f"{tps:,.0f} tok/s | {(now - t0) / 60:.1f} min", flush=True)
if it % eval_interval == 0:
losses = estimate_loss(model) # train ≈ val so far: 1 epoch on TinyStories, no overfit yet
print(f" >> eval: train {losses['train']:.3f} val {losses['val']:.3f}", flush=True)
print(" sample:", sample_story(model), flush=True) # watch fluency emerge
torch.save({"model": model.state_dict(), "config": cfg.__dict__}, os.path.join(BASE_PATH, "ckpt_base.pt"))
print(f"\nDONE iters={it} tok_seen={tok_seen:,} time={(time.time() - t0) / 60:.1f} min")
base = copy.deepcopy(model).eval()iter 50 | loss 5.384 | lr 3.00e-04 | 27,141 tok/s | 0.4 min
iter 100 | loss 4.086 | lr 6.00e-04 | 26,165 tok/s | 0.8 min
iter 150 | loss 3.698 | lr 6.00e-04 | 24,933 tok/s | 1.2 min
iter 200 | loss 3.339 | lr 6.00e-04 | 25,133 tok/s | 1.6 min
iter 250 | loss 3.279 | lr 6.00e-04 | 25,559 tok/s | 2.0 min
iter 300 | loss 3.153 | lr 5.99e-04 | 25,306 tok/s | 2.4 min
iter 350 | loss 3.003 | lr 5.99e-04 | 25,300 tok/s | 2.8 min
iter 400 | loss 2.929 | lr 5.98e-04 | 25,300 tok/s | 3.2 min
iter 450 | loss 2.824 | lr 5.97e-04 | 25,282 tok/s | 3.6 min
iter 500 | loss 2.727 | lr 5.97e-04 | 25,290 tok/s | 4.0 min
>> eval: train 2.677 val 2.659
sample: upon a time , there was a little girl named Sally . She was very excited to go to see her mom and her mum . She said , " It ' s a great job !" Jane smiled and said , " It ' s easy for finding a nap !" Her mom nodded , and said , " I would have fun with a long time , but be scared to do it was too far away .SFT
MARKER = "Story:"
# Parse the instruct corpus -> list of (token ids, prompt length). prompt_len
# tells make_batch which positions to mask.
def build_examples(path, tok, block_size, eot, limit=None):
with open(path, encoding="utf-8") as f:
docs = [d.strip() for d in f.read().split(EOT) if d.strip()][:limit]
examples = []
for d in docs:
i = d.find(MARKER)
if i == -1:
continue
prompt = tok.encode(d[: i + len(MARKER)])
comp = tok.encode(d[i + len(MARKER):].strip())
if not comp:
continue
ids = (prompt + comp + [eot])[: block_size + 1]
if len(ids) > len(prompt): # truncation must leave some completion
examples.append((ids, len(prompt)))
return examples
# Build one padded batch. Inputs pad with PAD, targets with -1, so padding is
# ignored by the loss. Targets at positions 0..plen-2 are also -1: those predict
# prompt tokens. The last prompt position predicts the first story token, so
# masking stops one short of plen. Right-padding is safe under causal attention.
def make_batch(examples, idxs, pad_id, device):
maxlen = max(len(examples[i][0]) for i in idxs)
X = np.full((len(idxs), maxlen - 1), pad_id, dtype=np.int64)
Y = np.full((len(idxs), maxlen - 1), -1, dtype=np.int64)
for r, i in enumerate(idxs):
ids, plen = examples[i]
X[r, : len(ids) - 1] = ids[:-1]
Y[r, plen - 1 : len(ids) - 1] = ids[plen:]
return torch.from_numpy(X).to(device), torch.from_numpy(Y).to(device)
# Completion-masked loss on a held-out example set. Counts only story tokens,
# so it's NOT comparable to pretraining loss — track it over time: val rising
# while train falls = memorizing the SFT set.
@torch.no_grad()
def estimate_sft_loss(model, examples, iters=20):
model.eval()
losses = []
for _ in range(iters):
idxs = torch.randint(len(examples), (batch_size,)).tolist()
_, loss = model(*make_batch(examples, idxs, PAD_ID, device))
losses.append(loss.item())
model.train()
return sum(losses) / iters
minutes = 5.0
max_iters = 100_000
batch_size = 48
lr = 2e-4 # lower than pretraining: nudge behavior, don't overwrite the base
eval_interval = 250
data_dir = os.path.join(BASE_PATH, "data")
examples = build_examples(os.path.join(data_dir, "instruct_train.txt"), tok, cfg.block_size, EOT_ID, limit=40_000)
val_examples = build_examples(os.path.join(data_dir, "instruct_valid.txt"), tok, cfg.block_size, EOT_ID, limit=5000)
print(f"SFT examples: {len(examples):,} (held-out val {len(val_examples):,})", flush=True)
params = [p for p in model.parameters() if p.requires_grad]
opt = torch.optim.AdamW([
{"params": [p for p in params if p.dim() >= 2], "weight_decay": weight_decay},
{"params": [p for p in params if p.dim() < 2], "weight_decay": 0.0},
], lr=lr, betas=betas)
demo_prompt = ("Features: Dialogue\nWords: dog, happy, park\n"
"Summary: A dog makes a new friend at the park.\nStory:")
t0 = time.time()
deadline = t0 + minutes * 60
it = 0
while it < max_iters and time.time() < deadline:
idxs = torch.randint(len(examples), (batch_size,)).tolist()
x, y = make_batch(examples, idxs, PAD_ID, device)
_, loss = model(x, y) # prompt/pad targets are -1, so loss covers story tokens only
opt.zero_grad(set_to_none=True)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
it += 1
if it % 50 == 0:
print(f"iter {it:5d} | loss {loss.item():.3f} | {(time.time() - t0) / 60:.1f} min", flush=True)
if it % eval_interval == 0:
val_loss = estimate_sft_loss(model, val_examples)
print(f" >> eval iter {it}: val_loss {val_loss:.3f} ", flush=True)
# fixed hand-written prompt (not from val): does it follow Words/Features and stop at EOT?
story = sample_story(model, demo_prompt, n=120, eos_id=EOT_ID)
print(" --- sample story ---\n " + story.replace("\n", "\n "), flush=True)
torch.save({"model": model.state_dict(), "config": cfg.__dict__}, os.path.join(BASE_PATH, "ckpt_sft.pt"))
sft = copy.deepcopy(model).eval()prompt = ("Features: Dialogue\nWords: dog, happy, park\n"
"Summary: A dog makes a new friend at the park.\nStory:")
for i in range(3):
print(f"\n--- sample {i} ---\n{sample_story(model, prompt, n=160, eos_id=EOT_ID)}")Direct Preference Optimization
Rewards
POSITIVE_WORDS = {
"happy", "happily", "joy", "joyful", "smile", "smiled", "smiling", "laugh",
"laughed", "laughing", "fun", "love", "loved", "loving", "kind", "kindly",
"friend", "friends", "friendly", "play", "played", "playing", "good", "great",
"wonderful", "nice", "proud", "excited", "cheer", "cheered", "hug", "hugged",
"share", "shared", "sharing", "brave", "safe", "warm", "yay", "hooray",
"best", "beautiful", "delighted", "glad", "grateful", "thank", "thanked",
}
NEGATIVE_WORDS = {
"sad", "sadly", "cry", "cried", "crying", "scared", "scary", "afraid",
"angry", "mad", "hurt", "hurts", "pain", "bad", "terrible", "awful", "fear",
"fearful", "worried", "worry", "lonely", "alone", "dark", "monster", "die",
"died", "dead", "broken", "lost", "lose", "cruel", "mean", "fight",
"fought", "yell", "yelled", "scream", "screamed", "frown", "frowned", "sick",
}
WORD_RE = re.compile(r"[a-zA-Z']+")
def words(text):
return [w.lower() for w in WORD_RE.findall(text)]
def sentiment_reward(text):
toks = words(text)
if not toks:
return 0.0
score = sum(t in POSITIVE_WORDS for t in toks) - sum(t in NEGATIVE_WORDS for t in toks)
# normalize by length, with a floor so short stories aren't over-rewarded
return max(-1.0, min(1.0, score / max(8.0, len(toks) / 12)))
def required_words_reward(prompt_text, gen_text):
m = re.search(r"Words:\s*(.+)", prompt_text)
wanted = [w.strip().lower() for w in m.group(1).split(",") if w.strip()] if m else []
if not wanted:
return 0.0
gen = set(words(gen_text))
# prefix match so "jump" counts "jumped"/"jumping"
hits = sum(any(g.startswith(w) for g in gen) for w in wanted)
return hits / len(wanted)
def length_penalty(gen_text, target=70, span=60):
return -min(1.0, abs(len(words(gen_text)) - target) / span)
def compute_reward(prompt_text, gen_text, mode="sentiment"):
"""mode in {"sentiment", "words", "both"}."""
r = 0.1 * length_penalty(gen_text)
if mode in ("sentiment", "both"):
r += sentiment_reward(gen_text)
if mode in ("words", "both"):
r += 0.5 * required_words_reward(prompt_text, gen_text)
return rTraining
# Truncate ids at the first EOT, keeping it; the model's "stop" marker
def cut_at_eot(ids, eot):
return ids[: ids.index(eot) + 1] if eot in ids else ids
# Build a buffer of (prompt_ids, chosen_ids, rejected_ids): sample k completions
# per prompt from the frozen SFT model, score them, pair best vs worst.
# Tied scores carry no preference signal, so those prompts are skipped.
@torch.no_grad()
def generate_pairs(model, tok, buckets, lengths, weights, rng, n_pairs, k,
gen_batch, gen_len, temperature, top_k, reward, eot):
was_training = model.training
model.eval()
pairs, attempts = [], 0
while len(pairs) < n_pairs and attempts < n_pairs * 6:
plen = int(rng.choice(lengths, p=weights))
bucket = buckets[plen]
rows = [bucket[i] for i in rng.integers(0, len(bucket), size=gen_batch)]
attempts += gen_batch
prompts = torch.tensor([ids for _, ids in rows], device=device)
out = model.generate(prompts.repeat_interleave(k, dim=0), # k samples per prompt
max_new_tokens=gen_len, temperature=temperature, top_k=top_k)
comps = out[:, plen:].tolist()
for b, (ptext, pids) in enumerate(rows):
scored = sorted(
(compute_reward(ptext, tok.decode(c), mode=reward), c)
for c in (cut_at_eot(comps[b * k + j], eot) for j in range(k))
)
(lo, worst), (hi, best) = scored[0], scored[-1]
if hi - lo > 1e-6 and best and worst:
pairs.append((pids, best, worst))
model.train(was_training)
return pairs[:n_pairs]
# Pack chosen and rejected into padded (seq, mask) tensors. mask=1 on completion
# tokens only, so prompt and padding drop out of the log-prob sums.
def make_dpo_batch(pairs, idxs, pad_id, device):
rows = [pairs[i] for i in idxs]
max_len = max(len(p) + max(len(c), len(r)) for p, c, r in rows)
def pack(which):
x = np.full((len(rows), max_len), pad_id, dtype=np.int64)
m = np.zeros((len(rows), max_len), dtype=np.float32)
for i, (p, c, r) in enumerate(rows):
comp = c if which == "chosen" else r
x[i, : len(p) + len(comp)] = p + comp
m[i, len(p) : len(p) + len(comp)] = 1.0
return torch.from_numpy(x).to(device), torch.from_numpy(m).to(device)
return *pack("chosen"), *pack("rejected")
# log pi(completion | prompt) per row: logits at position t predict token t+1,
# so gather targets seq[:, 1:] and sum where the (shifted) completion mask is on.
def completion_logprob(model, seq, comp_mask):
logits, _, _ = model(seq)
logp = F.log_softmax(logits[:, :-1], dim=-1)
tok_logp = torch.gather(logp, 2, seq[:, 1:].unsqueeze(-1)).squeeze(-1)
return (tok_logp * comp_mask[:, 1:]).sum(dim=1)
# Mean reward of the policy on held-out prompts, plus one printed sample.
@torch.no_grad()
def evaluate(model, gen_len, top_k, reward, show=True):
model.eval()
rewards = []
for plen, items in eval_byl.items():
prompts = torch.tensor([ids for _, ids in items], device=device)
out = model.generate(prompts, max_new_tokens=gen_len, temperature=0.8, top_k=top_k)
for row, (ptext, _) in enumerate(items):
comp = cut_at_eot(out[row].tolist()[plen:], EOT_ID)
rewards.append(compute_reward(ptext, tok.decode(comp), mode=reward))
if show:
print(" sample:", sample_story(model, eval_prompts[0][0], n=gen_len, eos_id=EOT_ID)[:300], flush=True)
model.train()
return float(np.mean(rewards)) if rewards else 0.0
def load_prompts(path, tok, max_prompt_len, limit=None):
with open(path, encoding="utf-8") as f:
docs = [d.strip() for d in f.read().split(EOT) if d.strip()][:limit]
buckets = {}
for d in docs:
i = d.find(MARKER)
if i == -1:
continue
ptext = d[: i + len(MARKER)]
pids = tok.encode(ptext)
if 4 <= len(pids) <= max_prompt_len:
buckets.setdefault(len(pids), []).append((ptext, pids))
return {n: items for n, items in buckets.items() if len(items) >= 8}
# Policy starts from the SFT weights; dropout off everywhere so log-probs are
# deterministic. The frozen copy is the reference that anchors DPO updates.
for m in model.modules():
if isinstance(m, nn.Dropout):
m.p = 0.0
ref = copy.deepcopy(model).eval()
for p in ref.parameters():
p.requires_grad_(False)
batch_size = 16 # pairs per update
# pair-generation knobs
n_pairs = 2000 # preference pairs to build
k = 4 # samples per prompt (best vs worst)
gen_batch = 16 # prompts per generation call
gen_len = 80
temperature = 1.
eval_interval = 50
max_prompt_len = cfg.block_size - gen_len - 1
buckets = load_prompts(os.path.join(BASE_PATH, "data", "instruct_valid.txt"),
tok, max_prompt_len, limit=20_000)
# sample prompt lengths proportional to how many prompts each bucket holds
lengths = list(buckets)
weights = np.array([len(buckets[n]) for n in lengths], dtype=np.float64)
weights /= weights.sum()
# fixed eval pool, grouped by length
pool = [p for n in lengths for p in buckets[n]]
eval_prompts = [pool[i] for i in rng.integers(0, len(pool), size=64)]
eval_byl = {}
for ptext, pids in eval_prompts:
eval_byl.setdefault(len(pids), []).append((ptext, pids))lr = 1e-5
beta = 0.3
opt = torch.optim.AdamW(model.parameters(), lr=lr)
model.train()
t0 = time.time()
minutes = 10.0
deadline = t0 + minutes * 60
step = 0
regen_interval = 250
top_k = 50
reward = "both" # choices=["sentiment", "words", "both"]
while time.time() < deadline:
if step % regen_interval == 0:
pairs = generate_pairs(model, tok, buckets, lengths, weights, rng, n_pairs, k,
gen_batch, gen_len, temperature, top_k, reward, EOT_ID)
idxs = rng.integers(0, len(pairs), size=batch_size).tolist()
cs, cm, rs, rm = make_dpo_batch(pairs, idxs, PAD_ID, device)
pi_c = completion_logprob(model, cs, cm)
pi_r = completion_logprob(model, rs, rm)
with torch.no_grad(): # frozen reference
ref_c = completion_logprob(ref, cs, cm)
ref_r = completion_logprob(ref, rs, rm)
# DPO: prefer chosen over rejected by the reference-anchored margin
margin = beta * ((pi_c - ref_c) - (pi_r - ref_r))
loss = -F.logsigmoid(margin).mean()
opt.zero_grad(set_to_none=True)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
step += 1
if step % 10 == 0:
acc = (margin > 0).float().mean() # fraction of pairs ranked correctly
print(f"step {step:4d} | loss {loss.item():.4f} | pref_acc {acc.item():.2f} | "
f"margin {margin.mean().item():+.3f} | {(time.time() - t0) / 60:.1f} min", flush=True)
if step % eval_interval == 0:
r = evaluate(model, top_k=top_k, reward=reward, gen_len=gen_len, show=True)
print(f"[eval] step {step} mean_reward={r:+.3f}", flush=True)
torch.save({"model": model.state_dict(), "config": cfg.__dict__,
"reward_mode": reward, "step": step}, os.path.join(BASE_PATH, "ckpt_dpo.pt"))
print(f"\nDONE steps={step} ", flush=True)Compare Pretrain vs SFT vs DPO
models = [("pretrain", base), ("sft", sft), ("dpo", model)]
# ---- 1) instruction following on a hard prompt (unusual words, checkable) ----
hard_prompt = ("Features: Dialogue\nWords: spoon, bird, brave\n"
"Summary: A brave bird helps a friend find a lost spoon.\nStory:")
print("=" * 30, "hard instruction prompt", "=" * 30)
for name, m in models:
s = sample_story(m, hard_prompt, n=120, eos_id=EOT_ID)
stopped = len(words(s)) < 110 # eos before token cap -> learned to stop
print(f"\n--- {name} | words {required_words_reward(hard_prompt, s):.2f} | "
f"sentiment {sentiment_reward(s):+.2f} | stopped {stopped} ---\n{s}")
# ---- 2) sad instruction: SFT obeys, DPO drags toward happy ----
sad_prompt = "Summary: A dog loses his toy and cries.\nStory:"
print("\n" + "=" * 30, "sad instruction prompt", "=" * 30)
for name, m in models:
s = sample_story(m, sad_prompt, n=120, eos_id=EOT_ID)
print(f"\n--- {name} | sentiment {sentiment_reward(s):+.2f} ---\n{s}")
# ---- 3) mean reward over the fixed eval pool: three numbers, one trend ----
print("\n" + "=" * 30, "mean reward (64 prompts)", "=" * 30)
for name, m in models:
print(f"{name:9s} {evaluate(m, gen_len, top_k, reward, show=False):+.3f}")
# ---- 4) next-token probability probe (no sampling noise) ----
@torch.no_grad()
def next_word_probs(m, prefix, candidates):
was_training = m.training
m.eval()
ctx = torch.tensor([tok.encode(prefix)], device=device)
logits, _, _ = m(ctx)
probs = F.softmax(logits[0, -1], dim=-1)
m.train(was_training)
return {w: probs[tok.token_to_id[w]].item() for w in candidates}
print("\n" + "=" * 30, "P(next word) after 'The dog felt very'", "=" * 30)
for name, m in models:
p = next_word_probs(m, "The dog felt very", ["happy", "sad", "scared", "excited"])
print(f"{name:9s} " + " ".join(f"{w} {v:.3f}" for w, v in p.items()))Repository: github.com/nenuadrian/mvGPT


