Training loop, sanity checks and pilot run
Write a training loop with AdamW, gradient clipping, learning-rate warmup and decay, and periodic evaluation. Apply sanity checks for initial loss, single-batch overfitting, and per-layer norms. Before long training, validate the entire system with a TinyStories pilot that produces coherent stories in under an hour.
After this lesson you can
- Implement the loop with AdamW, selective weight decay, gradient clipping, and a scheduler.
- Verify that initial loss is approximately the logarithm of vocabulary size and overfit one batch to nearly zero.
- Log gradient norms and update-to-weight ratios by layer.
- Train a 10-to-30-million-parameter model on TinyStories and generate coherent stories.
Before you start
Before spending the full budget
In p06-l06 we will train an 86-million-parameter GPT for hours. If the loop has a silent bug, such as unshifted labels, a parameter group receiving no gradient, a learning rate ten times larger than intended, or validation sharing stories with training, we will discover it late and at considerable cost. This lesson builds the training loop and puts it through increasingly expensive tests: first milliseconds, then a minute, and finally half an hour of GPU time. Each test rules out a particular family of failures, which is why they are performed in order.
The figure contains actual lab records from this lesson. The first two runs are a learning-rate probe using the same 13-million-parameter model, data, and seed, with a peak rate of or , stopped at step 1000 of a 3000-step plan. The third is the full pilot with batches eight times larger, verified using the first 3000 of its 12000 steps. Start by comparing the two rates: the larger wins initially and loses at step 1000. Then switch the axis to tokens, choose the pilot as run A, and browse its checkpoints while reading samples.
The training sanity protocol orders tests from cheapest to most expensive: initial loss against its theoretical value, gradient in every parameter, overfitting a fixed batch, per-layer metrics over a few steps, and finally a small end-to-end pilot with separate validation. It is this project’s version of the tools module’s sanity checks and Karpathy’s recipe: do not proceed while the previous test fails.
One training step and its decisions
The GPT from p06-l03 returns logits for each position. Given a token window from the p06-l02 shard stream, the model receives the first and each position predicts the next. Batch mean cross-entropy is
It is measured in nats per token, and its exponential is perplexity. If targets are masked, such as padding or end-of-document, the denominator counts only valid positions. For the same reason, aggregate validation loss by summing losses and dividing by total targets: averaging means of different-sized batches gives a different quantity. In this lab all windows have targets, so the simple mean is correct.
A complete step does the following in order:
lr = lr_at(step, warmup, steps, peak, floor) # 1. planificador: la tasa de ESTE paso
for group in opt.param_groups: group['lr'] = lr
x, y = windows(train, B, T, generator) # 2. lote nuevo: y es x desplazado una posición
opt.zero_grad(set_to_none=True) # 3. sin gradientes del paso anterior
with torch.autocast('cuda', dtype=torch.bfloat16):
loss = F.cross_entropy(model(x).reshape(-1, V), y.reshape(-1))
loss.backward() # 4. gradientes en float32
norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) # 5. norma ANTES del recorte
opt.step() # 6. AdamW con decay desacoplado
Setting the rate manually at the start of the step, rather than using a PyTorch scheduler object, makes the rate used by each update explicit. This is what we log and what a checkpoint must reconstruct. With bfloat16, loss scaling is unnecessary. With float16, it is needed, and gradients must be unscaled (scaler.unscale_) before measuring and clipping their norm, or the threshold would apply to scaled gradients.
An often overlooked consequence: if every gradient in a training run were multiplied by the same constant, the Adam step would barely change because numerator and denominator scale equally, apart from . With Adam, clipping does not directly bound step size. It reduces the influence of an anomalous gradient on moving averages and , so an unusual batch does not drag the moments along. In our probe, pre-clipping norm is 6.23 at step 1, 1.81 at step 500, and 2.02 at step 1000: clipping at acts at every logged step. That is why we log the norm. A threshold that always activates is part of the optimizer rather than an emergency mechanism, and it is useful to know that.
Which parameters receive weight decay
AdamW separates weight decay from adaptive moments. With bias-corrected moments and , each coordinate updates as
If is added to the gradient instead, as L2 regularization, that term passes through and and is ultimately divided by : coordinates with large gradients are regularized less than those with small gradients. Loshchilov and Hutter show that with Adam the two forms are not equivalent and that decoupled decay generalizes better; see the lesson on decay versus L2.
Which tensors receive decay is a decision, not a law. Here we apply it only to projection matrices, attention and MLP, excluding biases, LayerNorm gains, and embeddings. LayerNorm gains start at 1, and pushing them toward 0 shrinks the signal scale the network needs. Biases multiply nothing and do not contribute complexity in the sense decay aims to control. Embeddings are debatable: nanoGPT applies decay to every tensor of two or more dimensions, including embeddings. We exclude them because the token matrix is also the output head, with tied weights, and each row receives gradient only when its token appears, so decay would shrink rare tokens every step without a compensating signal. Both policies are defensible; not knowing which one is in use is not.
There are two implementation traps. With tied weights, lm_head.weight and transformer.wte.weight are the same object. named_parameters() returns it once, under the first name it finds, but a hand-built list may include it twice, and PyTorch rejects a parameter repeated across groups. The second trap is forgetting a parameter: a tensor absent from all groups is never trained and produces no error. The lab’s param_groups therefore checks that groups are disjoint, cover all trainable parameters, and place the tied matrix in the no-decay group.
Three tests before the pilot
Initial loss has an expected value
If all logits at a position are equal, the distribution is uniform over tokens and loss is exactly , regardless of target. For (GPT-2), this is nats; for our vocabulary, . Initialization gives small logits, not equal ones, and the next proposition states how far expected loss departs from .
Proof
(1) Loss for target is ; averaging over uniform gives the expression. Write . Since the exponential is strictly convex, Jensen’s inequality gives , with equality only when all are equal. Taking logarithms gives , as claimed.
(2) If is independent of , , leaving . Since is concave, Jensen in the other direction gives , using for . For large , concentrates around its mean, with variance , and the inequality is nearly an equality.
∎Point (1) explains why is the reference: nonconstant logits increase mean loss. Point (2) says by how much: . We still need for our model. With p06-l03 initialization, the output head is the embedding matrix with entries , applied to final LayerNorm output whose coordinates have mean 0 and variance 1, since gain is 1. Each logit is a sum of independent products, so :
| measured in the lab | ||||
|---|---|---|---|---|
| 64 | 50257 | 0.160 | 10.8377 | 10.8328 |
| 512 | 513 | 0.453 | 6.3427 | 6.3467 |
| 768 | 50257 | 0.554 | 10.9785 | (not measured) |
The sanity cell also prints measured logit standard deviation, 0.160 and 0.460. Using that value, stays within 0.02 of observed loss. The last row is a warning: for GPT-2 small with tied weights, expected initial loss is 10.98, 0.15 away from , without any error. A tolerance of 0.1 against is valid for the lab’s dimension-64 model, not every model. Compare with using measured .
This reasoning also says what cannot cause anomalous initial loss. Misaligned labels do not change initial loss: with nearly uniform logits, any target costs about . That bug is detected during overfitting or at step 1000, not step 0. An out-of-vocabulary ID raises an exception in the embedding or loss rather than returning a number. Base-2 logarithms give . Sum reduction instead of mean multiplies loss by . And loss of 25 with requires, for Gaussian logits, , more than ten times the expected scale: look for an initialization with wrong standard deviation, a head without final LayerNorm, or a scale factor multiplied rather than divided.
Memorize a fixed batch
Take a batch and repeat it each step without changing inputs or targets, without dropout or decay. A model with sufficient capacity and a correct optimizer memorizes it: loss must fall nearly to zero. In the lab, a two-block GPT of dimension 128 memorizes 4 windows of 64 real tokens, or 256 targets, and falls below 0.05 at step 39. If it stalls, the bug lies in the gradient chain: absent or misplaced zero_grad, parameters outside the optimizer, a disconnected layer such as a forgotten detach, an absurd learning rate, or labels that do not match inputs. Before that, the cell runs a cheaper check: after backward, every tensor has a finite nonzero gradient. A parameter that never receives gradients can survive an entire training run without an error.
Overfitting has a clear limit: it shows the system can fit data, not that it generalizes. That is why validation always uses examples unseen during training.
Gradients and updates are different
Instrumentation logs two quantities per block. Gradient norm before clipping locates explosions. Relative update measures how much weights actually move:
calculated over the concatenated block tensors before and after opt.step(), including decay. With AdamW, multiplying gradient norm by learning rate does not give the update: the optimizer normalizes each coordinate by . The first step shows this in pure form.
We check this with the records. Each block has parameters and initially. In the probe with peak rate and 50 warmup steps, the step-1 rate is and the formula predicts . The dashboard shows . A detail about that : 56% of for the block comes from LayerNorm gains, which equal 1. The block-level ratio is dominated by 1024 numbers out of more than three million in the block. Therefore also log per-tensor ratios when a block behaves strangely.
The theorem explains two things. Without warmup, the first step would move every weight by in the direction of a gradient sign estimated from one batch: with , 4% of typical weight scale in one step. It also sets the scale of : in steady state, is usually much smaller than 1 because gradient signs fluctuate across batches. At step 1000 in the probe, is around with and with . A rule of thumb in the CS231n notes puts a healthy ratio around . A sustained means each step rewrites 10% of that block’s weights: its rate is too high or its norm abnormally small, since a nearly zero denominator also inflates . The lab computes with in the denominator because no block has zero norm. If one could, explicitly decide what to record.
Schedule the rate without hiding endpoints
The warmup and cosine schedule combines a linear rise with a smooth decline. Warmup avoids the previous theorem’s -sized sign steps while is estimated from very few batches. Liu et al. analyze this as reducing adaptive-rate variance in early steps. Let be update index, warmup steps, and the plan end, with and :
The branches meet: at the cosine gives , the limit of the ramp; at it gives , matching the third branch. If , the first branch does not exist and the schedule starts at . The indexing convention matters at endpoints. The lab numbers updates : the first uses rather than wasting a step at , and the last uses exactly . A loop over with the same formula takes a zero-rate step and never reaches . Either convention works if chosen and tested; the coding exercise checks the function at the endpoints.
Compare with linear decay to zero without attributing unmeasured results to either. With and decay progress , linear gives and cosine gives . They coincide at , , and . One quarter through decay, linear retains of the peak rate and cosine ; at three quarters, versus . Cosine spends more time near the maximum and near the end, with zero derivative at both endpoints. Which shape gives lower loss under fixed budget is empirical. The lab accepts schedule='lineal' to answer using the same data, seed, and step count. Our pilot uses cosine to 10% of peak rate, like GPT-3 (Brown et al., appendix B).
A TinyStories pilot
The TinyStories pilot trains a small model end to end with the same code on a corpus where success is visible. TinyStories is a collection of short stories generated by GPT-3.5 and GPT-4 using the vocabulary of a three- or four-year-old. Its authors show that models under 10 million parameters, or with a single transformer block, trained on it generate fluent and coherent multi-paragraph stories with almost perfect grammar. This is what we need: if our system cannot achieve it with 13 million parameters, the problem is ours.
Data. The roneneldan/TinyStories repository publishes training in four parquet files and validation in one, with 21990 stories. The lab pins a repository revision, checks each file’s SHA-256, and uses the first 250000 stories from the first parquet, which has 529930. After removing exact duplicates there are 114388456 training tokens, 226 MB of text, or 1.98 bytes per token with the p06-l02 BPE. Deduplication finds something important: 800 validation stories, 3.6%, are identical to training stories. They are removed from validation, leaving 21190 stories and 9303582 tokens. Without this, part of validation loss would measure memory rather than generalization.
Model and plan. The pilot uses the GPT class from p06-l03 with 4 blocks, 8 heads, dimension 512, and context 256. With our vocabulary of 513 IDs this gives parameters, within the project’s requested 10-to-30-million range. The batch has 32 windows, 8192 tokens per step; the 12000-step plan processes 98.3 million tokens, 86% of a pass over the data and about 7.6 tokens per parameter. The rate rises for 300 steps to and decays by cosine to , with AdamW , decay 0.1 on matrices, clipping to 1, and no dropout because windows are not repeated frequently. On our 4060, a step costs 0.15 to 0.2 s and peak memory is 1.9 GB, so the full plan takes half an hour to forty minutes including evaluations.
Why . The rate probe uses 1024-token batches and shows is already aggressive at that scale. At step 1000 validation is 2.164 with and 2.244 with , although at step 500 the higher rate led, 2.540 versus 2.573. An eightfold larger batch reduces gradient noise and tolerates a somewhat higher rate. lies between the two and is what GPT-3 used for its 125-million model. This is a reasoned decision, not a measured optimum. With another half hour, rerun the pilot at and compare on the dashboard.
Short verification results and expectations. To verify the lab, we ran the first 3000 steps of the plan, 24.6 million tokens, one quarter of it. This is the figure’s third run. Validation goes from 6.277 at step 1 to 1.527 at 1000, 1.333 at 2000, and 1.248 at 3000: perplexity per token, or bits per byte of text. The step-3000 sample is already grammatical (“Once upon a time, there was a kind lady. She was three years old and very good. […] One day, the lady was feeling very hungry. She knew what to do. She went to the kitchen to get a piece of poem.”) while revealing its limit: the model has learned sentence form and story tone, but not coherence between sentences, with a three-year-old lady and a poem in the kitchen. The curve is still falling, by 0.036 between steps 2500 and 3000, and three quarters of the tokens and the entire rate decay remain.
We have not measured the full plan. The expectation is what the TinyStories paper describes for models of this size: multi-paragraph stories, grammatical and reasonably coherent. As a scale reference, the 15-million-parameter llama2.c model, 6 layers, dimension 288, context 256, trained for several hours on four A100s, reaches 1.072 validation nats per token. This is not directly comparable to ours: it uses the Llama 2 tokenizer with 32000 tokens, whose tokens span many more bytes. Compare bits per byte across different tokenizers rather than loss per token. The final JSON includes a story for each of four prompts: read them all before accepting the pilot.
Lab
Run the cells in order from the project root in an environment with PyTorch and CUDA, NumPy, pyarrow, regex, tiktoken, and hypothesis. The lab needs p06-l02 preparation: it reads the manifest, verifies hashes, and loads its vocabulary of 512 ordinary IDs plus the separator. It also avoids copying code: it extracts the p06-l01 encoder and p06-l03 GPT class from the current MDX and saves their SHA-256 hashes so a later change requires preparing data again.
The p06-l02 data is sought in p06_data, configurable with P06_DATA_DIR. Everything produced by this lab goes to p06_pilot (P06_PILOT_DIR). The first cell downloads 259 MB of parquet, one training file and the validation file, tokenizes 250000 stories in under two minutes in our measurement, and writes train.bin, validation.bin, smaller probe files, and data.json with all hashes. If data is already prepared and verified, nothing is repeated. With P06_PILOT_QUICK=1, the whole lab runs as a smoke test: 20000 stories and at most 200 steps per run. This is how the lesson was checked before starting long runs.
"""Piloto TinyStories con el GPT y el BPE actuales de las lecciones p06.
prepare(): CPU y red. sanity() y pilot(): CUDA. Todo se escribe en P06_PILOT_DIR
(por defecto p06_pilot). Con P06_PILOT_QUICK=1 el mismo código hace una prueba
de humo: 20000 historias de entrenamiento y 200 pasos como máximo por ejecución.
"""
import hashlib
import json
import math
import os
import time
import urllib.error
import urllib.request
from pathlib import Path
import numpy as np
import torch
import torch.nn.functional as F
def project_root():
configured = os.environ.get('P06_PROJECT_ROOT')
for c in ([Path(configured)] if configured else [Path.cwd(), *Path.cwd().parents]):
if (c / 'src/content/lessons/p06').is_dir():
return c.resolve()
raise FileNotFoundError('Define P06_PROJECT_ROOT con la raíz del proyecto')
ROOT = project_root()
HERE = Path(os.environ.get('P06_PILOT_DIR', 'p06_pilot')).resolve()
HERE.mkdir(parents=True, exist_ok=True)
DATA02 = Path(os.environ.get('P06_DATA_DIR', 'p06_data')).resolve()
os.environ['BPE_DATA_DIR'] = str(HERE / 'bpe_cache')
os.environ['P06_PROJECT_ROOT'] = str(ROOT)
os.environ['P06_DATA_DIR'] = str(DATA02)
QUICK = os.environ.get('P06_PILOT_QUICK') == '1'
TRAIN_DOCS = 20_000 if QUICK else 250_000
PROBE_DOCS = {'train': 5000, 'validation': 500}
# roneneldan/TinyStories en una revisión fija: nombre, bytes y SHA-256 (oid LFS) de cada parquet.
REVISION = 'f54c09fd23315a6f9c86f9dc80f725de7d8f9c64'
HF = f'https://huggingface.co/datasets/roneneldan/TinyStories/resolve/{REVISION}/data/'
PARQUET = {
'train': ('train-00000-of-00004-2d5a1467fff1081b.parquet', 248731111,
'77cf780cebe52b6e83e3a2ac84bc56d8059363113e41d17a023f1d8b2ed0fc0b'),
'validation': ('validation-00000-of-00001-869c898b519ad725.parquet', 9989127,
'33406a6206554cfc279c29c11f4df51528af487aa1a602b075566fc83c49dcab'),
}
def cell(filename, title):
text = (ROOT / 'src/content/lessons/p06' / filename).read_text(encoding='utf-8')
marker = f'```python run runtime=local title="{title}"\n'
return text.split(marker, 1)[1].split('\n```', 1)[0]
def lesson_envs():
bpe_code = cell('l01-tokenizador-bpe.mdx', 'Codificador y entrenador BPE incremental')
bpe = {'__name__': 'bpe_actual'}
exec(compile(bpe_code, 'p06-l01.mdx', 'exec'), bpe)
pipe_cell = cell('l02-datos-de-preentrenamiento.mdx', 'Descarga, tokenización en procesos y shards')
pipe_code = pipe_cell.split("source = r'''\n", 1)[1].split("\n'''", 1)[0]
pipe = {'__name__': 'pipeline_actual'}
exec(compile(pipe_code, 'p06-l02.mdx', 'exec'), pipe)
if not (DATA02 / 'manifest.json').exists():
raise FileNotFoundError(f'No hay manifiesto en {DATA02}: ejecuta antes el laboratorio de p06-l02')
manifest = json.loads((DATA02 / 'manifest.json').read_text(encoding='utf-8'))
pipe['verify_manifest'](manifest)
payload = json.loads((DATA02 / manifest['vocab_file']).read_text(encoding='utf-8'))
ranks = {bytes.fromhex(k): v for k, v in payload['vocab_hex'].items()}
assert payload['pretokenization'] == bpe['PAT'].pattern
special = payload['special_id']
assert len(ranks) == special == 512
enc = bpe['make_text_encoder'](ranks, special_id=special)
rev = {rank: token for token, rank in ranks.items()}
rev[special] = payload['special_literal'].encode('utf-8')
model_cell = cell('l03-modelo-gpt-y-paridad.mdx', 'GPT propio y controles')
model_code = model_cell.split('\nattention_test()\nbehavior_test()', 1)[0]
model = {'__name__': 'modelo_actual'}
exec(compile(model_code, 'p06-l03.mdx', 'exec'), model)
return enc, rev, special, model['GPT'], manifest, {
'gpt_code_sha256': hashlib.sha256(model_cell.encode('utf-8')).hexdigest(),
'bpe_code_sha256': manifest['tokenizer_code_sha256'],
'vocab_sha256': manifest['vocab_sha256']}
def file_sha(path):
digest = hashlib.sha256()
with open(path, 'rb') as f:
while chunk := f.read(1 << 22):
digest.update(chunk)
return digest.hexdigest()
def download(name, size, sha):
path = HERE / 'parquet' / name
path.parent.mkdir(exist_ok=True)
if path.exists() and path.stat().st_size == size and file_sha(path) == sha:
return path
part = path.with_name(name + '.part')
for attempt in range(8):
have = part.stat().st_size if part.exists() else 0
if have >= size:
break
request = urllib.request.Request(HF + name, headers={'Range': f'bytes={have}-'} if have else {})
try:
with urllib.request.urlopen(request, timeout=120) as r:
with open(part, 'ab' if have and r.status == 206 else 'wb') as f:
while chunk := r.read(1 << 20):
f.write(chunk)
except urllib.error.HTTPError as error:
if error.code not in (429, 500, 502, 503, 504) or attempt == 7:
raise
time.sleep(min(60, 5 * 2**attempt))
except (urllib.error.URLError, TimeoutError, ConnectionError):
if attempt == 7:
raise
time.sleep(min(60, 5 * 2**attempt))
if part.stat().st_size != size or file_sha(part) != sha:
part.unlink()
raise ValueError(f'{name}: tamaño o SHA-256 distintos; vuelve a ejecutar la descarga')
part.replace(path)
return path
def tokenize_split(split, enc, special, seen, probe_seen, limit):
"""Historias en el orden del parquet, sin duplicados exactos; escribe IDs uint16 y huellas.
Además guarda el sondeo: las primeras historias del split sin duplicados dentro del propio
sondeo (5000 de entrenamiento y 500 de validación), que reproducen los registros de la figura."""
import pyarrow.parquet as pq
def write(name, ids):
values = np.asarray(ids, dtype=np.int64)
if values.size and not (0 <= values.min() and values.max() <= special):
raise ValueError('ID fuera del vocabulario')
tmp = (HERE / name).with_suffix('.tmp')
values.astype('<u2').tofile(tmp)
tmp.replace(HERE / name)
return file_sha(HERE / name)
full, probe = hashlib.sha256(), hashlib.sha256()
ids, probe_ids = [], []
kept = probe_kept = duplicates = text_bytes = 0
start = time.time()
for batch in pq.ParquetFile(download(*PARQUET[split])).iter_batches(columns=['text'], batch_size=5000):
for text in batch.column(0).to_pylist():
full_done = limit is not None and kept >= limit
probe_done = probe_kept >= PROBE_DOCS[split]
if full_done and probe_done:
break
raw = text.encode('utf-8')
key = hashlib.sha256(raw).digest()
doc = None
if not probe_done and key not in probe_seen:
probe_seen.add(key)
probe.update(len(raw).to_bytes(8, 'big')); probe.update(raw)
doc = enc(text) + [special]
probe_ids.extend(doc); probe_kept += 1
if full_done:
continue
if key in seen:
duplicates += 1
continue
seen.add(key)
full.update(len(raw).to_bytes(8, 'big')); full.update(raw)
ids.extend(doc if doc is not None else enc(text) + [special])
kept += 1; text_bytes += len(raw)
print(f'{split}: {kept} historias, {len(ids)} tokens, {time.time()-start:.0f} s', flush=True)
if (limit is not None and kept >= limit) and probe_kept >= PROBE_DOCS[split]:
break
return {'file': PARQUET[split][0], 'documents': kept, 'duplicates_removed': duplicates,
'tokens': len(ids), 'text_bytes': text_bytes, 'sample_sha256': full.hexdigest(),
'ids_sha256': write(f'{split}.bin', ids), 'probe_documents': probe_kept,
'probe_tokens': len(probe_ids), 'probe_sha256': probe.hexdigest(),
'probe_ids_sha256': write(f'{split}-probe.bin', probe_ids)}
def prepare():
if (HERE / 'data.json').exists():
try:
meta = source_data()[0]
if meta['quick'] == QUICK and meta['train']['documents'] == TRAIN_DOCS:
print('Datos ya preparados y verificados:',
{s: meta[s]['tokens'] for s in ('train', 'validation')}, flush=True)
return
except (ValueError, KeyError, FileNotFoundError) as error:
print('Se vuelven a preparar los datos:', error, flush=True)
enc, rev, special, GPT, manifest, hashes = lesson_envs()
seen, probe_seen = set(), set()
# Primero el entrenamiento: una historia de validación idéntica a una ya vista se descarta.
result = {'quick': QUICK, 'revision': REVISION,
'train': tokenize_split('train', enc, special, seen, probe_seen, TRAIN_DOCS),
'validation': tokenize_split('validation', enc, special, seen, probe_seen, None)}
result.update(hashes)
(HERE / 'data.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps(result, ensure_ascii=False, indent=2), flush=True)
def source_data():
meta = json.loads((HERE / 'data.json').read_text(encoding='utf-8'))
enc, rev, special, GPT, manifest, hashes = lesson_envs()
for k, v in hashes.items():
if meta[k] != v:
raise ValueError('El código o el vocabulario ya no coincide: vuelve a preparar')
arrays = {}
for split in ('train', 'validation'):
for key, name, digest in [(split, f'{split}.bin', 'ids_sha256'),
(split + '_probe', f'{split}-probe.bin', 'probe_ids_sha256')]:
if file_sha(HERE / name) != meta[split][digest]:
raise ValueError(f'El contenido de {name} cambió')
arrays[key] = np.memmap(HERE / name, dtype='<u2', mode='r')
return meta, enc, rev, special, GPT, arrays
def lr_at(step, warmup, max_steps, peak, floor):
if not (0 < warmup < max_steps and 0 <= step <= max_steps and 0 <= floor <= peak):
raise ValueError('parámetros del planificador inválidos')
if step < warmup:
return peak * step / warmup
return floor + 0.5*(peak-floor)*(1+math.cos(math.pi*(step-warmup)/(max_steps-warmup)))
def lr_linear(step, warmup, max_steps, peak):
if not (0 < warmup < max_steps and 0 <= step <= max_steps):
raise ValueError('parámetros del planificador inválidos')
return peak * step / warmup if step < warmup else peak * (max_steps-step) / (max_steps-warmup)
def param_groups(model, decay):
yes, no = [], []
for name, parameter in model.named_parameters():
if parameter.ndim >= 2 and name not in ('transformer.wte.weight', 'transformer.wpe.weight'):
yes.append(parameter)
else:
no.append(parameter)
every = {id(p) for p in model.parameters() if p.requires_grad}
assert len({id(p) for p in yes+no}) == len(yes)+len(no) == len(every)
assert id(model.transformer.wte.weight) in {id(p) for p in no}
return [{'params': yes, 'weight_decay': decay}, {'params': no, 'weight_decay': 0.0}]
def windows(array, batch, length, generator):
indices = torch.randint(0, len(array)-length, (batch,), generator=generator).tolist()
rows = np.stack([np.array(array[i:i+length+1], dtype=np.int64) for i in indices])
tensor = torch.from_numpy(rows).cuda()
return tensor[:, :-1].contiguous(), tensor[:, 1:].contiguous()
def sanity():
meta, enc, rev, special, GPT, arrays = source_data()
assert lr_at(0,10,100,0.001,0.0001)==0
assert lr_at(10,10,100,0.001,0.0001)==0.001
assert lr_at(100,10,100,0.001,0.0001)==0.0001
assert lr_linear(100,10,100,0.001)==0
device, vocab = 'cuda', special + 1
# 1. Pérdida inicial: GPT-2 (V = 50257) con IDs aleatorios y nuestro modelo con datos reales.
for V, d, layers, context in [(50257, 64, 2, 16), (vocab, 512, 4, 128)]:
torch.manual_seed(8)
initial = GPT(vocab=V, context=context, layers=layers, heads=4, d=d, dropout=0).to(device).eval()
generator = torch.Generator().manual_seed(100)
if V == 50257:
ids = torch.randint(0, V, (4, context), generator=generator).cuda()
x, y = ids[:, :-1], ids[:, 1:]
else:
x, y = windows(arrays['train_probe'], 8, context, generator)
with torch.no_grad():
logits = initial(x).float()
loss = F.cross_entropy(logits.reshape(-1, V), y.reshape(-1)).item()
sigma = logits.std(dim=-1).mean().item()
print(f'V={V}, d={d}: pérdida inicial {loss:.4f}, ln V = {math.log(V):.4f}, '
f'diferencia {loss-math.log(V):+.4f}, σ de los logits {sigma:.3f}, '
f'ln V + σ²/2 = {math.log(V)+sigma**2/2:.4f}', flush=True)
if V == 50257:
assert abs(loss - math.log(V)) < 0.1 # requisito del proyecto
assert abs(loss - math.log(V) - sigma**2/2) < 0.05 # predicción con la σ medida
del initial, logits
# 2. Todos los parámetros reciben un gradiente finito y no nulo.
torch.manual_seed(9)
model = GPT(vocab=vocab, context=64, layers=2, heads=4, d=128, dropout=0).to(device).train()
opt = torch.optim.AdamW(param_groups(model, 0.0), lr=0.002, foreach=False)
g = torch.Generator().manual_seed(10)
x, y = windows(arrays['train_probe'], 4, 64, g) # mismo lote con o sin P06_PILOT_QUICK
F.cross_entropy(model(x).reshape(-1, vocab), y.reshape(-1)).backward()
silent = [n for n, p in model.named_parameters()
if p.grad is None or not torch.isfinite(p.grad).all() or p.grad.abs().max() == 0]
assert not silent, silent
print('Gradiente finito y no nulo en los', sum(1 for _ in model.parameters()), 'tensores', flush=True)
# 3. Sobreajuste de un lote fijo, sin dropout ni decay.
for step in range(1, 501):
opt.zero_grad(set_to_none=True)
logits = model(x)
loss = F.cross_entropy(logits.reshape(-1, vocab), y.reshape(-1))
loss.backward(); norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
if step % 25 == 0:
print('sobreajuste paso', step, 'pérdida', round(loss.item(), 4), 'norma', round(norm.item(), 3), flush=True)
if loss.item() < 0.05:
break
assert loss.item() < 0.05
print('sobreajuste conseguido en el paso', step, 'con pérdida', round(loss.item(), 4), flush=True)
del model, opt, x, y, logits, loss
torch.cuda.empty_cache()
def validate(model, fixed):
model.eval()
with torch.no_grad():
losses = [F.cross_entropy((logits := model(x)).reshape(-1, logits.shape[-1]), y.reshape(-1)).item()
for x, y in fixed]
model.train()
return sum(losses) / len(losses)
def generate(model, enc, rev, prompt, count=120, seed=2026, stop=512):
model.eval()
ids = enc(prompt)
generator = torch.Generator(device='cuda').manual_seed(seed)
with torch.no_grad():
for _ in range(count):
x = torch.tensor([ids[-model.context:]], device='cuda')
logits = model(x)[0, -1, :].float()
top = torch.topk(logits, min(30, len(logits)))
probs = F.softmax(top.values / 0.8, dim=-1)
token = int(top.indices[torch.multinomial(probs, 1, generator=generator)].item())
if token == stop:
break
ids.append(token)
model.train()
return b''.join(rev[i] for i in ids).decode('utf-8', errors='replace')
# Sondeo de tasas (los registros de la figura) y piloto completo.
PROBE = {'data': 'sondeo', 'batch': 8, 'context': 128, 'dropout': 0.1, 'val_batches': 5,
'warmup': 50, 'betas': (0.9, 0.999), 'fused': False, 'sample_tokens': 120}
FULL = {'data': 'completo', 'batch': 32, 'context': 256, 'dropout': 0.0, 'val_batches': 20,
'warmup': 300, 'betas': (0.9, 0.95), 'fused': True, 'sample_tokens': 200}
PROMPTS = ['Once upon a time', 'Tom and Lily went to the park.', 'One day, a little cat', 'The sun was hot and']
def pilot(peak, steps, interval, resume=False, stop_after=None, profile=PROBE, schedule='coseno'):
meta, enc, rev, special, GPT, arrays = source_data()
if QUICK:
stop_after = min(stop_after or steps, 200)
elif meta['quick']:
raise ValueError('Los datos son de la prueba de humo: ejecuta prepare() sin P06_PILOT_QUICK')
vocab, B, T = special + 1, profile['batch'], profile['context']
if profile['data'] == 'sondeo':
train, valid = arrays['train_probe'], arrays['validation_probe']
train_hash, val_hash = meta['train']['probe_sha256'], meta['validation']['probe_sha256']
else:
train, valid = arrays['train'], arrays['validation']
train_hash, val_hash = meta['train']['sample_sha256'], meta['validation']['sample_sha256']
torch.manual_seed(37)
model = GPT(vocab=vocab, context=T, layers=4, heads=8, d=512, dropout=profile['dropout']).cuda().train()
n = sum(p.numel() for p in model.parameters())
assert 10_000_000 <= n <= 30_000_000
opt = torch.optim.AdamW(param_groups(model, 0.1), lr=peak, betas=profile['betas'],
**({'fused': True} if profile['fused'] else {'foreach': False}))
g = torch.Generator().manual_seed(123)
v = torch.Generator().manual_seed(456)
val = [windows(valid, B, T, v) for _ in range(profile['val_batches'])]
def lr_of(step):
if schedule == 'coseno':
return lr_at(step, min(profile['warmup'], steps-1), steps, peak, peak*0.1)
if schedule == 'lineal':
return lr_linear(step, min(profile['warmup'], steps-1), steps, peak)
raise ValueError(schedule)
config = {'data': profile['data'], 'parameters': n, 'layers': 4, 'heads': 8, 'd': 512, 'vocab': vocab,
'context': T, 'batch_size': B, 'steps': steps, 'warmup': min(profile['warmup'], steps-1),
'schedule': schedule, 'lr_min': peak*0.1 if schedule == 'coseno' else 0.0,
'weight_decay': 0.1, 'betas': list(profile['betas']), 'dropout': profile['dropout'],
'training_dtype': 'bf16 autocast', 'train_tokens': len(train), 'val_tokens': len(valid),
'train_hash': train_hash, 'val_hash': val_hash}
tag = f"{profile['data']}-{schedule}-{peak:g}"
path, checkpoint_path = HERE / f'pilot-{tag}.json', HERE / f'pilot-{tag}-checkpoint.pt'
points, start_step, elapsed = [], 1, 0.0
if resume:
state = torch.load(checkpoint_path, map_location='cpu', weights_only=False)
if state['config'] != config or state['lr_max'] != peak:
raise ValueError('Configuración, datos o plan de tasas distintos al checkpoint')
model.load_state_dict(state['model']); opt.load_state_dict(state['optimizer'])
torch.set_rng_state(state['torch_rng']); torch.cuda.set_rng_state_all(state['cuda_rng'])
g.set_state(state['data_rng'])
points, start_step, elapsed = state['points'], state['step'] + 1, state['elapsed']
print('Reanudado tras el paso', state['step'], flush=True)
if start_step > steps:
print('El entrenamiento ya completó el plan', flush=True)
return path
t0 = time.time()
def save_progress(extra=None):
tmp = path.with_suffix('.tmp')
result = {'lr_max': peak, 'seed': 37, 'config': config, 'checkpoints': points, **(extra or {})}
tmp.write_text(json.dumps(result, ensure_ascii=False, indent=1), encoding='utf-8')
tmp.replace(path)
def save_checkpoint(step):
tmp = checkpoint_path.with_suffix('.tmp')
torch.save({'step': step, 'model': model.state_dict(), 'optimizer': opt.state_dict(),
'torch_rng': torch.get_rng_state(), 'cuda_rng': torch.cuda.get_rng_state_all(),
'data_rng': g.get_state(), 'points': points, 'config': config, 'lr_max': peak,
'elapsed': elapsed + time.time() - t0}, tmp)
tmp.replace(checkpoint_path)
torch.cuda.reset_peak_memory_stats()
running, count = torch.zeros((), device='cuda'), 0
for step in range(start_step, steps + 1):
lr = lr_of(step)
for group in opt.param_groups:
group['lr'] = lr
x, y = windows(train, B, T, g)
opt.zero_grad(set_to_none=True)
with torch.autocast(device_type='cuda', dtype=torch.bfloat16):
logits = model(x)
loss = F.cross_entropy(logits.reshape(-1, vocab), y.reshape(-1))
loss.backward()
running += loss.detach(); count += 1
record = step % interval == 0 or step == 1 or step == steps or step == stop_after
if record:
if not math.isfinite(loss.item()):
raise RuntimeError(f'Pérdida no finita en el paso {step}')
grad_norms = {f'block_{i}': math.sqrt(sum(p.grad.detach().float().square().sum().item()
for p in block.parameters() if p.grad is not None))
for i, block in enumerate(model.transformer.h)}
saved = [[p.detach().clone() for p in b.parameters()] for b in model.transformer.h]
grad = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
if record:
ratios = {}
for i, (block, before) in enumerate(zip(model.transformer.h, saved)):
numerator = sum((p.detach()-q).float().square().sum().item() for p, q in zip(block.parameters(), before))
denominator = sum(q.float().square().sum().item() for q in before)
ratios[f'block_{i}'] = math.sqrt(numerator / denominator)
del saved
point = {'step': step, 'tokens': step * B * T, 'seconds': round(elapsed + time.time() - t0, 1),
'train_loss': float(loss.item()), 'train_loss_mean': running.item() / count,
'val_loss': validate(model, val), 'lr': lr, 'grad_norm': float(grad.item()),
'grad_norms': grad_norms, 'update_ratios': ratios,
'sample': generate(model, enc, rev, PROMPTS[0], profile['sample_tokens'], stop=special)}
running.zero_(); count = 0
points.append(point)
print(json.dumps(point, ensure_ascii=False), flush=True)
save_progress()
save_checkpoint(step)
if stop_after is not None and step >= stop_after:
print('Pausa después del checkpoint', step, flush=True)
break
extra = {}
if step == steps:
extra['final_samples'] = [{'prompt': p, 'text': generate(model, enc, rev, p, profile['sample_tokens'], 2026 + i, special)}
for i, p in enumerate(PROMPTS)]
for s in extra['final_samples']:
print('---', s['prompt'], '\n' + s['text'], flush=True)
config['gpu_peak_allocated_bytes'] = torch.cuda.max_memory_allocated()
save_progress(extra)
print('parámetros:', n, 'segundos:', points[-1]['seconds'], 'pico CUDA bytes:',
config['gpu_peak_allocated_bytes'], flush=True)
del model, opt, x, y, logits, loss, val
torch.cuda.empty_cache()
return path
prepare()npm run lab and open the connection link.The sanity cell chains the previous section’s tests. Initial loss uses and dimension 64 on random IDs, with the project’s requested 0.1 tolerance against , and also uses our vocabulary and pilot model on real text. In both cases it additionally requires loss within 0.05 of using measured . It then checks that all 28 tensors in a two-block GPT receive gradients and that this model memorizes a fixed batch to loss below 0.05.
sanity()npm run lab and open the connection link.The rate probe uses the 12938752-parameter model, context 128, batches of 8 windows, dropout 0.1, and a 3000-step plan with 50 warmup steps and cosine decay to 10% of peak rate, paused after checkpoint 1000. It trains on the first 5000 training stories and validates on the first 500 validation stories. These are the same data that produced the figure’s records, and data.json stores their fingerprints for verification. Each record saves the step’s batch loss and mean since the previous log before updating, plus validation on five fixed batches, per-block ratios, and a sample after updating. Sampling uses temperature 0.8, top-k 30, and a fixed seed; bytes that are not valid UTF-8 appear as replacement characters.
pilot(0.0003, 3000, 500, stop_after=1000)npm run lab and open the connection link.pilot(0.001, 3000, 500, stop_after=1000)npm run lab and open the connection link.Seeds and fingerprints fix the protocol but do not guarantee identical bits on another GPU or library version: the order of parallel additions changes. When repeating the probe for this lesson, we obtained 2.1632 and 2.2383 at step 1000 versus the recorded 2.1635 and 2.2444. The next cell compares your run with the figure’s record; expect differences in hundredths, not tenths.
recorded = json.loads((ROOT / 'src/widgets/p06/l04/pilot-runs.json').read_text(encoding='utf-8'))
for run in recorded[:2]:
mine = json.loads((HERE / f"pilot-sondeo-coseno-{run['lr_max']:g}.json").read_text(encoding='utf-8'))
assert mine['config']['train_hash'] == run['config']['train_hash'], 'datos del sondeo distintos'
assert mine['config']['val_hash'] == run['config']['val_hash'], 'validación del sondeo distinta'
theirs = {p['step']: p['val_loss'] for p in run['checkpoints']}
for p in mine['checkpoints']:
if p['step'] in theirs:
print(f"tasa {run['lr_max']:g}, paso {p['step']}: validación {p['val_loss']:.4f}, "
f"registrada {theirs[p['step']]:.4f}, diferencia {p['val_loss']-theirs[p['step']]:+.4f}")npm run lab and open the connection link.The full pilot is the long cell, thirty to forty minutes of GPU time. It saves a checkpoint every 500 steps, so an interruption loses at most 500, and finally generates one story for each of four prompts. The resulting JSON, p06_pilot/pilot-completo-coseno-0.0006.json, can be loaded into the figure.
pilot(0.0006, 12000, 500, profile=FULL)npm run lab and open the connection link.Each checkpoint atomically replaces the previous one and contains model, optimizer, CPU, GPU and data generator states, step, recorded points, and configuration. Resuming follows the same plan without repeating warmup and refuses to continue if data or configuration has changed. For example, to complete the probes or pilot after interruption:
pilot(0.0003, 3000, 500, resume=True)
pilot(0.0006, 12000, 500, profile=FULL, resume=True)
Exercises
import math
def get_lr(step, warmup, max_steps, max_lr, min_lr):
passSummary
Before long training, each component has a test ruling it out as a cause: initial loss against , gradients in all parameters, fixed-batch memorization, gradient norm and relative update by block, and finally a complete pilot with separate deduplicated validation. Cheap tests come first; the pilot validates what no unit test touches. With Adam, learning rate rather than gradient magnitude sets update scale: the first step is a sign step of size in each coordinate, which is why warmup exists.