File size: 10,503 Bytes
2717ac7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 | """Train 3 transformers to compare convergence:
1. Chebyshev residual (shallow, 12 layers)
2. Standard residual (shallow, 12 layers)
3. Standard residual (deep, 24 layers, same params via smaller hidden)
All trained on same data, same compute budget.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, Dataset
import math, time, json, os
import numpy as np
DEVICE = "mps" # Apple Silicon
SEED = 42
torch.manual_seed(SEED)
np.random.seed(SEED)
# === Config ===
VOCAB = 256 # byte-level for simplicity
SEQ_LEN = 128
BATCH = 32
HIDDEN = 256
HEADS = 8
HEAD_DIM = HIDDEN // HEADS
N_STEPS = 5000
LR = 3e-4
EVAL_EVERY = 250
# === Dataset: Shakespeare byte-level ===
class ByteDataset(Dataset):
def __init__(self, data, seq_len):
self.data = data
self.seq_len = seq_len
def __len__(self):
return len(self.data) - self.seq_len - 1
def __getitem__(self, idx):
x = self.data[idx:idx+self.seq_len]
y = self.data[idx+1:idx+self.seq_len+1]
return torch.tensor(x, dtype=torch.long), torch.tensor(y, dtype=torch.long)
# Download Shakespeare
DATA_PATH = "/tmp/shakespeare.txt"
if not os.path.exists(DATA_PATH):
print("Downloading Shakespeare...", flush=True)
import urllib.request
url = "https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt"
urllib.request.urlretrieve(url, DATA_PATH)
with open(DATA_PATH, "rb") as f:
raw = list(f.read())
split = int(len(raw) * 0.9)
train_data = raw[:split]
val_data = raw[split:]
train_ds = ByteDataset(train_data, SEQ_LEN)
val_ds = ByteDataset(val_data, SEQ_LEN)
train_dl = DataLoader(train_ds, batch_size=BATCH, shuffle=True, drop_last=True)
val_dl = DataLoader(val_ds, batch_size=BATCH, shuffle=False, drop_last=True)
print("Data: %d train, %d val tokens" % (len(train_data), len(val_data)), flush=True)
# === Attention block ===
class CausalSelfAttention(nn.Module):
def __init__(self, hidden, heads):
super().__init__()
self.heads = heads
self.head_dim = hidden // heads
self.qkv = nn.Linear(hidden, 3 * hidden)
self.out = nn.Linear(hidden, hidden)
def forward(self, x):
B, T, C = x.shape
qkv = self.qkv(x).reshape(B, T, 3, self.heads, self.head_dim).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2]
att = (q @ k.transpose(-2, -1)) * (self.head_dim ** -0.5)
mask = torch.triu(torch.ones(T, T, device=x.device, dtype=torch.bool), diagonal=1)
att = att.masked_fill(mask, float("-inf"))
att = F.softmax(att, dim=-1)
out = (att @ v).transpose(1, 2).reshape(B, T, C)
return self.out(out)
# === MLP ===
class MLP(nn.Module):
def __init__(self, hidden):
super().__init__()
self.fc1 = nn.Linear(hidden, 4 * hidden)
self.fc2 = nn.Linear(4 * hidden, hidden)
def forward(self, x):
return self.fc2(F.gelu(self.fc1(x)))
# === Standard Transformer Block ===
class StandardBlock(nn.Module):
def __init__(self, hidden, heads):
super().__init__()
self.ln1 = nn.LayerNorm(hidden)
self.attn = CausalSelfAttention(hidden, heads)
self.ln2 = nn.LayerNorm(hidden)
self.mlp = MLP(hidden)
def forward(self, x):
x = x + self.attn(self.ln1(x))
x = x + self.mlp(self.ln2(x))
return x
# === Chebyshev Transformer Block ===
class ChebyshevBlock(nn.Module):
"""Two-step Chebyshev recurrence: h_{n+1} = 2*f(h_n) - h_{n-1}"""
def __init__(self, hidden, heads):
super().__init__()
self.ln1 = nn.LayerNorm(hidden)
self.attn = CausalSelfAttention(hidden, heads)
self.ln2 = nn.LayerNorm(hidden)
self.mlp = MLP(hidden)
# Learnable mixing coefficient (starts at standard residual)
self.alpha = nn.Parameter(torch.tensor(0.5))
def forward(self, x, x_prev):
# Compute layer output
f_x = x + self.attn(self.ln1(x))
f_x = f_x + self.mlp(self.ln2(f_x))
# Chebyshev recurrence: blend between standard and two-step
# alpha=0.5 -> standard residual, alpha=1.0 -> full Chebyshev
alpha = torch.sigmoid(self.alpha)
h_new = (1 + alpha) * f_x - alpha * x_prev
return h_new
# === Full Models ===
class StandardTransformer(nn.Module):
def __init__(self, vocab, hidden, heads, n_layers):
super().__init__()
self.embed = nn.Embedding(vocab, hidden)
self.pos = nn.Embedding(SEQ_LEN, hidden)
self.blocks = nn.ModuleList([StandardBlock(hidden, heads) for _ in range(n_layers)])
self.ln_f = nn.LayerNorm(hidden)
self.head = nn.Linear(hidden, vocab, bias=False)
self.n_layers = n_layers
def forward(self, x):
B, T = x.shape
h = self.embed(x) + self.pos(torch.arange(T, device=x.device))
for block in self.blocks:
h = block(h)
return self.head(self.ln_f(h))
class ChebyshevTransformer(nn.Module):
def __init__(self, vocab, hidden, heads, n_layers):
super().__init__()
self.embed = nn.Embedding(vocab, hidden)
self.pos = nn.Embedding(SEQ_LEN, hidden)
self.blocks = nn.ModuleList([ChebyshevBlock(hidden, heads) for _ in range(n_layers)])
self.ln_f = nn.LayerNorm(hidden)
self.head = nn.Linear(hidden, vocab, bias=False)
self.n_layers = n_layers
def forward(self, x):
B, T = x.shape
h = self.embed(x) + self.pos(torch.arange(T, device=x.device))
h_prev = h.clone() # initial h_{-1} = h_0
for block in self.blocks:
h_new = block(h, h_prev)
h_prev = h
h = h_new
return self.head(self.ln_f(h))
# === Training ===
def count_params(model):
return sum(p.numel() for p in model.parameters())
def evaluate(model, dl):
model.eval()
total_loss = 0
n = 0
with torch.no_grad():
for xb, yb in dl:
xb, yb = xb.to(DEVICE), yb.to(DEVICE)
logits = model(xb)
loss = F.cross_entropy(logits.view(-1, VOCAB), yb.view(-1))
total_loss += loss.item()
n += 1
if n >= 20:
break
model.train()
return total_loss / n
def train_model(name, model):
model = model.to(DEVICE)
params = count_params(model)
print("\n%s: %d params (%.2fM), %d layers" % (name, params, params/1e6, model.n_layers), flush=True)
opt = torch.optim.AdamW(model.parameters(), lr=LR)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(opt, N_STEPS)
losses = []
val_losses = []
step = 0
t0 = time.perf_counter()
while step < N_STEPS:
for xb, yb in train_dl:
if step >= N_STEPS:
break
xb, yb = xb.to(DEVICE), yb.to(DEVICE)
logits = model(xb)
loss = F.cross_entropy(logits.view(-1, VOCAB), yb.view(-1))
opt.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
scheduler.step()
losses.append(loss.item())
step += 1
if step % EVAL_EVERY == 0:
vl = evaluate(model, val_dl)
val_losses.append((step, vl))
elapsed = time.perf_counter() - t0
print(" step %d/%d: train=%.4f val=%.4f (%.0fs)" % (
step, N_STEPS, np.mean(losses[-100:]), vl, elapsed), flush=True)
# Final eval
vl = evaluate(model, val_dl)
val_losses.append((step, vl))
elapsed = time.perf_counter() - t0
print(" FINAL: val=%.4f, %.0fs, %.1f steps/s" % (vl, elapsed, N_STEPS/elapsed), flush=True)
return {
"name": name,
"params": params,
"layers": model.n_layers,
"train_losses": losses,
"val_losses": val_losses,
"time": elapsed,
"final_val": vl,
}
# === Deep standard: SAME hidden, MORE params (2x layers = ~2x params) ===
HIDDEN_DEEP = HIDDEN # same width
HEADS_DEEP = HEADS # same heads
print("=" * 60, flush=True)
print("CHEBYSHEV vs STANDARD TRANSFORMER COMPARISON", flush=True)
print("=" * 60, flush=True)
print("Shallow: %d layers, hidden=%d, heads=%d" % (12, HIDDEN, HEADS), flush=True)
print("Deep: %d layers, hidden=%d, heads=%d" % (24, HIDDEN_DEEP, HEADS_DEEP), flush=True)
print("Steps: %d, Batch: %d, Seq: %d" % (N_STEPS, BATCH, SEQ_LEN), flush=True)
# Run all 3
results = []
# 1. Chebyshev shallow
model1 = ChebyshevTransformer(VOCAB, HIDDEN, HEADS, 12)
r1 = train_model("Chebyshev-12L", model1)
results.append(r1)
del model1
torch.mps.empty_cache() if hasattr(torch.mps, 'empty_cache') else None
# 2. Standard shallow
model2 = StandardTransformer(VOCAB, HIDDEN, HEADS, 12)
r2 = train_model("Standard-12L", model2)
results.append(r2)
del model2
torch.mps.empty_cache() if hasattr(torch.mps, 'empty_cache') else None
# 3. Standard deep (matched params)
model3 = StandardTransformer(VOCAB, HIDDEN_DEEP, HEADS_DEEP, 24)
r3 = train_model("Standard-24L", model3)
results.append(r3)
del model3
# === Summary ===
print("\n" + "=" * 60, flush=True)
print("RESULTS", flush=True)
print("=" * 60, flush=True)
print("%-20s %8s %6s %10s %10s" % ("Model", "Params", "Layers", "Final Val", "Time"), flush=True)
print("-" * 58, flush=True)
for r in results:
print("%-20s %8d %6d %10.4f %8.0fs" % (r["name"], r["params"], r["layers"], r["final_val"], r["time"]), flush=True)
# Convergence comparison: val loss at step 1000, 2500, 5000
print("\nConvergence:", flush=True)
print("%-20s %10s %10s %10s" % ("Model", "Step 1000", "Step 2500", "Step 5000"), flush=True)
print("-" * 52, flush=True)
for r in results:
vals = dict(r["val_losses"])
v1k = vals.get(1000, vals.get(750, "N/A"))
v25k = vals.get(2500, "N/A")
v5k = vals.get(5000, vals.get(4750, "N/A"))
print("%-20s %10s %10s %10s" % (
r["name"],
"%.4f" % v1k if isinstance(v1k, float) else v1k,
"%.4f" % v25k if isinstance(v25k, float) else v25k,
"%.4f" % v5k if isinstance(v5k, float) else v5k,
), flush=True)
# Save results
save = {r["name"]: {"val_losses": r["val_losses"], "params": r["params"],
"final_val": r["final_val"], "time": r["time"]} for r in results}
with open("/tmp/donkey_cheb_train_results.json", "w") as f:
json.dump(save, f, indent=2)
print("\nSaved to /tmp/donkey_cheb_train_results.json", flush=True)
|