Module contents
Stage 4 of 9Advanced 100 min

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 3⋅10−43\cdot10^{-4} or 10−310^{-3}, 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.

InteractivePilot training dashboard

Source: records from this lesson. A: peak rate 3·10⁻⁴, 1000 of 3000 steps, 1024 tokens per step, 12.9 M parameters. B: peak rate 1·10⁻³, 1000 of 3000 steps, 1024 tokens per step, 12.9 M parameters. The vertical line marks the checkpoint of A. Points are measurements; line segments only connect them. The training curve for A is one noisy batch loss.

Loss (nats per token)1.8284.2626.697A training, tokens 1024: 6.36102294921875A training, tokens 512000: 2.6417534351348877A training, tokens 1024000: 2.323563575744629B training, tokens 1024: 6.36102294921875B training, tokens 512000: 2.5982866287231445B training, tokens 1024000: 2.3965868949890137A validation, tokens 1024: 6.30073881149292A validation, tokens 512000: 2.572581481933594A validation, tokens 1024000: 2.1635274648666383B validation, tokens 1024: 6.199630641937256B validation, tokens 512000: 2.5398560047149656B validation, tokens 1024000: 2.2444272041320810241.02 M tokens
━ A training━ B training┄ A validation┄ B validation
Learning rate0.0005.12e-40.001A, tokens 1024: 0.000005999999999999999A, tokens 512000: 0.0002847925301326371A, tokens 1024000: 0.0002366068225961652B, tokens 1024: 0.00002B, tokens 512000: 0.0009493084337754572B, tokens 1024000: 0.000788689408653884110241.02 M tokens
━ A━ B
Global gradient norm before clipping0.9023.7666.629A, tokens 1024: 6.234428405761719A, tokens 512000: 1.8149899244308472A, tokens 1024000: 2.0178475379943848B, tokens 1024: 6.234428405761719B, tokens 512000: 1.2968182563781738B, tokens 1024000: 1.3490998744964610241.02 M tokens
━ A━ B
Update / weight, block 0 (log scale)1.91e-40.0010.009A, tokens 1024: 0.0002492286055128776A, tokens 512000: 0.002648348919334672A, tokens 1024000: 0.0021607256724961578B, tokens 1024: 0.0008307644691811453B, tokens 512000: 0.007134423467345839B, tokens 1024000: 0.005529756594135187510241.02 M tokens
━ A━ B
Sample A, step 1000

Once upon a time, there was a knea. But a pretture the park. He saw that he would not something special lots of wonderful, the cake. It felt scared to job. She put his grucket so scared and thank the flowed and said, "Can I will go!" The lit

Sample B, step 1000

Once upon a time, there was a tree. there was a big ground. The big horse and careful. His couldn't wait his eyes. "Oh name. She was find outside and saw the park. It was so happy. He slowly that they couldn't sll the pirate. They had made a passed

Gradient and training loss are measured before the step; validation, ratio, and sample afterwards. B shows its last checkpoint no later than A on the chosen axis. Compare by tokens when batch sizes differ.

step 1000
Horizontal axis
Step A1000
Tokens A1.02 M
Validation A2.164
Training A (one batch)2.324
Block ratio A2.16e-3
Loss, learning rate, gradient norm, and relative update by block, with the sample generated at each checkpoint. These are lab records; you can load JSON from your own run.

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 zb,t∈RV\vb{z}_{b,t}\in\R^V for each position. Given a T+1T+1 token window xb,1,…,xb,T+1x_{b,1},\ldots,x_{b,T+1} from the p06-l02 shard stream, the model receives the first TT and each position predicts the next. Batch mean cross-entropy is

L(θ)=−1BT∑b=1B∑t=1Tlog⁡pθ(xb,t+1∣xb,1:t),pθ(⋅∣xb,1:t)=softmax⁡(zb,t).\Loss(\theta)=-\frac{1}{BT}\sum_{b=1}^{B}\sum_{t=1}^{T}\log p_\theta(x_{b,t+1}\given x_{b,1:t}),\qquad p_\theta(\cdot\given x_{b,1:t})=\operatorname{softmax}(\vb{z}_{b,t}).

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 TT 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 m^/(v^+ϵ)\hat m/(\sqrt{\hat v}+\epsilon) would barely change because numerator and denominator scale equally, apart from ϵ\epsilon. With Adam, clipping does not directly bound step size. It reduces the influence of an anomalous gradient on moving averages mm and vv, so an unusual batch does not drag the moments along. In our 3⋅10−43\cdot10^{-4} probe, pre-clipping norm is 6.23 at step 1, 1.81 at step 500, and 2.02 at step 1000: clipping at c=1c=1 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 m^t\hat m_t and v^t\hat v_t, each coordinate updates as

θt+1=θt−ηt(m^tv^t+ϵ+λ θt).\theta_{t+1}=\theta_t-\eta_t\left(\frac{\hat m_t}{\sqrt{\hat v_t}+\epsilon}+\lambda\,\theta_t\right).

If λθ\lambda\theta is added to the gradient instead, as L2 regularization, that term passes through mm and vv and is ultimately divided by v^\sqrt{\hat v}: 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 VV tokens and loss is exactly ln⁡V\ln V, regardless of target. For V=50257V=50257 (GPT-2), this is 10.824910.8249 nats; for our V=513V=513 vocabulary, ln⁡513=6.2403\ln 513=6.2403. Initialization gives small logits, not equal ones, and the next proposition states how far expected loss departs from ln⁡V\ln V.

Proof

(1) Loss for target yy is log⁡∑jezj−zy\log\sum_j e^{z_j}-z_y; averaging over uniform yy gives the expression. Write log⁡∑jezj=ln⁡V+log⁡(1V∑jezj)\log\sum_j e^{z_j}=\ln V+\log\big(\frac1V\sum_j e^{z_j}\big). Since the exponential is strictly convex, Jensen’s inequality gives 1V∑jezj≥e1V∑jzj\frac1V\sum_j e^{z_j}\ge e^{\frac1V\sum_j z_j}, with equality only when all zjz_j are equal. Taking logarithms gives log⁡∑jezj≥ln⁡V+1V∑jzj\log\sum_j e^{z_j}\ge \ln V+\frac1V\sum_j z_j, as claimed.

(2) If yy is independent of z\vb{z}, E[zy]=0\mathbb{E}[z_y]=0, leaving E[log⁡∑jezj]\mathbb{E}[\log\sum_j e^{z_j}]. Since log⁡\log is concave, Jensen in the other direction gives E[log⁡∑jezj]≤log⁡∑jE[ezj]=log⁡(Veσ2/2)=ln⁡V+σ2/2\mathbb{E}[\log\sum_j e^{z_j}]\le\log\sum_j\mathbb{E}[e^{z_j}]=\log\big(V e^{\sigma^2/2}\big)=\ln V+\sigma^2/2, using E[ez]=eσ2/2\mathbb{E}[e^{z}]=e^{\sigma^2/2} for z∼N(0,σ2)z\sim\mathcal{N}(0,\sigma^2). For large VV, 1V∑jezj\frac1V\sum_j e^{z_j} concentrates around its mean, with variance (e2σ2−eσ2)/V(e^{2\sigma^2}-e^{\sigma^2})/V, and the inequality is nearly an equality.

∎

Point (1) explains why ln⁡V\ln V is the reference: nonconstant logits increase mean loss. Point (2) says by how much: σ2/2\sigma^2/2. We still need σ\sigma for our model. With p06-l03 initialization, the output head is the embedding matrix with entries N(0,0.022)\mathcal{N}(0,0.02^2), applied to final LayerNorm output whose coordinates have mean 0 and variance 1, since gain is 1. Each logit is a sum of dd independent products, so σ2≈0.022 d\sigma^2\approx 0.02^2\,d:

ddVVσ=0.02d\sigma=0.02\sqrt dln⁡V+σ2/2\ln V+\sigma^2/2measured in the lab
64502570.16010.837710.8328
5125130.4536.34276.3467
768502570.55410.9785(not measured)

The sanity cell also prints measured logit standard deviation, 0.160 and 0.460. Using that value, ln⁡V+σ2/2\ln V+\sigma^2/2 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 ln⁡V\ln V, without any error. A tolerance of 0.1 against ln⁡V\ln V is valid for the lab’s dimension-64 model, not every model. Compare with ln⁡V+σ2/2\ln V+\sigma^2/2 using measured σ\sigma.

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 ln⁡V\ln V. 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 log⁡250257=15.62\log_2 50257=15.62. Sum reduction instead of mean multiplies loss by BTBT. And loss of 25 with V=50257V=50257 requires, for Gaussian logits, σ≈5.7\sigma\approx5.7, 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:

r=∥θt+1−θt∥2∥θt∥2,r=\frac{\norm{\theta_{t+1}-\theta_t}_2}{\norm{\theta_t}_2},

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 v^\sqrt{\hat v}. The first step shows this in pure form.

We check this with the records. Each block has n=3152384n=3152384 parameters and rms⁡(θ1)=0.02405\operatorname{rms}(\theta_1)=0.02405 initially. In the probe with peak rate 3⋅10−43\cdot10^{-4} and 50 warmup steps, the step-1 rate is 6⋅10−66\cdot10^{-6} and the formula predicts r1=2.494⋅10−4r_1=2.494\cdot10^{-4}. The dashboard shows 2.492⋅10−42.492\cdot10^{-4}. A detail about that rms⁡\operatorname{rms}: 56% of ∥θ∥22\norm{\theta}_2^2 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 ηmax⁡\eta_{\max} in the direction of a gradient sign estimated from one batch: with ηmax⁡=10−3\eta_{\max}=10^{-3}, 4% of typical weight scale in one step. It also sets the scale of rr: in steady state, ∣m^/v^∣|\hat m/\sqrt{\hat v}| is usually much smaller than 1 because gradient signs fluctuate across batches. At step 1000 in the probe, rr is around 2.2⋅10−32.2\cdot10^{-3} with 3⋅10−43\cdot10^{-4} and 5.6⋅10−35.6\cdot10^{-3} with 10−310^{-3}. A rule of thumb in the CS231n notes puts a healthy ratio around 10−310^{-3}. A sustained 10−110^{-1} 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 rr. The lab computes with ϵ=0\epsilon=0 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 ηmax⁡\eta_{\max}-sized sign steps while v^\hat v is estimated from very few batches. Liu et al. analyze this as reducing adaptive-rate variance in early steps. Let ss be update index, WW warmup steps, and MM the plan end, with 0≤W<M0\le W<M and 0≤ηmin⁡≤ηmax⁡0\le\eta_{\min}\le\eta_{\max}:

η(s)={ηmax⁡ s/W,0≤s<W,ηmin⁡+12(ηmax⁡−ηmin⁡)[1+cos⁡(π s−WM−W)],W≤s≤M,ηmin⁡,s>M.\eta(s)=\begin{cases} \eta_{\max}\,s/W, & 0\le s<W,\\[2pt] \eta_{\min}+\tfrac12(\eta_{\max}-\eta_{\min})\left[1+\cos\left(\pi\,\dfrac{s-W}{M-W}\right)\right], & W\le s\le M,\\[2pt] \eta_{\min}, & s> M. \end{cases}

The branches meet: at s=Ws=W the cosine gives ηmax⁡\eta_{\max}, the limit of the ramp; at s=Ms=M it gives ηmin⁡\eta_{\min}, matching the third branch. If W=0W=0, the first branch does not exist and the schedule starts at ηmax⁡\eta_{\max}. The indexing convention matters at endpoints. The lab numbers updates s=1,…,Ms=1,\ldots,M: the first uses ηmax⁡/W\eta_{\max}/W rather than wasting a step at η(0)=0\eta(0)=0, and the last uses exactly ηmin⁡\eta_{\min}. A loop over s=0,…,M−1s=0,\ldots,M-1 with the same formula takes a zero-rate step and never reaches ηmin⁡\eta_{\min}. 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 ηmin⁡=0\eta_{\min}=0 and decay progress u=(s−W)/(M−W)∈[0,1]u=(s-W)/(M-W)\in[0,1], linear gives ηmax⁡(1−u)\eta_{\max}(1-u) and cosine gives ηmax⁡(1+cos⁡πu)/2\eta_{\max}(1+\cos\pi u)/2. They coincide at u=0u=0, u=1/2u=1/2, and u=1u=1. One quarter through decay, linear retains 3/43/4 of the peak rate and cosine (2+2)/4≈0.854(2+\sqrt2)/4\approx0.854; at three quarters, 1/41/4 versus (2−2)/4≈0.146(2-\sqrt2)/4\approx0.146. 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 513⋅512+256⋅512+4 (12⋅5122+13⋅512)+2⋅512=13004288513\cdot512+256\cdot512+4\,(12\cdot512^2+13\cdot512)+2\cdot512=13004288 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 6⋅10−46\cdot10^{-4} and decays by cosine to 6⋅10−56\cdot10^{-5}, with AdamW β=(0.9, 0.95)\beta=(0.9,\,0.95), 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 6⋅10−46\cdot10^{-4}. The rate probe uses 1024-token batches and shows 10−310^{-3} is already aggressive at that scale. At step 1000 validation is 2.164 with 3⋅10−43\cdot10^{-4} and 2.244 with 10−310^{-3}, 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. 6⋅10−46\cdot10^{-4} 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 3⋅10−43\cdot10^{-4} 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 e1.248≈3.48e^{1.248}\approx3.48 per token, or 1.248/(ln⁡2⋅1.978)≈0.911.248/(\ln2\cdot1.978)\approx0.91 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.

[ ]Pilot model, data, and loopLocal GPU
"""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()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The sanity cell chains the previous section’s tests. Initial loss uses V=50257V=50257 and dimension 64 on random IDs, with the project’s requested 0.1 tolerance against ln⁡V\ln V, and also uses our vocabulary and pilot model on real text. In both cases it additionally requires loss within 0.05 of ln⁡V+σ2/2\ln V+\sigma^2/2 using measured σ\sigma. 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.

[ ]Initial loss and overfitting one batchLocal GPU
sanity()
This cell needs the local lab (PyTorch with your GPU). Start it with 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 with peak rate 0.0003Local GPU
pilot(0.0003, 3000, 500, stop_after=1000)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Pilot with peak rate 0.001Local GPU
pilot(0.001, 3000, 500, stop_after=1000)
This cell needs the local lab (PyTorch with your GPU). Start it with 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.

[ ]Comparison with figure recordsLocal GPU
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}")
This cell needs the local lab (PyTorch with your GPU). Start it with 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.

[ ]Complete TinyStories pilotLocal GPU
pilot(0.0006, 12000, 500, profile=FULL)
This cell needs the local lab (PyTorch with your GPU). Start it with 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

NumericA reference for loss
If all 32000 logits are equal, what is cross-entropy in nats for any target token?
NumericA tolerance that does not hold
A GPT with dimension d = 768 and vocabulary V = 50257 ties its output head to the embedding matrix, initialized with N(0, 0.02²), and applies it to LayerNorm output with variance 1. Using the lesson's Gaussian approximation, what mean initial loss in nats do you expect?
QuizAn initial loss of 25
A GPT with V = 50257 has loss 25 at step 0, before any update. What is the most likely cause?
QuizA layer that changes quickly
With AdamW, a block's ratio ‖θ after − θ before‖ / ‖θ before‖ remains around 0.1 for hundreds of steps while the others are around 10⁻³. What does this indicate?
QuizDecay and tied weights
The token embedding matrix is tied to the output head. Which statement is correct?
CodeSchedule endpoints
Implement get_lr(step, warmup, max_steps, max_lr, min_lr) using the convention in the text: linear ramp max_lr · step / warmup for step < warmup, cosine from max_lr to min_lr between warmup and max_steps, and min_lr for step ≥ max_steps. With warmup = 0, start cosine directly. Raise ValueError if step < 0, if 0 ≤ warmup < max_steps does not hold, or if 0 ≤ min_lr ≤ max_lr does not hold.
import math

def get_lr(step, warmup, max_steps, max_lr, min_lr):
  pass
Shift+Enter to run

Summary

Key idea

Before long training, each component has a test ruling it out as a cause: initial loss against ln⁡V+σ2/2\ln V+\sigma^2/2, 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 η\eta in each coordinate, which is why warmup exists.