GPT in PyTorch: training on the local GPU
Compare the NumPy GPT with PyTorch, then train a larger model locally while measuring memory, gradients, and controlled recipe ablations.
After this lesson you can
- Import NumPy weights into PyTorch and compare logits and gradients.
- Explain residual-scaled initialization and the transformer training recipe.
- Use gradient accumulation, clipping, warmup, and AdamW parameter groups.
- Measure GPU memory, throughput, and validation loss with explicit limitations.
- Compare training decisions through controlled ablations.
Before you start
- 18GPT architectureModular transformer backward passAutoregressive generation loopTransformer parameter and FLOP accountingPre-LN versus Post-LN
- 00Canonical training and evaluation loopTraining memory budgetPyTorch optimizer APIPyTorch tensorGraph capture with TorchDynamotorch.profiler tracesAutomatic mixed precision in PyTorch
- 06Weight decay versus L2 regularization
- 15Learning rate warmupVariance propagationInverted dropout
From the manual model to PyTorch
The NumPy GPT implementation provides a reference for checking an autograd version. First import weights and compare logits and gradients; then scale the model and measure local training.
Residual-scaled initialization reduces the standard deviation of projections writing to the residual stream by a depth-dependent factor. The training recipe combines AdamW, a schedule, clipping, and accumulation. Transformer dropout can apply to embeddings, attention, and residual outputs, and must be disabled for comparison or generation.
The same function, two conventions
In NumPy each projection uses x @ w + b, with w of shape (entrada, salida). PyTorch nn.Linear stores weight with shape (salida, entrada) and applies its transpose to the batch. The loader therefore copies the transpose of Q, K, V, the output projection, and the two MLP matrices. Embeddings, positions, scales, and biases are copied without transposition. The head uses F.linear and the same token table: output and input gradients accumulate in one parameter.
The test uses GELU with tanh approximation and the same in LayerNorm, because changing either prevents exact equality. It uses CPU float64, zero dropout, and evaluation mode. It compares both logits and gradients of all 36 exported tensors; gradient matrices are transposed back before comparison. Equality does not independently prove both implementations correct, but detects many shape, order, and accumulation discrepancies.
Attention calls scaled dot product attention with is_causal=True and no other mask. In this API a Boolean mask True indicates a participating position; it does not have the same meaning as the padding mask of MultiheadAttention. Argument dropout_p must explicitly be zero at evaluation: the function applies the supplied probability regardless of module mode. Backend and precision can alter last decimals, so strict comparison uses CPU and double precision.
To interpret the test, follow a tensor of shape (B, T, d). Each Q, K, or V projection preserves three axes and rearranges d into H heads of size d/H; attention returns an output per position and head. After rejoining heads, attn.o writes back to the width-d stream. The MLP expands to 4d, applies GELU, and projects back to d. Both residual additions require matching input and output dimensions. Incorrect weight transposition can still yield valid shapes for square matrices: compare values and gradients too.
The parity test uses a specific checkpoint exported by the learner in the prior lesson. Investigate discrepancies first using the same inputs, eval(), types, and parameters; do not resolve them by increasing tolerance without explanation. Then check causality and fixed-batch overfitting, since both implementations can share an error. Large training starts with new weights: the small test validates translation of functions, not transfer to the large model.
Why scale the residual?
Assume approximately that each block writes two zero-mean increments with comparable variance, uncorrelated with one another and with the previous state. Without scaling, variance of the sum of increments grows proportionally to . Multiplying each by keeps their total variance contribution constant. This is intuition under assumptions, not a guarantee: real branches may be correlated and normalization changes dynamics.
GPT-2 describes initialization scaled by the square root of the number of residual layers (Radford and colleagues, section 2.3). This block has two projections writing to the residual per layer, attn.o and mlp.proj; code uses base standard deviation 0.02 and for those two matrices. It does not indiscriminately scale Q, K, V, or embedding. The figure measures this intervention for one initialization and specific inputs without promising improvement on every run.
The first cell repeats the NumPy reference so the local comparison is self-contained. It does not train or need report files.
The following implementation preserves the same mathematical convention and uses PyTorch matrices stored as output by input.
import io, json, math
from pathlib import Path
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
class Attention(nn.Module):
def __init__(self, width, heads, dropout):
super().__init__()
assert width % heads == 0
self.heads = heads; self.dropout_p = dropout
self.q = nn.Linear(width, width); self.k = nn.Linear(width, width)
self.v = nn.Linear(width, width); self.o = nn.Linear(width, width)
self.residual_dropout = nn.Dropout(dropout)
def forward(self, x, diagnostics=False):
b, t, d = x.shape; dh = d // self.heads
def split(linear): return linear(x).view(b, t, self.heads, dh).transpose(1, 2)
q, k, v = split(self.q), split(self.k), split(self.v)
out = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=self.dropout_p if self.training else 0.)
entropy = None
if diagnostics:
scores = (q @ k.transpose(-2, -1)) / math.sqrt(dh)
mask = torch.ones((t,t), dtype=torch.bool, device=x.device).tril()
probs = scores.masked_fill(~mask, float('-inf')).softmax(-1)
entropy = -(probs * probs.clamp_min(1e-30).log()).sum(-1).mean().detach()
out = out.transpose(1,2).contiguous().view(b,t,d)
return self.residual_dropout(self.o(out)), entropy
class MLP(nn.Module):
def __init__(self, width, dropout):
super().__init__()
self.fc = nn.Linear(width, 4*width); self.proj = nn.Linear(4*width, width)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
return self.dropout(self.proj(F.gelu(self.fc(x), approximate='tanh')))
class Block(nn.Module):
def __init__(self, width, heads, dropout):
super().__init__()
self.n1 = nn.LayerNorm(width, eps=1e-5); self.n2 = nn.LayerNorm(width, eps=1e-5)
self.attn = Attention(width, heads, dropout); self.mlp = MLP(width, dropout)
def forward(self, x, diagnostics=False):
a, entropy = self.attn(self.n1(x), diagnostics)
x = x + a
return x + self.mlp(self.n2(x)), entropy
class TorchGPT(nn.Module):
def __init__(self, vocab, context, width, layers, heads, dropout=0.):
super().__init__()
if width % heads: raise ValueError('width debe ser divisible por heads')
self.config = dict(vocab=vocab, context=context, width=width, layers=layers, heads=heads, dropout=dropout)
self.token = nn.Embedding(vocab, width); self.position = nn.Embedding(context, width)
self.embedding_dropout = nn.Dropout(dropout)
self.blocks = nn.ModuleList([Block(width, heads, dropout) for _ in range(layers)])
self.final = nn.LayerNorm(width, eps=1e-5)
self.apply(self._init)
for block in self.blocks:
nn.init.normal_(block.attn.o.weight, mean=0, std=.02/math.sqrt(2*layers))
nn.init.normal_(block.mlp.proj.weight, mean=0, std=.02/math.sqrt(2*layers))
@staticmethod
def _init(module):
if isinstance(module, (nn.Linear, nn.Embedding)):
nn.init.normal_(module.weight, mean=0, std=.02)
if isinstance(module, nn.Linear) and module.bias is not None: nn.init.zeros_(module.bias)
def forward(self, ids, targets=None, diagnostics=False):
b, t = ids.shape
if t < 1 or t > self.config['context']: raise ValueError('contexto fuera de rango')
pos = torch.arange(t, device=ids.device)
x = self.embedding_dropout(self.token(ids) + self.position(pos)[None,:,:])
entropies = []
for block in self.blocks:
x, entropy = block(x, diagnostics)
if diagnostics: entropies.append(entropy)
logits = F.linear(self.final(x), self.token.weight)
loss = None if targets is None else F.cross_entropy(logits.reshape(-1, logits.shape[-1]), targets.reshape(-1))
return logits, loss, entropies
@torch.no_grad()
def generate(self, ids, count, generator):
self.eval()
for _ in range(count):
logits, _, _ = self(ids[:, -self.config['context']:])
probs = logits[:, -1].softmax(-1)
token = torch.multinomial(probs, 1, generator=generator)
ids = torch.cat((ids, token), dim=1)
return ids
def load_numpy_checkpoint(path, dtype=torch.float64):
with np.load(path, allow_pickle=False) as z:
cfg = json.loads(str(z['config'])); chars = z['characters'].tolist()
model = TorchGPT(**cfg, dropout=0.).to(dtype=dtype)
if len(chars) != cfg['vocab'] or len(set(chars)) != len(chars): raise ValueError('vocabulario inválido')
expected = {'config', 'characters', 'token', 'position', 'final.g', 'final.b'}
for i in range(cfg['layers']):
for n in ('n1', 'n2'):
expected.update({f'block.{i}.{n}.g', f'block.{i}.{n}.b'})
for n in ('q', 'k', 'v', 'o', 'fc', 'proj'):
expected.update({f'block.{i}.{n}.w', f'block.{i}.{n}.b'})
if set(z.files) != expected: raise ValueError('nombres de tensores incompatibles')
with torch.no_grad():
def copy(parameter, name, transpose=False):
a = z[name]
if transpose: a = a.T
if tuple(a.shape) != tuple(parameter.shape) or not np.isfinite(a).all(): raise ValueError('tensor inválido: '+name)
parameter.copy_(torch.as_tensor(a.copy(), dtype=dtype))
copy(model.token.weight, 'token'); copy(model.position.weight, 'position')
copy(model.final.weight, 'final.g'); copy(model.final.bias, 'final.b')
for i, block in enumerate(model.blocks):
pre = f'block.{i}.'
for name in ('n1','n2'):
layer = getattr(block, name)
copy(layer.weight, pre+name+'.g'); copy(layer.bias, pre+name+'.b')
for name in ('q','k','v','o'):
layer = getattr(block.attn, name)
copy(layer.weight, pre+name+'.w', True); copy(layer.bias, pre+name+'.b')
for name in ('fc','proj'):
layer = getattr(block.mlp, name)
copy(layer.weight, pre+name+'.w', True); copy(layer.bias, pre+name+'.b')
return model, chars
def configure_optimizers(model, weight_decay, lr=.0003):
decay, no_decay = [], []
for name, parameter in model.named_parameters():
if not parameter.requires_grad: continue
if parameter.ndim >= 2 and name not in ('token.weight','position.weight'): decay.append(parameter)
else: no_decay.append(parameter)
return torch.optim.AdamW([{'params': decay, 'weight_decay': weight_decay},
{'params': no_decay, 'weight_decay': 0.}], lr=lr, betas=(.9,.95))
def save_checkpoint(path, model, characters):
if len(characters) != model.config['vocab']: raise ValueError('vocabulario inconsistente')
torch.save({'config': model.config, 'characters': list(characters), 'state_dict': model.state_dict()}, path)
def load_checkpoint(path, map_location='cpu'):
state = torch.load(path, map_location=map_location, weights_only=True)
model = TorchGPT(**state['config']).to(device=map_location, dtype=state['state_dict']['token.weight'].dtype)
model.load_state_dict(state['state_dict'], strict=True)
if len(state['characters']) != model.config['vocab']: raise ValueError('vocabulario inconsistente')
return model, state['characters']npm run lab and open the connection link.Download gpt-numpy.npz from the previous lesson’s panel and place it in the lab directory, or edit numpy_path in this cell. Comparison uses CPU, float64, dropout=0, and the same batch; it does not measure speed. The small saved PyTorch file contains the same weights and vocabulary, not new training.
import os
torch.set_num_threads(1)
numpy_path = Path(os.environ.get('GPT_NUMPY_FILE', 'gpt-numpy.npz'))
manual, chars_numpy = load_npz(numpy_path.read_bytes())
converted, chars_torch = load_numpy_checkpoint(numpy_path)
converted.eval()
assert chars_numpy == chars_torch
ids = np.array([[0,1,2,3,4], [4,3,2,1,0]], dtype=np.int64)
targets = np.array([[1,2,3,4,5], [3,2,1,0,6]], dtype=np.int64)
numpy_logits, _ = manual.forward(ids)
numpy_loss, numpy_grads = manual.loss_and_grads(ids, targets)
torch_logits, torch_loss, _ = converted(torch.tensor(ids), torch.tensor(targets))
torch_loss.backward()
errors = {}
for name, parameter in converted.named_parameters():
if name == 'token.weight': source, transpose = 'token', False
elif name == 'position.weight': source, transpose = 'position', False
elif name == 'final.weight': source, transpose = 'final.g', False
elif name == 'final.bias': source, transpose = 'final.b', False
else:
parts = name.split('.'); index = parts[1]
if parts[2] in ('n1','n2'):
source = f'block.{index}.{parts[2]}.{ "g" if parts[3] == "weight" else "b" }'; transpose = False
else:
group, layer, kind = parts[2:]
source = f'block.{index}.{layer}.{ "w" if kind == "weight" else "b" }'; transpose = kind == 'weight'
expected = numpy_grads[source].T if transpose else numpy_grads[source]
errors[name] = float(np.max(np.abs(parameter.grad.detach().numpy() - expected)))
logit_error = float(np.max(np.abs(numpy_logits-torch_logits.detach().numpy())))
loss_error = abs(numpy_loss-torch_loss.item())
print('Máximo error logits:', logit_error, 'pérdida:', loss_error)
print('Máximo error de gradiente:', max(errors.values()), 'tensores:', len(errors))
assert logit_error < 1e-10 and loss_error < 1e-10 and max(errors.values()) < 1e-9
small_out = Path(os.environ.get('GPT_SMALL_OUT', 'gpt-pytorch-small.pt'))
save_checkpoint(small_out, converted, chars_torch)
reloaded, reloaded_chars = load_checkpoint(small_out)
reloaded.eval()
again, _, _ = reloaded(torch.tensor(ids))
assert reloaded_chars == chars_torch and torch.allclose(again, torch_logits, atol=1e-10, rtol=1e-10)
print('Checkpoint pequeño recargado, dtype:', next(reloaded.parameters()).dtype)npm run lab and open the connection link.A larger model on the GPU
Download the Tiny Shakespeare corpus as input.txt in the lab directory or adjust GPT_CORPUS_FILE. By default this cell uses five updates to check the flow. With GPT_FULL=1 it uses 1 000; GPT_STEPS sets another budget. gpt-pytorch.pt saves the large model’s configuration, vocabulary, and state_dict; optimizer and random generator are not saved, so this is not exact resumption.
The checked corpus version has 1 115 394 characters and 65 symbols. Text is split before building windows: 1 003 854 characters for training and 111 540 for validation. Since vocabulary comes from the entire corpus, validation symbols are known, but not their sequences. The six-block model with width 384 and context 128 has 10 721 664 unique parameters; its output table remains tied to input. The downloaded file may change, so the cell prints its SHA-256 instead of assuming all copies are identical.
One optimizer step accumulates four microbatches of eight windows: effective batch is 32 windows, or 4 096 tokens. Each mean loss is divided by four before backward, and one update is made after accumulation. With equally sized batches this equals the concatenated-batch mean gradient except for numerical differences and random dropout masks. Clipping applies to joint norm after accumulation, not separately per microbatch. AdamW uses ; embeddings, positions, norms, and biases are explicitly excluded from decay.
The schedule rises linearly for 50 updates and then decays by cosine to one tenth of the peak. Warmup avoids starting directly at the maximum step while AdamW moments are still being estimated; it does not remove the need to review the rate. Clipping limits the norm received by the optimizer when it exceeds one, but does not guarantee that AdamW’s effective update has that norm. Recorded norm is before clipping: a single spike does not prove failure, but repeated spikes with rising loss merit inspection.
Dropout applies to the embedding sum, attention probabilities, and both residual branch outputs. During training it introduces random masks; in evaluation and generation model.eval() disables them. Comparing training loss with dropout to validation loss without it can yield curves on different scales even without leakage. Observe both curves together with samples and gradient norm rather than selecting a recipe from one number.
The value is not universal. nanoGPT proposes zero for its pretraining configuration, while its character Shakespeare configuration uses 0.2. In a small corpus many windows overlap and the model may memorize; dropout can reduce that fitting at the cost of harder optimization. With large amounts of data and less reuse, that regularization may contribute less. Ablation measures what happens in this corpus and budget, not a rule for all sizes.
Budget before running
For FP32 parameters, weights and gradients each occupy approximately bytes. AdamW stores two moments of the same size: another bytes. These four copies alone total bytes, excluding activations, buffers, fragmentation, and other processes. BF16 autocast does not necessarily convert those four groups: here parameters and moments remain FP32. The figure separates components and adds an explicit activation model; its quadratic attention term can overestimate fused implementations while still omitting other costs.
Reducing microbatch lowers simultaneous activations, and accumulation can restore tokens per update. More accumulation does not increase each example’s context or equal running more sequences in parallel: it can change performance and gradient noise. Increasing makes activations costlier and, for materialized attention, the score term grows as . If a memory error occurs, try a smaller microbatch or context, measure peak again, and also inspect reserved memory and other processes. The estimator does not replace that measurement.
Training enables BF16 autocast if the GPU supports it; parameters and AdamW states remain FP32. Otherwise it uses FP32. Results depend on device and chosen kernels. Measurement synchronizes CUDA before and after the timed section, counts all processed tokens, and records peak PyTorch-allocated memory for that process. That peak does not necessarily include all reserved memory, fragmentation, or other processes, so it does not guarantee another run fits an 8 GiB device.
Every hundred steps and at the end, the same validation batch is evaluated and a sample generated with the same seed. The model then returns to training mode. Recorded speed includes those diagnostic pauses and batch preparation, so it describes the complete loop, not only training kernels. Saving logs relates loss changes to rate, norm, and samples. One validation batch is fast for detecting issues, but quality evaluation should aggregate many independent batches.
import hashlib, time
corpus_path = Path(os.environ.get('GPT_CORPUS_FILE', 'input.txt'))
raw = corpus_path.read_bytes()
text = raw.decode('utf-8')
print('Corpus SHA-256:', hashlib.sha256(raw).hexdigest())
characters = sorted(set(text)); mapping = {c:i for i,c in enumerate(characters)}
data = np.array([mapping[c] for c in text], dtype=np.int64)
cut = int(.9*len(data)); train_data, val_data = data[:cut], data[cut:]
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if device.type != 'cuda': raise RuntimeError('Este entrenamiento requiere una GPU CUDA; la comparación pequeña anterior funciona en CPU.')
torch.manual_seed(1712); np_rng = np.random.default_rng(1712)
cfg = dict(vocab=len(characters), context=128, width=384, layers=6, heads=6, dropout=.1)
model = TorchGPT(**cfg).to(device)
opt = configure_optimizers(model, weight_decay=.1, lr=.0003)
batch_size, accumulation = 8, 4
full = os.environ.get('GPT_FULL') == '1'
steps = int(os.environ.get('GPT_STEPS', '1000' if full else '5'))
assert steps > 0
def make_batch(data, generator):
starts = generator.integers(0, len(data)-cfg['context'], size=batch_size)
x = np.stack([data[i:i+cfg['context']] for i in starts])
y = np.stack([data[i+1:i+cfg['context']+1] for i in starts])
return torch.from_numpy(x).to(device), torch.from_numpy(y).to(device)
def rate(step, total, warmup=50, peak=.0003, floor=.1):
if step < warmup: return peak*(step+1)/warmup
phase = min(1., (step-warmup)/max(1,total-warmup))
return peak*(floor+(1-floor)*.5*(1+math.cos(math.pi*phase)))
use_bf16 = torch.cuda.is_bf16_supported()
torch.cuda.reset_peak_memory_stats(device)
torch.cuda.synchronize(device); begin = time.perf_counter()
val_rng = np.random.default_rng(1812)
vx, vy = make_batch(val_data, val_rng)
model.train(); records, diagnostics = [], []
for step_index in range(steps):
for group in opt.param_groups: group['lr'] = rate(step_index, max(1000, steps))
opt.zero_grad(set_to_none=True)
accumulated = 0.
for _ in range(accumulation):
x_batch, y_batch = make_batch(train_data, np_rng)
with torch.autocast(device_type='cuda', dtype=torch.bfloat16, enabled=use_bf16):
_, loss, _ = model(x_batch, y_batch)
scaled_loss = loss / accumulation
scaled_loss.backward(); accumulated += float(scaled_loss.detach())
grad_norm = nn.utils.clip_grad_norm_(model.parameters(), 1.)
opt.step()
records.append({'step': step_index+1, 'train': accumulated, 'grad': float(grad_norm), 'lr': opt.param_groups[0]['lr']})
if (step_index+1) % 100 == 0 or step_index+1 == steps:
model.eval()
with torch.no_grad():
_, val_loss, entropies = model(vx, vy, diagnostics=True)
prompt = torch.tensor([[mapping['F']]], dtype=torch.long, device=device)
generated = model.generate(prompt, 40, torch.Generator(device=device).manual_seed(1712))[0].tolist()
sample = ''.join(characters[k] for k in generated)
diagnostics.append({'step': step_index+1, 'val': float(val_loss),
'entropy': [float(e) for e in entropies], 'sample': sample})
print('Diagnóstico paso', step_index+1, 'validación:', float(val_loss), 'muestra:', repr(sample), flush=True)
model.train()
torch.cuda.synchronize(device); elapsed = time.perf_counter()-begin
peak = torch.cuda.max_memory_allocated(device)
model.eval()
print('Parámetros únicos:', sum(p.numel() for p in model.parameters()))
print('Pasos:', steps, 'pérdida final:', records[-1]['train'], 'validación:', float(val_loss))
print('Norma de gradiente antes del recorte:', records[-1]['grad'])
print('Entropía por capa:', [float(e) for e in entropies])
print('Tokens/s sincronizados:', steps*batch_size*accumulation*cfg['context']/elapsed)
print('Pico de memoria asignada en bytes:', peak, 'BF16:', use_bf16)
print('Muestra:', repr(sample))
torch_out = Path(os.environ.get('GPT_TORCH_OUT', 'gpt-pytorch.pt'))
save_checkpoint(torch_out, model, characters)
print('Checkpoint guardado:', torch_out)npm run lab and open the connection link.In a five-step local RTX 3060 check, the model produced peak allocated memory of 332 101 632 bytes (approximately 316.7 MiB) and validation loss 3.4541 on the diagnostic batch. These are figures for that brief run, not a trained-model measurement or memory promise for other configurations. Its generated sample was mostly noise. Shared GPU speed varies; rerun the cell to measure your environment.
With GPT_FULL=1, 1 000 steps also ran on that GPU: loss on the same fixed batch fell from 2.3759 at step 100 to 1.8513 at 1 000. Final-step training loss was 1.7390; peak allocated was 332 105 728 bytes and the complete loop processed approximately 10 682 tokens per second, including diagnostics. Samples showed words and dialogue structure but still contained fragments and errors: this run does not demonstrate coherent text. Comparison uses one seed and one validation batch; speed depends on load and environment.
The next cell uses matplotlib to display what your own run recorded. The training curve includes every step, whereas validation and entropy are measured only at diagnostic points; short mode shows one validation point. The norm line is before clipping and can exceed one without contradicting the limit applied afterward.
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 2, figsize=(10, 3.5), constrained_layout=True)
axes[0].plot([r['step'] for r in records], [r['train'] for r in records], label='entrenamiento')
axes[0].plot([r['step'] for r in diagnostics], [r['val'] for r in diagnostics], 'o-', label='validación fija')
axes[0].set(xlabel='paso', ylabel='pérdida'); axes[0].legend()
axes[1].plot([r['step'] for r in records], [r['grad'] for r in records], label='norma antes del recorte')
axes[1].set(xlabel='paso', ylabel='norma'); axes[1].legend()
plt.show()
print('Entropía por capa en cada diagnóstico:', [(r['step'], r['entropy']) for r in diagnostics])npm run lab and open the connection link.Continue with a new optimizer
The checkpoint contains weights, configuration, and vocabulary, but not moments or random state. The next optional cell loads gpt-pytorch.pt or path GPT_TORCH_FILE, creates AdamW anew, and adds 2 000 steps; GPT_CONTINUE_STEPS allows a shorter test. To reproduce the described trial, first generate a 3 000-step checkpoint with GPT_STEPS=3000, use the same corpus, and retain its hash. This continuation’s schedule starts again and batch seeds are new: it continues from weights, not an exact resumption.
The same validation batch is always evaluated and six fixed samples generated: three prompts, each at temperatures 0.7 and 1.0 with specific seeds. In one RTX 3060 run, loss on that batch fell from 1.6278 to 1.6029 after 2 000 additional steps. The sample with KING:, temperature 0.7, and seed 1812 continued with To my master and my father kingly justice and To be answer'd and that I may be my lord.. Samples contain recognizable phrases alongside grammatical errors and fragments; they do not establish sustained coherence. Code saves a checkpoint and diagnostics at configurable paths. It does not run automatically in the short check because of its duration.
import os, json, math, time, hashlib
torch.set_num_threads(1)
raw=Path(os.environ.get('GPT_CORPUS_FILE','input.txt')).read_bytes();text=raw.decode('utf-8')
model,chars=load_checkpoint(os.environ.get('GPT_TORCH_FILE','gpt-pytorch.pt'),map_location='cuda');mapping={c:i for i,c in enumerate(chars)}
assert sorted(set(text))==chars and hashlib.sha256(raw).hexdigest()=='86c4e6aa9db7c042ec79f339dcb96d42b0075e16b8fc2e86bf0ca57e2dc565ed'
data=np.array([mapping[c] for c in text],dtype=np.int64);cut=int(.9*len(data));train,val=data[:cut],data[cut:]
rng=np.random.default_rng(2718); val_rng=np.random.default_rng(1812);B=8;T=model.config['context'];acc=4;device=torch.device('cuda')
def batch(part,generator):
starts=generator.integers(0,len(part)-T,size=B);x=np.stack([part[i:i+T] for i in starts]);y=np.stack([part[i+1:i+T+1] for i in starts]);return torch.from_numpy(x).to(device),torch.from_numpy(y).to(device)
vx,vy=batch(val,val_rng)
@torch.no_grad()
def samples():
model.eval(); results=[]
for prompt,seed,temp in [('F',1712,.7),('F',1713,1.),('KING:',1812,.7),('KING:',1813,1.),('The ',1912,.7),('The ',1913,1.)]:
ids=torch.tensor([[mapping[c] for c in prompt]],device=device);gen=torch.Generator(device='cuda').manual_seed(seed)
for _ in range(100):
logits,_,_=model(ids[:,-T:]);probs=(logits[:,-1]/temp).softmax(-1);ids=torch.cat((ids,torch.multinomial(probs,1,generator=gen)),1)
results.append({'prompt':prompt,'seed':seed,'temperature':temp,'sample':''.join(chars[i] for i in ids[0].tolist())})
return results
@torch.no_grad()
def evaluate():
model.eval();_,loss,_=model(vx,vy);return float(loss)
optimizer=configure_optimizers(model,.1,lr=.0001);steps=int(os.environ.get('GPT_CONTINUE_STEPS','2000'));assert steps>0
bf16=torch.cuda.is_bf16_supported();torch.manual_seed(2718)
records=[]; start=time.perf_counter(); print('antes:',evaluate(),samples(),flush=True)
for step in range(steps):
model.train();optimizer.zero_grad(set_to_none=True);total=0.
lr=.0001*(.1+.9*.5*(1+math.cos(math.pi*min(step,2000)/2000)))
for group in optimizer.param_groups:group['lr']=lr
for _ in range(acc):
x,y=batch(train,rng)
with torch.autocast('cuda',dtype=torch.bfloat16,enabled=bf16):_,loss,_=model(x,y);scaled=loss/acc
scaled.backward();total+=float(scaled.detach())
norm=nn.utils.clip_grad_norm_(model.parameters(),1.);optimizer.step()
if (step+1)%500==0 or step+1==steps:
record={'step_extra':step+1,'train':total,'validation':evaluate(),'grad':float(norm),'samples':samples()};records.append(record);print(json.dumps(record,ensure_ascii=False),flush=True)
save_checkpoint(os.environ.get('GPT_CONTINUE_OUT','gpt-pytorch-continued.pt'),model,chars)
Path(os.environ.get('GPT_CONTINUE_REPORT','gpt-continuation.json')).write_text(json.dumps({'optimizer':'nuevo AdamW','extra_steps':steps,'records':records},ensure_ascii=False),encoding='utf-8')
print('Checkpoint guardado. Segundos:',time.perf_counter()-start,flush=True)npm run lab and open the connection link.Controlled ablations
The next cell compares a reference recipe with six changes, using three seeds and the same batches for conditions of each seed. Short mode performs ten updates per run: it checks the experiment, not which is better. With GPT_ABLATION_FULL=1 it performs 300. These models are small enough for a practical comparison; all are evaluated on the same held-out batch with dropout disabled.
The seven conditions are base, no warmup, , no clipping, decay on all parameters, no residual scaling, and dropout. Each changes one decision relative to base. For the unscaled trial, the same two residual projections are multiplied by , restoring standard deviation 0.02; other matrices and batches start from the same seed. Comparison uses a two-layer width-64 model, not the 10.7-million-parameter one. Averaging three seeds reduces dependence on one initialization but does not yield a universal conclusion, especially with a single validation sample.
conditions = ['base', 'sin warmup', 'beta2 0.999', 'sin recorte', 'decay total', 'sin escala', 'dropout']
abl_steps = 300 if os.environ.get('GPT_ABLATION_FULL') == '1' else 10
def small_batch(part, rng, size=4, context=32):
starts = rng.integers(0, len(part)-context, size=size)
a = np.stack([part[i:i+context] for i in starts]); b = np.stack([part[i+1:i+context+1] for i in starts])
return torch.from_numpy(a).to(device), torch.from_numpy(b).to(device)
fixed_val = small_batch(val_data, np.random.default_rng(1912))
ablation_records = []
for seed in (1,2,3):
for condition in conditions:
torch.manual_seed(seed)
candidate = TorchGPT(len(characters), 32, 64, 2, 4, dropout=.1 if condition == 'dropout' else 0.).to(device)
if condition == 'sin escala':
with torch.no_grad():
for block in candidate.blocks:
block.attn.o.weight.mul_(math.sqrt(2*candidate.config['layers']))
block.mlp.proj.weight.mul_(math.sqrt(2*candidate.config['layers']))
if condition == 'decay total':
optimizer = torch.optim.AdamW(candidate.parameters(), lr=.0003, betas=(.9,.95), weight_decay=.1)
else:
optimizer = configure_optimizers(candidate, .1)
if condition == 'beta2 0.999':
for group in optimizer.param_groups: group['betas'] = (.9,.999)
batch_rng = np.random.default_rng(seed+5000)
trace = []
for step_index in range(abl_steps):
lr = rate(step_index, 300, warmup=0 if condition == 'sin warmup' else 10)
for group in optimizer.param_groups: group['lr'] = lr
candidate.train(); xb, yb = small_batch(train_data, batch_rng)
_, loss, _ = candidate(xb, yb)
optimizer.zero_grad(set_to_none=True); loss.backward()
norm = nn.utils.clip_grad_norm_(candidate.parameters(), 1.) if condition != 'sin recorte' else torch.sqrt(sum((p.grad.detach()**2).sum() for p in candidate.parameters() if p.grad is not None))
optimizer.step()
if (step_index+1) % 5 == 0 or step_index == 0:
candidate.eval()
with torch.no_grad(): _, val_loss, _ = candidate(*fixed_val)
trace.append({'step': step_index+1, 'train': float(loss.detach()), 'val': float(val_loss), 'grad': float(norm)})
ablation_records.append({'condition': condition, 'seed': seed, 'trace': trace})
for condition in conditions:
vals = [r['trace'][-1]['val'] for r in ablation_records if r['condition'] == condition]
print(condition, 'pasos:', abl_steps, 'validación media:', float(np.mean(vals)), 'por semilla:', vals)
ablation_path = Path(os.environ.get('GPT_ABLATION_OUT', 'gpt-ablation.json'))
ablation_path.write_text(json.dumps({'steps': abl_steps, 'seeds': [1,2,3],
'corpus_sha256': hashlib.sha256(raw).hexdigest(), 'records': ablation_records}, ensure_ascii=False), encoding='utf-8')
print('Registros guardados:', ablation_path)npm run lab and open the connection link.def residual_probe(depth):
if not 1 <= depth <= 12: raise ValueError('profundidad fuera de rango')
outputs = []
with torch.random.fork_rng(devices=[device.index or 0]):
for scaled in (True, False):
torch.manual_seed(1912)
candidate = TorchGPT(len(characters), 32, 64, depth, 4, dropout=0.).to(device).eval()
if not scaled:
with torch.no_grad():
for block in candidate.blocks:
block.attn.o.weight.mul_(math.sqrt(2*depth))
block.mlp.proj.weight.mul_(math.sqrt(2*depth))
inputs = fixed_val[0]
with torch.no_grad():
state = candidate.token(inputs) + candidate.position(torch.arange(inputs.shape[1], device=device))[None,:,:]
variances = [float(state.var(unbiased=False))]
for block in candidate.blocks:
state, _ = block(state)
variances.append(float(state.var(unbiased=False)))
outputs.append(variances)
comparison = [r for r in ablation_records if r['seed'] == 1 and r['condition'] in ('base','sin escala')]
return {'scaled': outputs[0], 'unscaled': outputs[1], 'losses': comparison}
print('Instrumentos listos; registros de ablación:', len(ablation_records))npm run lab and open the connection link.Attention entropy is calculated as for each query and then averaged. Under a causal mask the first position can attend only to itself and has zero entropy; the maximum at position is . A mean without normalization by available position count also depends on length and is insufficient to diagnose collapse. The large cell calculates probabilities explicitly for diagnostics, although production attention may use a fused kernel that does not materialize them.
If a loss spike appears, retain the log and inspect the batch first: shapes, index range, and input-target shift. Then compare pre-clipping norm with neighboring steps and review the scheduled rate; a scale change or excessive rate are hypotheses testable by repetition. Observe per-layer entropy and logit magnitude to look for saturation or non-finite values. Do not adjust all variables at once: save the reference condition and change one decision in each comparison.
Samples are complementary qualitative diagnostics. With the same input and seed one can observe evolution, but a lucky sample does not estimate loss or generalization. Validation worsening while training improves suggests checking overfitting, the split, and statistical noise; one batch is insufficient to decide. Because the checkpoint contains only model and vocabulary, training again without restoring optimizer, schedule, and random states produces a different trajectory. Exact resumption would require saving and restoring those states and the step number too.
The initialization figure keeps seed and data fixed when comparing two models; it multiplies residual projections of the scaled model by to obtain the unscaled variant. This isolates that change in the probe. Loss curves below come from two-layer ablations, not from the upper figure’s depth sweep.
The figures’ recorded data came from this lesson’s code, Tiny Shakespeare identified by SHA-256 86c4e6aa9db7c042ec79f339dcb96d42b0075e16b8fc2e86bf0ca57e2dc565ed, and 300 updates per condition. The three seeds are 1, 2, and 3; the variance probe uses 1912. In that run, mean final validation was 3.055 for base and 3.056 without warmup. That small difference on one fixed batch does not establish that warmup has no value in larger models or at another rate. The selector compares other conditions and individual values, and the button replaces the chosen curve with data from your local session.
The next test uses torch.compile with the eager backend to check capture and correspondence, not to claim speedup. If GPT_COMPILE=1 is enabled, it also attempts the default backend; it may be unavailable for your system and packages. Compilation and first use can take time: do not mix them into steady-state measurement.
The high setting of FP32 multiplication precision may enable faster internal calculations, such as TF32 on compatible hardware, without changing external tensor type. It differs from BF16 autocast. The code saves and restores the prior setting; also compare logits before interpreting timings. torch.compile may produce graph breaks or select a backend that fails on a particular system: successful capture does not necessarily imply better performance.
candidate.eval()
old_precision = torch.get_float32_matmul_precision()
try:
torch.set_float32_matmul_precision('high')
with torch.no_grad(): expected, _, _ = candidate(fixed_val[0])
try:
captured = torch.compile(candidate, backend='eager')
with torch.no_grad(): actual, _, _ = captured(fixed_val[0])
torch.cuda.synchronize(device)
print('Captura eager: diferencia máxima:', float((actual-expected).abs().max()))
except Exception as exc:
print('Captura eager no disponible:', type(exc).__name__, str(exc)[:200])
else:
assert torch.allclose(actual, expected, atol=1e-5, rtol=1e-5)
def bench(fn, repeat=10):
with torch.no_grad():
fn(fixed_val[0]); torch.cuda.synchronize(device)
start = time.perf_counter()
for _ in range(repeat): fn(fixed_val[0])
torch.cuda.synchronize(device)
return (time.perf_counter()-start)/repeat
print('Segundos por forward, eager y captura eager:', bench(candidate), bench(captured))
if os.environ.get('GPT_COMPILE') == '1':
try:
compiled = torch.compile(candidate)
with torch.no_grad(): actual, _, _ = compiled(fixed_val[0])
torch.cuda.synchronize(device)
print('Backend por defecto: diferencia máxima:', float((actual-expected).abs().max()))
except Exception as exc:
print('Backend por defecto no disponible:', type(exc).__name__, str(exc)[:200])
else:
assert torch.allclose(actual, expected, atol=1e-4, rtol=1e-4)
finally:
torch.set_float32_matmul_precision(old_precision)npm run lab and open the connection link.Exercises
import torch
def configure_optimizers(model, weight_decay):
pass