What you will build
blog-coding-tutorials/c05-pretrainingpretrain, a small and complete LLM pretraining system. It turns raw stories into token shards and trains a Llama-style decoder with AdamW, accumulation and bf16. It resumes to the same bits after a stop. It measures model FLOPs utilisation (MFU), runs real two-process distributed data parallel (DDP) training, and survives bad batches, NaNs and corrupt checkpoints.
- Theory first
- Time
- About 3 hours, plus the training run
- Hardware
- Any CPU for everything except the GPU-only paths, which are marked. Fully sharded data parallel (FSDP) on NCCL, NVIDIA’s GPU communication library, and DeepSpeed need GPUs.
- You need
- Python 3.10+, PyTorch 2.x, transformers, tokenizers, numpy, pytest. C4 helps but is optional.
- Package
pretrain
Final repo tree c05-pretraining/
c05-pretraining/ ├── README.md # every command, results table ├── conftest.py ├── configs/ │ ├── smoke.yaml # tiny, for tests and CPU experiments │ ├── tinystories.yaml # the main run │ ├── ddp_cpu.yaml # two processes with gloo │ └── deepspeed_zero3.json # GPU only ├── pretrain/ │ ├── config.py # ModelArgs, TrainConfig │ ├── corpus.py # step 2: download and split │ ├── tokenizer.py # step 3: GPT-2 and our own BPE │ ├── shards.py # step 4: EOS and uint16 files │ ├── packing.py # step 5: padding, packing, masks │ ├── loader.py # step 6: shuffling, resume, ranks │ ├── streaming.py # step 6: worker sharding │ ├── model.py # the model, and C4 behind a flag │ ├── optim.py # step 7: AdamW and two groups │ ├── schedule.py # step 8: warmup and cosine │ ├── step.py # steps 9 to 11: one optimiser step │ ├── activation_ckpt.py # step 12 │ ├── rng.py # step 13: every generator │ ├── checkpoint.py # step 13: atomic, with a checksum │ ├── metrics.py # step 15: JSONL logging │ ├── trainer.py # step 15: the loop │ ├── mfu.py # step 16 │ ├── distributed.py # step 17: DDP │ ├── fsdp.py # step 18 │ ├── zero.py # step 18 │ ├── guards.py # step 19 │ └── utils.py # device, seed, memory ├── scripts/ # one runnable script per experiment ├── benchmarks/ # packing, loader, precision, memory, MFU ├── results/ # saved outputs of the runs in this post └── tests/ # data, loader, training, systems
The plan
A training loop fits in ten lines. What does it take to stop that loop at any step, restart it on another day, and get the same numbers to the last bit?
The answer is most of a pretraining system. The ten-line loop has no epochs, no saved position, no schedule and no way to run on two machines. We write that loop first and run it. Then we fix what it lacks, one module at a time, and test each fix.
A few short forms appear below, and each is explained again where it first matters. BPE is byte-pair encoding, the way our tokenizer builds its vocabulary. EOS is the end-of-sequence token that closes a story. ZeRO is the Zero Redundancy Optimizer, which splits optimiser state across processes. MAD is the median absolute deviation, a spread that one outlier cannot move.
The order follows the data. Stories become tokens, tokens become windows, and windows become batches. Then come the optimiser, the step, the checkpoint and the loop. Last come the parts that only matter at scale: utilisation, several processes, and things going wrong.
Why each stage existsHow LLMs are pretrainedWe train the architecture from Build a Modern LLM From Scratch. By default this folder builds it with Hugging Face’s LlamaForCausalLM, so the folder runs on its own. C4 showed that the two give the same logits. A flag swaps in C4’s TinyLLM. The trainer only needs model(input_ids).logits.
Every output below comes from a saved file in results/, unless the text says it is a separate run. Each output block names the hardware that ran it. The GPU outputs are single runs on NVIDIA H100 80GB HBM3 GPUs, labelled as such, and they are kept apart from the CPU numbers. Where a run has not happened, the post says “not yet measured” and gives the command. Commands run from the repo root.
$ git clone https://github.com/srini-anirudh/blog-coding-tutorials.git
$ cd blog-coding-tutorials
$ python -m venv .venv && .venv/bin/pip install -e ".[dev]"
$ .venv/bin/python c05-pretraining/scripts/prepare_data.py
The last command downloads the data and builds what steps 1 to 6 explain. Here is that whole path on real tokens. Press Next to walk it, or read on and come back.
The simplest loop that learns
Goal Watch the loss fall with almost no code, then list exactly what this loop cannot do.
We start at the end state of C1 and C4: a model, a flat file of tokens and a loop. Each row of the batch starts at a random offset. There is no dataset class and no schedule.
L, B = 64, 8
tokens = np.memmap(resolve("data_cache/tinystories/train_000.bin"), dtype=np.uint16, mode="r")
model = build_model(ModelArgs(hidden_size=64, num_layers=2, num_heads=4, num_kv_heads=2,
intermediate_size=172, max_seq_len=L))
opt = torch.optim.AdamW(model.parameters(), lr=args.lr)
t0 = time.time()
for step in range(1, args.steps + 1):
# A random start per row. No epochs, no position to save, no sharding.
starts = torch.randint(0, len(tokens) - L - 1, (B,)).tolist()
chunk = torch.stack([torch.from_numpy(tokens[s : s + L + 1].astype(np.int64)) for s in starts])
x, y = chunk[:, :-1], chunk[:, 1:] # (B, L) each
logits = model(x).logits # (B, L, V)
loss = F.cross_entropy(logits.reshape(-1, logits.size(-1)), y.reshape(-1))
loss.backward()
opt.step()
opt.zero_grad()
if step == 1 or step % (args.steps // 5) == 0:
print(f"step {step:4d} loss {loss.item():.3f} {step * B * L / (time.time() - t0):,.0f} tok/s")y is x moved along by one token, so every position learns to predict the next token.The slice has L + 1 tokens because L inputs need L targets, and the last target sits one place past the last input. The model returns one score per vocabulary entry at every position. So logits is three-dimensional, and cross_entropy wants it flat.
| Tensor | Shape | Meaning |
|---|---|---|
| tokens | (n,) | The memory-mapped file of uint16 ids. Nothing is read until it is sliced. |
| chunk | (8, 65) | Eight slices of L + 1 tokens. |
| x, y | (8, 64) | Inputs and the same tokens moved along by one. |
| logits | (8, 64, 4096) | A score for every vocabulary entry at every position. |
| loss | () | The mean over 512 target tokens. |
$ .venv/bin/python c05-pretraining/scripts/naive_train.py --steps 200step 1 loss 8.319 1,762 tok/s
step 40 loss 6.317 18,292 tok/s
step 80 loss 5.779 20,378 tok/s
step 120 loss 5.492 21,301 tok/s
step 160 loss 5.135 21,691 tok/s
step 200 loss 4.965 21,471 tok/sThe first loss is the number to check. An untrained model is close to uniform over 4,096 tokens, and ln(4096) is 8.318. The first printed loss is 8.319. If your first loss is far from ln(V), stop and look for a bug before you train.
The loop learns. Now look at what it cannot do:
- It samples with replacement, so it has no epochs and it cannot say what it has seen.
- It has no position to save, so it cannot resume.
- Each row can start in the middle of a word and can run across two stories.
- The learning rate never changes, and a single bad gradient is applied in full.
- Two processes running this loop would train on overlapping data and drift apart.
The next 18 steps fix these, and each one adds a module and a check.
The raw corpus
Goal Turn one large text file into a clean list of whole documents.
The corpus is TinyStories, a set of short stories generated by larger language models so that small models have something simple to learn from. We use its V2 GPT-4 file. It is plain text, with the literal string <|endoftext|> between stories. The small vocabulary is why a 5.4M-parameter model can make visible progress in minutes.
The train file is 2.2 GB, and we only need part of it. So download asks for the first 128 MiB with an HTTP Range request. That creates a problem. The cut lands in the middle of a story.
def split_documents(text: str, drop_last_partial: bool = False) -> list[str]:
"""Split raw text into stripped, non-empty documents.
A Range download cuts the final story mid-sentence; drop_last_partial removes it
so no truncated document enters the corpus.
"""
parts = text.split(SEPARATOR)
if drop_last_partial and len(parts) > 1:
parts = parts[:-1]
return [p.strip() for p in parts if p.strip()]drop_last_partial removes that fragment, so no truncated document enters the corpus.$ .venv/bin/python c05-pretraining/scripts/prepare_data.pydocuments: train 163,746 val 27,630 (6.2s)
first document (730 chars): 'Once upon a time there was a little boy named Ben. Ben loved to explore the world around him. He saw many amazing things, like beautiful vases that were on disp'...
tokenizer bpe-4096: vocab 4,096, eos id 0 (16.3s)
compression on 2,000 val docs: 3.97 chars/token
train: 33,284,335 tokens in 5 shard(s); doc length mean 203, median 180, max 1876
val: 5,578,843 tokens in 1 shard(s); doc length mean 202, median 180, max 1176
wrote tinystories/ (52.1s)The 128 MiB slice holds 163,746 training documents and 33,284,335 tokens. That is far less than a real model trains on, and it is enough to show every mechanism here. Note the median document: 180 tokens, not far below the window length of 256. That fact drives the packing choice in step 5.
Use a tokenizer, then train a small one
Goal Compare an existing tokenizer with one trained on our corpus, and see what the choice costs in parameters.
We start with an existing tokenizer, GPT-2’s, loaded from the Hub. Then we train a byte-level BPE on our own stories. Both sit behind one small interface, so the rest of the code does not care which it gets.
def train_bpe(texts: Iterable[str], vocab_size: int = 4096) -> TextTokenizer:
"""Train a byte-level BPE tokenizer.
Byte-level means every string is encodable (no unknown token): the 256 byte values
are the base alphabet and BPE merges frequent pairs on top of them.
EOS is added first so it gets id 0 and is never split.
"""
tok = Tokenizer(models.BPE())
tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
tok.decoder = decoders.ByteLevel()
trainer = trainers.BpeTrainer(
vocab_size=vocab_size,
special_tokens=[EOS],
initial_alphabet=pre_tokenizers.ByteLevel.alphabet(),
show_progress=False,
)
tok.train_from_iterator(texts, trainer=trainer)
return TextTokenizer(tok, f"bpe-{vocab_size}")BPE starts from single bytes and repeatedly merges the most frequent adjacent pair into a new token. It stops when the vocabulary reaches 4,096 entries. Common words become one token. Rare words stay in pieces.
$ .venv/bin/python c05-pretraining/scripts/inspect_tokens.pybpe-4096: vocab 4,096, eos 0, 12 tokens
ids [429, 438, 259, 398, 401, 283, 259, 391, 498, 402, 544, 14]
pieces Once _upon _a _time _there _was _a _little _boy _named _Ben .
gpt2: vocab 50,257, eos 50256, 12 tokens
ids [7454, 2402, 257, 640, 612, 373, 257, 1310, 2933, 3706, 3932, 13]
pieces Once _upon _a _time _there _was _a _little _boy _named _Ben .The output shows the two tokenizers one after the other. On this simple sentence they make the same 12 pieces. Their ids differ, and so do their sizes. The difference shows up in the model.
embedding bpe-4096 4096 x 256 = 1.05M params, 19% of a 4.4M-block model
embedding gpt2 50257 x 256 = 12.87M params, 75% of a 4.4M-block modelThe embedding table has one row per token. With tied embeddings that same table is also the output layer. At 256 dimensions, the GPT-2 vocabulary would take 12.87M parameters, which is 75% of the model. Our 4,096-token vocabulary takes 1.05M, which is 19%. On a corpus of children’s stories, most of GPT-2’s entries would never earn their place.
Document boundaries and token shards
Goal Put an EOS after every document, and store the corpus as flat files a loader can slice.
Why not join the documents and tokenize the result? Two things go wrong. The tokenizer can merge across the join, and the model never sees a signal that a story has ended. We measure both.
blind concatenation versus an explicit boundary
joined The _dog _was _happy . Once _upon _a _time
separate + EOS The _dog _was _happy . <|endoftext|> Once _upon _a _time
joined, no stop They _played _in _the _su nd ay _was _hot
separate + EOS They _played _in _the _sun <|endoftext|> day _was _hot
2 of 1999 real neighbouring document pairs tokenize differently when joinedThe first pair ends in a full stop, and joining changes nothing except the missing boundary. The second pair is a document cut mid-sentence. Here the join creates a word that was never written: sun and day become the pieces _su nd ay.
The last line is the surprise. Only 2 of 1,999 real neighbouring pairs tokenize differently when joined, because complete stories end in punctuation.
The encoding step appends EOS to each document and stores it as uint16. Two bytes are enough for any vocabulary up to 65,536, and they halve the disk use compared with int32.
def tokenize_documents(
docs: list[str], tok: TextTokenizer, batch_size: int = 2048
) -> list[np.ndarray]:
"""Encode each document and append EOS. Returns one uint16 array per document."""
assert tok.vocab_size <= 2**16, "uint16 shards need vocab_size <= 65536"
out: list[np.ndarray] = []
for i in range(0, len(docs), batch_size):
for ids in tok.encode_batch(docs[i : i + batch_size]):
out.append(np.asarray(ids + [tok.eos_id], dtype=np.uint16))
return outclass TokenShards:
"""Read-only, memory-mapped view of one split's shards."""
def __init__(self, data_dir: str | Path, split: str):
self.dir = Path(data_dir)
self.meta = json.loads((self.dir / "meta.json").read_text())
self.eos_id: int = self.meta["eos_id"]
self.vocab_size: int = self.meta["vocab_size"]
self.shards = [
np.memmap(self.dir / s["file"], dtype=np.uint16, mode="r")
for s in self.meta[split]["shards"]
]
@property
def num_tokens(self) -> int:
return sum(len(s) for s in self.shards)
def doc_lens(self, split: str) -> np.ndarray:
return np.load(self.dir / f"{split}_doc_lens.npy")| File | Shape and type | Meaning |
|---|---|---|
| train_000.bin to train_004.bin | (n,) uint16 | Token ids, documents back to back. Each shard ends on a document boundary. |
| train_doc_lens.npy | (163746,) int32 | Length of each document, including its EOS. |
| meta.json | text | Tokenizer name, EOS id, vocabulary size, and tokens per shard. |
train: 33,284,335 tokens, 5 shards, 130,015 windows of L=256
window 0: x (256,) torch.int64 y (256,) torch.int64
x[:8] [429, 438, 259, 398, 401, 283, 259, 391]
y[:8] [438, 259, 398, 401, 283, 259, 391, 498] (x shifted by one)
first EOS at position 176: x[174:179] [1118, 1, 0, 429, 438]
document ids [0, 0, 0, 1, 1]
positions [174, 175, 176, 0, 1]
documents touching window 0: 2The first EOS sits at position 176, so the first story has 177 tokens. Position 177 starts the next story. Already the first window holds parts of two documents. Step 5 asks whether that is acceptable.
Padding or packing
Goal Build fixed-length sequences both ways, then measure how much of each batch is real data.
The model wants a rectangle. Documents are not rectangles. There are two simple ways to get one.
Padding puts one document in each row. Long documents are cut at L. Short ones are filled with a padding token, which the loss must skip. Packing joins everything into one stream and cuts it every L tokens.
def pad_batch(docs: list[list[int]], seq_len: int, pad_id: int) -> tuple[torch.Tensor, torch.Tensor]:
"""One document per row, truncated or right-padded to seq_len.
Returns input_ids (B, L) and attention_mask (B, L) with 1 for real tokens.
"""
ids = torch.full((len(docs), seq_len), pad_id, dtype=torch.long)
mask = torch.zeros((len(docs), seq_len), dtype=torch.long)
for i, d in enumerate(docs):
d = d[:seq_len]
ids[i, : len(d)] = torch.tensor(d)
mask[i, : len(d)] = 1
return ids, maskdef pack_stream(docs: list[list[int]], seq_len: int) -> torch.Tensor:
"""Concatenate documents (each already ends in EOS) and cut windows of seq_len + 1.
Consecutive windows overlap by one token: window k holds tokens
[k*L, k*L + L + 1), so its input is the first L and its targets are the last L.
Returns (num_windows, L + 1). The tail that does not fill a window is dropped.
"""
stream = torch.tensor([t for d in docs for t in d], dtype=torch.long)
n = (len(stream) - 1) // seq_len
idx = torch.arange(n)[:, None] * seq_len + torch.arange(seq_len + 1)[None, :]
return stream[idx]k * L, so neighbouring windows share one token.Here are both on three tiny documents, where 0 is EOS and 99 is the padding token. This is a short run of ours, not a saved result, and you can paste it into a Python shell from inside the folder.
$ python -c "
from pretrain.packing import pad_batch, pack_stream
docs = [[5, 6, 7, 0], [8, 9, 0], [1, 2, 3, 4, 5, 6, 0]]
print(pad_batch(docs, seq_len=5, pad_id=99))
print(pack_stream(docs, seq_len=4))"
pad ids [[5, 6, 7, 0, 99], [8, 9, 0, 99, 99], [1, 2, 3, 4, 5]]
pad mask [[1, 1, 1, 1, 0], [1, 1, 1, 0, 0], [1, 1, 1, 1, 1]]
pack torch.Size([3, 5])
[[5, 6, 7, 0, 8], [8, 9, 0, 1, 2], [2, 3, 4, 5, 6]]
Padding lost the 6 and the 0 of the third document, and the second row is 40% filler. Packing kept every token, and windows of L + 1 overlap by one. The overlap is what gives each window its full set of targets. But the first window now runs from one document into the next.
Try the two strategies on 40 real document lengths from our corpus. Move L and watch the filler and the cuts trade places.
Now the same measurement on all 163,746 documents. This benchmark works from document lengths alone, so it builds no tensors and the numbers do not depend on the hardware.
$ .venv/bin/python c05-pretraining/benchmarks/bench_packing.py163,746 documents, 33,284,335 tokens, length p10 138 median 180 p90 279 max 1876
L strategy utilisation tokens cut multi-doc windows split docs
128 pad to L 99.6% 37.3% - -
128 pad to batch max (B=32) 99.6% 37.3% - -
128 greedy packing 100.0% 0.0% 62.7% 99.6%
128 best-fit packing 100.0% 0.0% - 95.1%
256 pad to L 73.0% 8.1% - -
256 pad to batch max (B=32) 73.0% 8.1% - -
256 greedy packing 100.0% 0.0% 91.9% 72.7%
256 best-fit packing 78.6% 0.0% - 12.7%
512 pad to L 39.3% 1.1% - -
512 pad to batch max (B=32) 44.3% 1.1% - -
512 greedy packing 100.0% 0.0% 98.9% 39.1%
512 best-fit packing 95.1% 0.0% - 1.9%Utilisation is the share of the rectangle that holds real tokens. Tokens cut is the share of the corpus that never reaches the model. Multi-doc windows are windows with a document boundary inside. Split docs are documents that do not fit whole in one window.
We use greedy packing because the loader becomes simple: window i is a fixed slice. The price is that 91.9% of windows at L = 256 contain a boundary, and attention can read across it. packing.py has the tools to stop that.
def document_ids(window: torch.Tensor, eos_id: int) -> torch.Tensor:
"""Which document each position of a packed window belongs to. (L,) -> (L,).
The EOS token closes its document, so the id increments on the token after it.
"""
is_eos = (window == eos_id).long()
return torch.cumsum(is_eos, 0) - is_eos
def position_ids(window: torch.Tensor, eos_id: int) -> torch.Tensor:
"""Positions that restart at 0 at every document start inside a packed window."""
doc = document_ids(window, eos_id)
starts = torch.ones_like(doc)
starts[1:] = (doc[1:] != doc[:-1]).long()
first = torch.cummax(torch.where(starts.bool(), torch.arange(len(doc)), 0), 0).values
return torch.arange(len(doc)) - first
def block_causal_mask(doc: torch.Tensor) -> torch.Tensor:
"""(L,) document ids -> (L, L) bool mask. True where query i may attend to key j:
j <= i and both tokens are in the same document."""
L = doc.numel()
causal = torch.ones(L, L, dtype=torch.bool).tril()
return causal & (doc[:, None] == doc[None, :])document_ids [0, 0, 0, 1, 1, 1, 2]
position_ids [0, 1, 2, 0, 1, 2, 0]
block_causal_mask
[1, 0, 0, 0, 0, 0, 0]
[1, 1, 0, 0, 0, 0, 0]
[1, 1, 1, 0, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 0]
[0, 0, 0, 1, 1, 0, 0]
[0, 0, 0, 1, 1, 1, 0]
[0, 0, 0, 0, 0, 0, 1]
A loader that can say where it is
Goal Shuffle, share out data across ranks and workers, prefetch, and save the exact data position in three numbers.
The naive loop sampled at random. That gave it nothing to save. We replace it with three small pieces. The first gives each window a fixed address.
class PackedWindows(Dataset):
"""Window i -> (input_ids, targets), both (L,) int64, targets shifted by one.
Windows never cross a shard file. Each shard of n tokens gives (n - 1) // L windows.
"""
def __init__(self, shards: TokenShards, seq_len: int):
self.shards = shards.shards
self.seq_len = seq_len
counts = [(len(s) - 1) // seq_len for s in self.shards]
self.offsets = np.cumsum([0] + counts) # first global window index of each shard
def __len__(self) -> int:
return int(self.offsets[-1])
def __getitem__(self, i: int) -> tuple[torch.Tensor, torch.Tensor]:
s = int(np.searchsorted(self.offsets, i, side="right") - 1)
start = (i - self.offsets[s]) * self.seq_len
chunk = torch.from_numpy(self.shards[s][start : start + self.seq_len + 1].astype(np.int64))
return chunk[:-1], chunk[1:]The second decides the order. It builds one permutation from seed + epoch, and the order depends on nothing else.
class EpochSampler(Sampler[int]):
"""Shuffled indices for one (epoch, rank), starting after `skip` samples.
Every rank builds the same permutation from (seed, epoch) and takes every
world_size-th entry, so ranks see disjoint windows without talking to each other.
"""
def __init__(self, n: int, seed: int, epoch: int, rank: int = 0, world_size: int = 1, skip: int = 0):
g = torch.Generator().manual_seed(seed + epoch)
perm = torch.randperm(n, generator=g)
perm = perm[: n - n % world_size] # equal share per rank
self.indices = perm[rank::world_size][skip:].tolist()
def __iter__(self):
return iter(self.indices)
def __len__(self) -> int:
return len(self.indices)world_size-th entry. The ranks get different windows without any communication.Here is the real output for 12 windows and two ranks. This is a short run of ours, and skip=2 is what a resume after two samples would do.
EpochSampler(12, seed=1337, epoch=0, rank=0, world_size=2) [7, 4, 11, 2, 3, 1]
EpochSampler(12, seed=1337, epoch=0, rank=1, world_size=2) [5, 10, 8, 0, 6, 9]
EpochSampler(12, seed=1337, epoch=0, rank=0, world_size=2, skip=2) [11, 2, 3, 1]
EpochSampler(12, seed=1337, epoch=1) [8, 9, 4, 3, 1, 2, 7, 10, 5, 0, 6, 11]
The third piece counts. The important detail is where it counts.
def __next__(self) -> tuple[torch.Tensor, torch.Tensor]:
if self._it is None:
self._start_epoch()
try:
batch = next(self._it)
except StopIteration:
self.epoch, self.consumed = self.epoch + 1, 0
self._start_epoch()
batch = next(self._it)
# Count in the main process, when the batch reaches the training loop. Batches
# that workers prefetched but we never used are not counted, so they are not lost.
self.consumed += 1
return batch def state_dict(self) -> dict:
return {"seed": self.seed, "epoch": self.epoch, "consumed": self.consumed,
"rank": self.rank, "world_size": self.world_size}| Tensor | Shape and type | Meaning |
|---|---|---|
| shard slice | (257,) uint16 | L + 1 tokens, read from the memory map. |
| chunk | (257,) int64 | Cast up, because nn.Embedding needs a long tensor. |
| x, y from the dataset | (256,) int64 | One sample: inputs and targets. |
| x, y from the loader | (16, 256) int64 | One micro-batch. |
The loader passes num_workers, prefetch_factor and pin_memory to PyTorch’s DataLoader. Workers prepare batches in other processes while the model is busy. Prefetch sets how many batches each worker keeps ready. Pinned memory lets a batch reach a GPU without an extra copy, so the trainer turns it on only for CUDA.
$ .venv/bin/python c05-pretraining/benchmarks/bench_loader.py130,015 windows, batch 32
workers first batch ms batches/s tokens/s
0 15.5 1910 15,644,537
2 87.1 718 5,878,219
4 69.6 1161 9,506,953Workers made it slower here. With none, the loader delivers 1,910 batches per second. Two workers give 718, and four give 1,161. A memory-mapped slice is cheap to read, so the likely cost is sending finished batches between processes, which is more than the work the workers take over. We did not profile this further.
A map-style dataset gets its worker split for free, because the sampler hands out indices. A stream does not. Every worker runs the same __iter__, so without a split each of N workers yields the whole stream.
def __iter__(self):
info = get_worker_info()
worker, num_workers = (info.id, info.num_workers) if info else (0, 1)
# One global stream id per (rank, worker) pair.
stream = self.rank * num_workers + worker
num_streams = self.world_size * num_workers
k = 0
L = self.seq_len
for shard in self.shards:
for w in range((len(shard) - 1) // L):
if k % num_streams == stream:
chunk = torch.from_numpy(shard[w * L : w * L + L + 1].astype(np.int64))
yield chunk[:-1], chunk[1:]
k += 1AdamW and its parameter groups
Goal Configure each number of the optimiser on purpose, and keep weight decay away from the parameters it would harm.
The derivation lives in the theory post. Here we set five numbers and decide which parameters get decay.
Derivation inWhat an optimizer actually does| Setting | Value | What it does here |
|---|---|---|
| lr | 2e-3 peak | Set in tinystories.yaml. It scales every step, and step 8 changes it over time. |
| beta1 | 0.9 | Averaging for the first moment, the running gradient. |
| beta2 | 0.95 | Averaging for the second moment. This is lower than the common 0.999, so the estimate follows recent gradients faster. |
| eps | 1e-8 | Keeps the denominator away from zero. |
| weight_decay | 0.1 | Pulls the weights in the decay group toward zero, separately from the gradient. |
def param_groups(model: nn.Module, weight_decay: float) -> list[dict]:
decay, no_decay = [], []
for name, p in model.named_parameters(): # tied weights appear once here
if not p.requires_grad:
continue
(decay if p.dim() >= 2 else no_decay).append(p)
return [
{"params": decay, "weight_decay": weight_decay, "name": "decay"},
{"params": no_decay, "weight_decay": 0.0, "name": "no_decay"},
]def build_optimizer(model: nn.Module, cfg: TrainConfig, device: torch.device) -> torch.optim.AdamW:
groups = param_groups(model, cfg.weight_decay)
return torch.optim.AdamW(
groups,
lr=cfg.lr,
betas=(cfg.beta1, cfg.beta2),
eps=cfg.eps,
# One fused kernel for all parameters instead of a loop of small ones.
fused=device.type in ("cuda", "mps"),
)RMSNorm gains have a natural value of 1. Decay would pull them toward 0, which fights their purpose. So how many parameters does this rule touch? We ran it on the main model.
params 5,401,856
decay 43 tensors 5,398,528 params weight_decay 0.1
no_decay 13 tensors 3,328 params weight_decay 0.0
The 13 vectors are two gains per block across 6 blocks, plus one final norm. They hold 0.06% of the parameters. We have not measured what happens if they do decay on this small run, so we make no claim about its size. The rule is standard, and exercise 5 asks you to measure it.
AdamW keeps state for each weight. After one step, the optimiser holds this for the embedding matrix.
| State | Shape | Meaning |
|---|---|---|
| step | () | Number of updates, used for bias correction. |
| exp_avg | (4096, 256) | First moment. One number per weight. |
| exp_avg_sq | (4096, 256) | Second moment. One more number per weight. |
So the optimiser holds twice the model, and that fact returns twice. In step 13 it is why a resume-ready checkpoint is three times the size of the weights. In step 18 it is what ZeRO removes first.
Warmup, cosine decay and a floor
Goal Write the schedule as one small function, plot it, and match it against the Transformers version.
At the start the second moment has seen almost nothing, and steps can be large. Warmup raises the learning rate slowly while that estimate settles. After the peak, cosine decay lowers it smoothly. A floor keeps some learning going at the end.
def lr_multiplier(step: int, warmup: int, total: int, min_ratio: float) -> float:
"""Multiplier on the peak LR at optimiser step `step` (0-based)."""
if step < warmup:
return (step + 1) / warmup
if step >= total:
return min_ratio
progress = (step - warmup) / max(1, total - warmup)
return min_ratio + (1 - min_ratio) * 0.5 * (1 + math.cos(math.pi * progress))step + 1 means the first step already has a usable learning rate.def build_scheduler(
opt: torch.optim.Optimizer, warmup: int, total: int, peak_lr: float, min_lr: float
) -> torch.optim.lr_scheduler.LambdaLR:
ratio = min_lr / peak_lr
return torch.optim.lr_scheduler.LambdaLR(opt, lambda s: lr_multiplier(s, warmup, total, ratio))LambdaLR, so its position is part of the scheduler’s state_dict and returns with the checkpoint.$ .venv/bin/python c05-pretraining/scripts/plot_schedule.pystep 0 lr 5.000e-05
step 1 lr 1.000e-04
step 20 lr 1.050e-03
step 39 lr 2.000e-03
step 40 lr 2.000e-03
step 400 lr 1.174e-03
step 799 lr 2.000e-04Change the shape yourself. The default values are the main run. The output above is the same curve at seven points.
lr_multiplier. With warmup 40, 800 steps and a 10% floor, step 400 gives 1.174e-3, which matches the saved output.Gradient accumulation that is really equal
Goal Split one large batch into micro-batches, get the same gradient, and catch the common bug.
One optimiser step can see more sequences than fit in memory at once. We run several forward and backward passes, let the gradients add up, and then step once. The size that matters to the optimiser is the global batch:
B_global = B_micro × N_accum × N_GPU
The main run has 16 × 2 × 1, which is 32 sequences, or 8,192 tokens per step. The question is what to divide by. A mean loss over a big batch weights every target token the same. To get the same gradient, each micro-batch must add its sum of per-token losses, divided by the token count of the whole step.
def lm_loss_sum(logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
"""logits (B, L, V), targets (B, L) -> summed cross-entropy over non-ignored targets.
Logits are upcast to fp32 first: softmax over V entries in bf16 loses precision.
"""
return F.cross_entropy(
logits.float().reshape(-1, logits.size(-1)), targets.reshape(-1),
ignore_index=IGNORE, reduction="sum",
)def train_step(
model: nn.Module,
opt: torch.optim.Optimizer,
sched: torch.optim.lr_scheduler.LRScheduler | None,
micro_batches: list[tuple[torch.Tensor, torch.Tensor]],
device: torch.device,
precision: str = "bf16",
grad_clip: float = 1.0,
) -> StepResult:
"""Run len(micro_batches) forward/backward passes and one optimiser step."""
n_tokens = sum(int((y != IGNORE).sum()) for _, y in micro_batches)
loss_total = 0.0
for i, (x, y) in enumerate(micro_batches):
x, y = x.to(device, non_blocking=True), y.to(device, non_blocking=True)
last = i == len(micro_batches) - 1
# Under DDP, skip the gradient all-reduce on every micro-batch but the last.
sync = contextlib.nullcontext() if last or not hasattr(model, "no_sync") else model.no_sync()
with sync:
with autocast(device, precision):
logits = model(x).logits # (B, L, V)
loss_sum = lm_loss_sum(logits, y)
(loss_sum / n_tokens).backward()
loss_total += loss_sum.item()
# clip_grad_norm_ returns the norm *before* clipping: the number worth logging.
grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip).item()
skipped = not torch.isfinite(torch.tensor(grad_norm))
if not skipped:
opt.step()
opt.zero_grad(set_to_none=True)
if sched is not None:
sched.step() # advance even on a skipped step, so the schedule stays aligned with step
return StepResult(loss_total / n_tokens, grad_norm, n_tokens, skipped)| Tensor | Shape | Meaning |
|---|---|---|
| x, y | (16, 256) | Inputs and targets. |
| logits | (16, 256, 4096) | Scores at every position, about 16.8M numbers. |
| flat logits | (4096, 4096) | 16 × 256 = 4,096 positions by 4,096 tokens. The two numbers are equal by coincidence. |
| flat targets | (4096,) | One target per position. |
| loss_sum | () | The sum over non-ignored targets. |
A common version averages each micro-batch’s mean loss. We call it mean of means. It looks right, and on our packed data it is right. So we test both, on real tokens, against one big batch.
$ .venv/bin/python c05-pretraining/scripts/check_accumulation.pypacked data, every micro-batch has the same number of targets
token-weighted accumulation max |diff| 3.73e-09
mean of means max |diff| 3.73e-09
unequal targets per micro-batch (112 of 512 ignored)
token-weighted accumulation max |diff| 3.73e-09
mean of means max |diff| 8.25e-03The first group uses packed data. Both methods agree with the big batch to float32 noise. In the second group, one micro-batch keeps only 16 of its 128 targets, as padding would cause. Our method stays at 3.73e-09, and mean of means moves to 8.25e-03. That is more than a million times larger. Figure 4 shows why.
check_accumulation.py: 8 sequences of 64 tokens in 4 micro-batches, with 112 targets ignored in the first.bf16 training compared with fp32
Goal Run the forward pass in bf16 with autocast, and measure what changes against fp32.
bf16 has the same exponent range as fp32 and far fewer mantissa bits. It rarely needs a loss scaler, and matmuls on it are faster on hardware that supports it. Autocast runs chosen operations in bf16 while the weights stay fp32.
The memory ledger and four precisions inInside a training stepdef autocast(device: torch.device, precision: str):
if precision == "fp32":
return contextlib.nullcontext()
return torch.autocast(device_type=device.type, dtype=torch.bfloat16)Look back at lm_loss_sum in step 9. It calls logits.float() before the cross-entropy. A softmax over 4,096 entries in bf16 has only about three decimal digits of precision to work with, and the loss is the number we most want to trust. So the loss is computed in fp32.
| Tensor | Type | Why |
|---|---|---|
| Weights | fp32 | Small updates would vanish if stored in bf16. |
| Activations in forward | bf16 | This is where the speed and memory gains are. |
| Logits at the loss | fp32 | Cast up by lm_loss_sum. |
| Gradients | fp32 | They have the type of the weights. |
The benchmark starts both runs from the same weights and the same batches, so any difference in loss comes from numerics alone.
$ .venv/bin/python c05-pretraining/benchmarks/bench_precision.py --config c05-pretraining/configs/smoke.yaml --device cpu --steps 30device cpu, 1,024 tokens/step, 30 steps (first 3 dropped as warmup)
precision median step ms tokens/s final loss
fp32 41.9 24,447 5.9233
bf16 460.8 2,222 5.9239
max |loss_fp32 - loss_bf16| over the run: 0.0010The numerics hold up. After 30 steps the final losses are 5.9233 and 5.9239, and the largest gap anywhere in the run is 0.0010. The speed is the surprise. On this CPU, bf16 takes 460.8 ms per step against 41.9 ms for fp32, so it is about 11 times slower.
Here is the same benchmark on one NVIDIA H100, with the main config and 8,192 tokens per step.
$ .venv/bin/python c05-pretraining/benchmarks/bench_precision.py --device cuda --steps 30device cuda, 8,192 tokens/step, 30 steps (first 3 dropped as warmup)
precision median step ms tokens/s final loss
fp32 45.8 178,750 5.6707
bf16 60.5 135,372 5.6676
max |loss_fp32 - loss_bf16| over the run: 0.0079On the H100, bf16 is slower than fp32 too: 60.5 ms against 45.8 ms per step. The loss gap is 0.0079, larger than on the CPU run. This model is far too small for the GPU. Each step is a few short kernels, so the time is probably spent launching them, and the cheaper bf16 matmuls save little. A larger model would keep the GPU busy, and we expect the usual gain there. That has not been measured.
Clip the gradient and record its norm
Goal Limit the size of a bad step, and turn the gradient norm into a number we can watch.
Clipping scales the whole gradient down when its total length is above a limit. Its direction does not change. So it limits the damage from one bad batch while leaving normal steps alone.
Why it works inWhy transformers do not explode # clip_grad_norm_ returns the norm *before* clipping: the number worth logging.
grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip).item()
skipped = not torch.isfinite(torch.tensor(grad_norm))
if not skipped:
opt.step()
opt.zero_grad(set_to_none=True)
if sched is not None:
sched.step() # advance even on a skipped step, so the schedule stays aligned with step
return StepResult(loss_total / n_tokens, grad_norm, n_tokens, skipped)train_step. clip_grad_norm_ returns the norm before clipping, which is the useful number to log. A non-finite norm skips the update.The norm that goes in the log is ‖∇θ L‖ before clipping. On the main run it starts at 2.83 and falls to 0.92 by step 20. After that, only one logged value goes above the limit of 1.0: 1.30 at step 140. So clipping matters early and then mostly does nothing. You can scrub through it in Figure 7.
The scheduler still advances on a skipped step. If it did not, the learning rate and step would no longer agree.
Activation checkpointing
Goal Trade compute for memory, and measure both sides of the trade.
The name is close to “checkpoint”, and the idea is unrelated to saving a file. Backward needs the intermediate tensors of forward, so autograd keeps them alive. For a deep model that memory is large. We can drop them and recompute them when backward arrives.
class CheckpointWrapper(nn.Module):
def __init__(self, block: nn.Module):
super().__init__()
self.block = block
def forward(self, *args, **kwargs):
if not torch.is_grad_enabled():
return self.block(*args, **kwargs)
# use_reentrant=False: the supported mode. It handles keyword arguments and
# inputs that do not require grad, and it nests with other autograd hooks.
return checkpoint(self.block, *args, use_reentrant=False, **kwargs)no_grad nothing needs to be saved, so the wrapper steps aside.def saved_tensor_bytes(fn) -> int:
"""Bytes of tensors autograd saves for backward while running fn().
Uses saved_tensors_hooks: every tensor autograd stores passes through `pack`.
Storages are de-duplicated, because several saved tensors can share memory.
"""
seen: dict[int, int] = {}
def pack(t: torch.Tensor):
s = t.untyped_storage()
seen[s.data_ptr()] = s.nbytes()
return t
with torch.autograd.graph.saved_tensors_hooks(pack, lambda t: t):
fn()
return sum(seen.values())pack. Storages are counted once, because saved tensors can share memory.$ .venv/bin/python c05-pretraining/benchmarks/bench_checkpointing.py --device cpu --steps 6model llama, device cpu, batch (16, 256), 6 layers, fp32, one fresh process per mode
mode autograd saved peak growth step ms
plain 571.7 MiB 749.7 MiB 604
checkpointed 104.1 MiB 528.2 MiB 665
autograd saved 0.18x, peak growth 0.70x, step time 1.10xThe saved tensors fall from 571.7 MiB to 104.1 MiB, which is 0.18 times. The step takes 1.10 times as long. The theory says about one extra forward pass, and forward is only part of a step, so a small rise is what we should expect.
Now the same benchmark on C4’s TinyLLM, which has the same architecture and the same parameter count.
$ .venv/bin/python c05-pretraining/benchmarks/bench_checkpointing.py --device cpu --steps 6 --model tinyllmmodel tinyllm, device cpu, batch (16, 256), 6 layers, fp32, one fresh process per mode
mode autograd saved peak growth step ms
plain 572.6 MiB 768.5 MiB 622
checkpointed 105.1 MiB 370.2 MiB 793
autograd saved 0.18x, peak growth 0.48x, step time 1.28xThe same benchmark on one NVIDIA H100, with the Llama model:
$ .venv/bin/python c05-pretraining/benchmarks/bench_checkpointing.py --device cudamodel llama, device cuda, batch (16, 256), 6 layers, fp32, one fresh process per mode
mode autograd saved peak growth step ms
plain 571.7 MiB 620.0 MiB 22
checkpointed 104.1 MiB 188.1 MiB 38
autograd saved 0.18x, peak growth 0.30x, step time 1.71xSaved tensors fall by the same 0.18 times. Peak growth falls to 0.30 times, a better result than on the CPU. The step takes 1.71 times as long, more than the 1.10 times on the CPU. On this small model the recompute is not hidden by anything.
Checkpoints that hold the whole run
Goal Save everything a run depends on, write it safely, and detect a damaged file.
A checkpoint with only weights restarts training. To resume it we need every piece of state that affects the next step. There are more than you might expect.
| Key | Contents | If you leave it out |
|---|---|---|
| model | Weights, 5.4M numbers | Nothing to resume. |
| optimizer | Both moments and step counts, 10.8M numbers | Adam restarts with empty moments, and early steps are too large. |
| scheduler | Position on the LR curve | The LR goes back to warmup. |
| step | Optimiser steps taken | Logging and stopping both go wrong. |
| rng | Python, NumPy, torch CPU, and the accelerator | Dropout and sampling differ from the original run. |
| data | Seed, epoch, batches consumed | The run replays batches it has already seen. |
| config | The whole run definition | A resume can silently change the run. |
| extra | Loop state, such as the spike detector | Its statistics restart. |
def save_checkpoint(out_dir: str | Path, step: int, model, opt, sched, loader, config: dict,
extra: dict | None = None, keep: int = 2) -> Path:
out_dir = Path(out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
state = {
"model": model.state_dict(),
"optimizer": opt.state_dict(),
"scheduler": sched.state_dict(),
"step": step,
"rng": rng_state(),
"data": loader.state_dict(),
"config": config,
"extra": extra or {},
}
path = out_dir / f"ckpt_{step:06d}.pt"
tmp = path.with_suffix(".tmp")
torch.save(state, tmp)
with open(tmp, "rb") as f:
os.fsync(f.fileno()) # the bytes are on disk before we publish the name
# rename is atomic: readers see the old file set or the new one, never half a file.
os.replace(tmp, path)
manifest = {"file": path.name, "step": step, "sha256": sha256(path), "bytes": path.stat().st_size}
path.with_suffix(".json").write_text(json.dumps(manifest))
for old in sorted(out_dir.glob("ckpt_*.pt"))[:-keep]:
old.unlink()
old.with_suffix(".json").unlink(missing_ok=True)
return pathdef latest_valid_checkpoint(out_dir: str | Path) -> Path | None:
"""Newest checkpoint that passes its checksum. Corrupt ones are reported and skipped."""
for path in sorted(Path(out_dir).glob("ckpt_*.pt"), reverse=True):
if verify(path):
return path
print(f"[checkpoint] {path.name} failed verification, trying an older one")
return Nonedef rng_state() -> dict:
kind, keys, pos, has_gauss, gauss = np.random.get_state()
state = {
"python": random.getstate(),
# Stored as a tensor so the checkpoint loads with torch.load(weights_only=True).
"numpy": (kind, torch.from_numpy(keys.astype(np.int64)), pos, has_gauss, gauss),
"torch_cpu": torch.get_rng_state(),
}
if torch.cuda.is_available():
state["cuda"] = torch.cuda.get_rng_state_all()
if torch.backends.mps.is_available():
state["mps"] = torch.mps.get_rng_state()
return stateweights_only=True.The final checkpoint of the main run is 61.9 MiB on disk. The weights alone are 5,401,856 × 4 bytes, which is 20.6 MiB. Three times that is 61.8 MiB, so the two Adam moments really do make the file three times the size of the model.
$ cat c05-pretraining/results/checkpoint_size.txttinystories ckpt_000800.pt 61.9 MiB
tinyllm ckpt_000800.pt 61.9 MiBThe restore mirrors this, with one safety check in the trainer. If the config in the checkpoint differs from the config of this run, the trainer refuses to continue.
ckpt = latest_valid_checkpoint(out_dir) if resume else None
if ckpt is not None:
state = load_checkpoint(ckpt, model, opt, sched, loader, device)
assert state["config"] == cfg.to_dict(), "config changed since the checkpoint was written"
step = state["step"]
spikes.load_state_dict(state["extra"]["spikes"])
print(f"[resume] {ckpt.name}: step {step}, data epoch {loader.epoch} batch {loader.consumed}")Prove that a resume is exact
Goal Compare an uninterrupted run with one stopped and restarted, down to the last bit.
We run the same config three ways on real data. Straight runs 40 steps. Resumed stops at step 20, builds a new model, optimiser and loader from the checkpoint, and continues. Weights only is the usual mistake: it reloads the weights and restarts everything else.
straight = losses(train(base, resume=False))
base.out_dir = "runs/resume/split"
resumed = losses(train(base, resume=False, stop_after=half))
resumed |= losses(train(base, resume=True))
# The usual mistake: reload the weights and start everything else fresh.
base.out_dir = "runs/resume/weights_only"
wrong = losses(train(base, resume=False, stop_after=half))
ckpt = next(root.glob("weights_only/ckpt_*.pt"))
state = torch.load(ckpt, weights_only=True)
keep = {"model": state["model"], "config": state["config"]}
fresh = TrainConfig.from_dict(state["config"])
fresh.out_dir = "runs/resume/weights_only_2"
wrong |= {half + k: v for k, v in losses(_train_from_weights(fresh, keep["model"], half)).items()}train call on the highlighted line has nothing in memory from the first.$ .venv/bin/python c05-pretraining/scripts/resume_test.py --steps 40model llama, device cpu, 40 steps, interrupted at step 20
step straight resumed weights only
19 6.256866 6.256866 6.256866
20 6.182747 6.182747 6.182747
21 6.138329 6.138329 5.995322
22 6.163684 6.163684 5.976992
23 6.238420 6.238420 5.957311
25 6.162146 6.162146 5.968109
30 5.994190 5.994190 5.699095
40 6.125680 6.125680 5.748873
bitwise equal: True (max |straight - resumed| = 0.00e+00)The resumed column equals the straight column at every step, and the largest gap is exactly 0. That is the claim we set out to prove in the plan. results/resume_test_tinyllm.txt shows the same result on C4’s model.
results/resume.json, step by step. Resumed sits exactly on straight. Weights only leaves at step 21.The training loop and its logs
Goal Connect every module into one loop, log what we need to debug it, and run it.
The loop is now short, because each hard part lives in its own module.
while step < cfg.max_steps:
micro = [next(loader) for _ in range(cfg.grad_accum_steps)]
for x, y in micro:
check_batch(x, y, cfg.model.vocab_size)
lr = sched.get_last_lr()[0] # the LR this step uses
res, n_micro = step_with_oom_retry(
lambda mb: train_step(ddp_model, opt, sched, mb, device, cfg.precision, cfg.grad_clip),
micro, opt, lambda: empty_cache(device))
nonfinite.update(res.skipped) # raises TrainingDiverged after `patience` in a row
spike = spikes.update(res.loss)
step += 1
steps_this_call += 1
tokens_since += res.tokens
steps_since += 1Every log line is one JSON record, appended to a file. Append-only logs survive a crash, and after a resume the file continues.
class MetricsLogger:
def __init__(self, out_dir: str | Path, rank: int = 0, filename: str = "metrics.jsonl"):
self.rank = rank
self.path = Path(out_dir) / filename
if rank == 0:
self.path.parent.mkdir(parents=True, exist_ok=True)
self.t0 = time.time()
def log(self, record: dict, echo: bool = True) -> None:
if self.rank != 0:
return
record = {"time": round(time.time() - self.t0, 2), **record}
with open(self.path, "a") as f:
f.write(json.dumps(record) + "\n")
if echo:
print(" ".join(_fmt(k, v) for k, v in record.items()), flush=True)| Field | What it tells you |
|---|---|
| loss, val_loss | Training and validation loss in nats per token. Validation uses the same fixed windows each time. |
| lr | The learning rate this step used. |
| grad_norm | The norm before clipping. |
| param_norm | The size of the weights. Weight decay and the LR shape it. |
| tok_s, step_ms | Throughput, with evaluation and checkpoint time left out. |
| mem_mb | Allocated tensor memory on a GPU. Resident memory of the whole process on a CPU. |
$ .venv/bin/python c05-pretraining/scripts/train.py --config c05-pretraining/configs/tinystories.yaml --precision fp32 --device cpu --threads 8measured matmul peak on cpu: 0.62 TFLOP/s
time 0 event start params 5401856 flops_per_token 37129728 tokens_per_step 8192 device cpu world_size 1
time 1.6000 step 1 loss 8.3875 lr 5e-05 grad_norm 2.8307 param_norm 74.0943 tok_s 5188.7080 step_ms 1578.8131 mem_mb 1265.5352 epoch 0 mfu 0.3129
time 11.3800 step 10 loss 7.3487 lr 0.0005 grad_norm 1.7323 param_norm 74.1452 tok_s 7539.8322 step_ms 1086.4963 mem_mb 1548.9414 epoch 0 mfu 0.4547
time 22.2200 step 20 loss 6.1249 lr 0.001 grad_norm 0.9156 param_norm 74.6801 tok_s 7562.0925 step_ms 1083.2980 mem_mb 1397.3555 epoch 0 mfu 0.4560
time 33.3800 step 30 loss 5.8435 lr 0.0015 grad_norm 0.5586 param_norm 75.8518 tok_s 7339.5567 step_ms 1116.1437 mem_mb 1477.7891 epoch 0 mfu 0.4426
time 46.1600 step 40 loss 5.6333 lr 0.002 grad_norm 0.5073 param_norm 77.1057 tok_s 6414.5067 step_ms 1277.1052 mem_mb 1401.2188 epoch 0 mfu 0.3868
time 60.4600 step 50 loss 5.3009 lr 0.002 grad_norm 0.7090 param_norm 78.2697 tok_s 5735.0440 step_ms 1428.4110 mem_mb 1460.2852 epoch 0 mfu 0.3459The first lines are worth reading closely. The model has 5,401,856 parameters. The first loss is 8.3875, close to ln(4096), which is 8.318. That is the loss of a uniform guess, so the model starts with no preference. On a CPU, mem_mb is the resident memory of the whole process, so it also counts Python, PyTorch and the loader. It sits between about 1.1 and 1.5 GiB and does not show the formula from step 7. A GPU would report tensor memory alone.
The run reaches step 800 in 1,002 seconds, about 17 minutes. Validation loss falls at every evaluation.
time 63.8900 step 50 val_loss 5.3276 val_ppl 205.9424 tokens_seen 409600
time 131.5700 step 100 val_loss 4.4436 val_ppl 85.0798 tokens_seen 819200
time 197.1900 step 150 val_loss 3.9245 val_ppl 50.6283 tokens_seen 1228800
time 263.1900 step 200 val_loss 3.6379 val_ppl 38.0107 tokens_seen 1638400
time 325.7800 step 250 val_loss 3.4236 val_ppl 30.6789 tokens_seen 2048000
time 389.3000 step 300 val_loss 3.2595 val_ppl 26.0363 tokens_seen 2457600
time 450.3400 step 350 val_loss 3.1045 val_ppl 22.2981 tokens_seen 2867200
time 511.8000 step 400 val_loss 3.0108 val_ppl 20.3039 tokens_seen 3276800
time 567.9800 step 450 val_loss 2.9262 val_ppl 18.6561 tokens_seen 3686400
time 629.4100 step 500 val_loss 2.8459 val_ppl 17.2178 tokens_seen 4096000
time 690.9000 step 550 val_loss 2.7787 val_ppl 16.0981 tokens_seen 4505600
time 748.5200 step 600 val_loss 2.7305 val_ppl 15.3405 tokens_seen 4915200
time 808.2300 step 650 val_loss 2.6918 val_ppl 14.7576 tokens_seen 5324800
time 868.6400 step 700 val_loss 2.6556 val_ppl 14.2330 tokens_seen 5734400
time 928.0500 step 750 val_loss 2.6316 val_ppl 13.8964 tokens_seen 6144000
time 1002.4800 step 800 val_loss 2.6135 val_ppl 13.6472 tokens_seen 6553600Scrub through the run. Each metric in the figure is a saved log value.
Do the pieces agree when they run together? Each module has its own test, but a bug can hide between modules. So we train the same model on the same batches with Hugging Face’s Trainer. The Trainer does its own accumulation, clipping and stepping. It gets only what it needs to match: our loss, our optimiser and schedule, and a sequential sampler.
class SameLossTrainer(Trainer):
def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
logits = model(inputs["input_ids"]).logits # (B, L, V)
loss = lm_loss_sum(logits, inputs["targets"]) / inputs["targets"].numel()
return (loss, logits) if return_outputs else loss
def _get_train_sampler(self, *args, **kwargs):
return SequentialSampler(self.train_dataset)$ .venv/bin/python c05-pretraining/scripts/compare_hf_trainer.py --steps 2020 steps, 2 micro-batches of 8 per step, seq_len 64, fp32, same init and same batches
step our loop HF Trainer
1 8.3234 8.3234
2 8.2918 8.2918
5 7.9845 7.9845
10 7.1485 7.1485
20 6.6148 6.6148
max |weights ours - weights HF| after the last step: 0.00e+00The same run on an H100
We ran the main config on NVIDIA H100 80GB HBM3 GPUs, once for each row, with bf16 and no other job on the GPUs. These runs are separate from the CPU numbers above, and each is a single run. The 2-GPU rows use DDP on NCCL and keep the batch per GPU. They see twice the tokens per step (16,384), so they are not the same run as the 1-GPU row.
| Run | Validation loss | Tokens per second (median) | Tokens per step | Results file |
|---|---|---|---|---|
| Llama, CPU | 2.6135 | about 7,000 | 8,192 | train_tinystories.log |
| Llama, 1 GPU | 2.6142 | about 148,000 | 8,192 | gpu_train_1gpu.log |
| Llama, 2 GPUs, DDP | 2.3521 | about 270,000 | 16,384 | gpu_train_ddp.log |
| TinyLLM, 2 GPUs, DDP | 2.0171 | about 274,000 | 16,384 | gpu_train_ddp_tinyllm.log |
The 1-GPU run ends at 2.6142 in 52 seconds, next to 2.6135 for the CPU run that took 17 minutes. So bf16 on a GPU gives the same quality here, about 21 times the throughput. Two GPUs give about 1.8 times the tokens per second of one. The lower loss of the DDP runs comes from seeing twice the data, and it says nothing about DDP being better. The TinyLLM gap seen on the CPU appears again: 2.0171 against 2.3521 for Llama.
Now sample from the final checkpoint. The sampler stops at EOS, which the model learned because every document ended in one.
$ .venv/bin/python c05-pretraining/scripts/sample.py --ckpt c05-pretraining/runs/tinystories/ckpt_000800.pt --device cpustep 800, device cpu, temperature 0.8, top-k 40
[Once upon a time] , there was a little girl called Lily. She loved to play with her red ball. One day, she went to the park with her mom.
At the park, Lily saw a big, pretty rock. She was very happy. She picked it up and put it on the ground. She was sad and decided to try the apple for their friend.
While they were playing, Mia saw the ball and wanted to play with it. She asked her mom, "Why are you scared, Kitty?" Her mom said, "I love you to make a new friend. Do you want to
(120 tokens, hit the limit)
[Lily found a] small apple on the beak. He thought the secret was a nice place to climb the leaf. So he found a big pile of paper. He looked at the apple and found the key!
Mom took the bug to the tree and showed it to the plant. Now, the rock was happy. Sue and the plant played together. They had lots of fun. But then, a big wind came and blew the key away. The bug was very happy.
The moral of the story is: always be careful.<|endoftext|>
(105 tokens, stopped at EOS)
[The little dog was sad because] he could have a new home. He asked his dog, "Can I help me eat the ball?" His dad said, "Yes, can we play together?"
The dog replied, "Yes, I want to play. But you can take your ball, we can use it." The cat wagged its tail and made a big mess. The cat was a small dog.
The cat was sad, but he could not play with the dog. The dog wanted to help the cat. So, he heard the cat and the cat. The dog was happy and had a new home. The
(120 tokens, hit the limit)The stories are grammatical and wander. Names change mid-story, and objects do odd things. That is what 6.5M training tokens buy a 5.4M-parameter model. The second prompt ends with EOS by itself, after 105 tokens. results/sample_tinyllm.txt has the same prompts on C4’s model.
The same command with --model tinyllm trains C4’s TinyLLM on the same data. It has the same architecture as the Llama model, yet it ends lower: 2.2611 against 2.6135. The two differ in two ways that we know of. Hugging Face draws every weight with a standard deviation of 0.02, while C4 also divides the two residual output projections by sqrt(2 × num_layers). The normalisation epsilon also differs, 1e-6 in Hugging Face and 1e-5 in C4. We suspected the start, so we trained the Llama model again with only those two matrices scaled.
$ .venv/bin/python c05-pretraining/scripts/compare_init.py step llama, flat init tinyllm llama, scaled init
50 5.3276 4.4215 4.4133
100 4.4436 3.6507 3.6288
200 3.6379 3.0837 3.0695
400 3.0108 2.6083 2.5965
600 2.7305 2.3667 2.3586
800 2.6135 2.2611 2.2529With C4’s scaling, the Llama model ends at 2.2529, next to TinyLLM. That is consistent with the initialisation being almost the whole gap. It is one seed per run, so we cannot rule out other causes, and we do not claim the remaining 0.008 is more than noise. The epsilon was not tested.
Model FLOPs utilisation
Goal Turn tokens per second into one honest number: the share of the hardware peak doing useful work.
A tokens-per-second number means little without the model size. MFU fixes that. It divides the useful FLOPs per second by the peak FLOPs per second of the hardware.
What to do with the number inHow to find what is slowing your modeldef flops_per_token(model: nn.Module, a: ModelArgs, seq_len: int) -> float:
return 6 * matmul_params(model, a) + 12 * a.num_layers * a.hidden_size * seq_len2N plus attention. Backward costs twice forward. Together that gives 6N + 12 n d T, the formula used in the PaLM appendix.Plug in the main model. N is 5,401,856, with n = 6 layers, d = 256 and T = 256.
6 × 5,401,856 + 12 × 6 × 256 × 256 = 32,411,136 + 4,718,592 = 37,129,728
That matches flops_per_token in the first line of the log. Nearly all of it comes from the weights. The attention term is 13% here because the context is short.
We also need a peak. Vendors publish one for datacenter GPUs. For other hardware we measure the best FLOP rate of a large square matmul, which is the friendliest workload the machine can run.
@torch.no_grad()
def measure_matmul_peak(device: torch.device, dtype: torch.dtype, n: int = 4096, iters: int = 20) -> float:
"""Best FLOP/s of a large square matmul on this device.
Vendors publish a peak for datacenter GPUs; use that number there. Elsewhere we
measure what the hardware actually reaches on the friendliest possible workload,
and report MFU against that. It is an upper bound we can defend, not a datasheet value.
"""
a = torch.randn(n, n, device=device, dtype=dtype)
b = torch.randn(n, n, device=device, dtype=dtype)
for _ in range(3):
a @ b
synchronize(device)
best = 0.0
for _ in range(iters):
t = time.perf_counter()
a @ b
synchronize(device)
best = max(best, 2 * n**3 / (time.perf_counter() - t))
return best2 n³ FLOPs. The synchronize calls matter: without them a GPU timing measures only the launch of the work.$ .venv/bin/python c05-pretraining/benchmarks/bench_mfu.py --device cpu --metrics runs/tinystories/metrics.jsonlparams 5,401,856, matmul params N 5,401,856
formula 6N + 12 n_layers d T = 32,411,136 + 4,718,592 = 37,129,728 FLOPs per token
FlopCounterMode (forward + backward): 37,896,192 FLOPs per token, ratio formula/counted 0.98
measured peak, best large square matmul: cpu torch.float32 0.731 TFLOP/s
training run: median 6,972 tokens/s on cpu (fp32)
achieved 0.259 TFLOP/s, MFU against that peak 35.4%Three checks are in that output. The formula gives 37,129,728 FLOPs per token and FlopCounterMode counts 37,896,192, a ratio of 0.98. The best matmul on this CPU reached 0.731 TFLOP/s in fp32. The training run had a median of 6,972 tokens per second, and 6,972 × 37,129,728 is 0.259 TFLOP/s. That is 35.4% of the peak. One caution: the peak and the throughput were measured at different times on a shared CPU. A second run of the benchmark on the same CPU measured the peak at 0.595 TFLOP/s, which would make the same throughput 43.5%. Read the MFU as a range of about 35% to 44%, not as one exact value.
MFU tells you there is a gap between what the hardware can do and what the run uses. It does not say why. The theory post covers how to find the cause. On one H100 the same benchmark gives a different picture.
$ .venv/bin/python c05-pretraining/benchmarks/bench_mfu.py --device cuda --precision bf16 --metrics runs/gpu_1/metrics.jsonlparams 5,401,856, matmul params N 5,401,856
formula 6N + 12 n_layers d T = 32,411,136 + 4,718,592 = 37,129,728 FLOPs per token
FlopCounterMode (forward + backward): 37,896,192 FLOPs per token, ratio formula/counted 0.98
measured peak, best large square matmul: cuda torch.bfloat16 687.697 TFLOP/s
training run: median 147,784 tokens/s on cuda (bf16)
achieved 5.487 TFLOP/s, MFU against that peak 0.8%The run reached 5.487 TFLOP/s against a measured bf16 peak of 687.7 TFLOP/s. That is an MFU of 0.8%. The model is too small to use the GPU, so most of the time goes to launching small kernels. A real run would aim far higher. This number is only for this model and says nothing about large ones.
Data parallelism with DDP
Goal Train with several processes, and prove that the result equals one big batch.
DDP keeps one full model per process. Each process gets different data, computes its own gradients, and averages them with all the others. All processes then apply the same step, so the replicas stay identical. torchrun starts the processes and sets RANK, WORLD_SIZE and LOCAL_RANK in the environment of each.
def init_distributed(timeout_s: int = 300) -> DistInfo:
"""Join the process group if torchrun launched us; otherwise run single-process."""
if "RANK" not in os.environ:
return DistInfo()
backend = "nccl" if torch.cuda.is_available() else "gloo"
# A finite timeout turns a dead peer into an error instead of a hang forever.
timeout = datetime.timedelta(seconds=timeout_s)
attempt = int(os.environ.get("TORCHELASTIC_RESTART_COUNT", 0))
if attempt == 0:
dist.init_process_group(backend, timeout=timeout)
else:
# After a restart torchrun's store still holds the addresses the dead processes published,
# and ranks would try to connect to those. A new key prefix gives each attempt a clean slate.
agent_store = dist.TCPStore(os.environ["MASTER_ADDR"], int(os.environ["MASTER_PORT"]),
is_master=False, timeout=timeout)
dist.init_process_group(backend, store=dist.PrefixStore(f"attempt_{attempt}", agent_store),
rank=int(os.environ["RANK"]), world_size=int(os.environ["WORLD_SIZE"]),
timeout=timeout)
info = DistInfo(dist.get_rank(), int(os.environ["LOCAL_RANK"]), dist.get_world_size())
if torch.cuda.is_available():
torch.cuda.set_device(info.local_rank)
return infoPrefixStore branch is for restarts, and step 19 shows why it exists.The data split is already done. EpochSampler from step 6 takes every world_size-th entry. The other half is the all-reduce, and it is short enough to write by hand.
def allreduce_gradients_by_hand(model: nn.Module) -> None:
"""What DDP does, without the bucketing and overlap: average every gradient."""
world = dist.get_world_size()
for p in model.parameters():
if p.grad is not None:
dist.all_reduce(p.grad, op=dist.ReduceOp.SUM)
p.grad /= worldIn train_step we saw one more line for this. Under DDP, the all-reduce runs only on the last micro-batch, because an all-reduce on each one would be wasted communication.
# Under DDP, skip the gradient all-reduce on every micro-batch but the last.
sync = contextlib.nullcontext() if last or not hasattr(model, "no_sync") else model.no_sync()no_sync turns off the all-reduce for this backward. The gradients still add up locally.EpochSampler from step 6. The gradient cells show the flow, and their colours are not real values.To check it, one script runs three versions on the same global batch of (8, 32). The first is one process with the whole batch. The second is two processes with DDP. The third is two processes with our all-reduce by hand.
| Tensor | Shape | Meaning |
|---|---|---|
| x, global | (8, 32) | The same batch on every rank, built from one seed. |
| xl, local | (4, 32) | x[rank::world_size], this rank’s half. |
| w_ddp | (P,) | All weights in one vector, gathered from each rank to compare. |
$ .venv/bin/torchrun --nproc_per_node 2 c05-pretraining/scripts/ddp_equivalence.pyworld size 2, backend gloo, local batch (4, 32), global batch (8, 32)
max |DDP - single process big batch| 3.73e-09
max |all-reduce by hand - DDP| 0.00e+00
weights identical on every rank: TrueDDP matches a single process to float32 noise. Our by-hand version matches DDP exactly. The weights are identical on every rank.
The full loop runs under torchrun with the same train.py. This config uses a smaller 1.25M-parameter model for 200 steps, so two processes fit on the CPU.
$ .venv/bin/torchrun --nproc_per_node 2 c05-pretraining/scripts/train.py --config c05-pretraining/configs/ddp_cpu.yaml --threads 4time 0 event start params 1250432 flops_per_token 8289024 tokens_per_step 4096 device cpu world_size 2
time 0.3000 step 1 loss 8.3468 lr 0.00015 grad_norm 1.9657 param_norm 40.6450 tok_s 1.43e+04 step_ms 284.3754 mem_mb 554.8828 epoch 0
time 5.7100 step 25 loss 5.8189 lr 0.003 grad_norm 0.3432 param_norm 46.1238 tok_s 1.82e+04 step_ms 225.1879 mem_mb 547.4961 epoch 0
time 11.4100 step 50 loss 5.3424 lr 0.00283 grad_norm 0.8168 param_norm 52.5865 tok_s 1.8e+04 step_ms 227.3825 mem_mb 557.5156 epoch 0
time 17.2000 step 75 loss 4.7435 lr 0.00244 grad_norm 0.9380 param_norm 56.0642 tok_s 1.79e+04 step_ms 224.7778 mem_mb 601.0898 epoch 0
time 22.6500 step 100 loss 4.3564 lr 0.00191 grad_norm 0.5730 param_norm 58.7382 tok_s 1.89e+04 step_ms 217.2901 mem_mb 536.9414 epoch 0
time 22.8200 step 100 val_loss 4.4264 val_ppl 83.6259 tokens_seen 409600
time 28.3300 step 125 loss 4.0599 lr 0.00132 grad_norm 0.6735 param_norm 60.7118 tok_s 1.89e+04 step_ms 214.0158 mem_mb 586.8281 epoch 0It ends at a validation loss of 3.9259, and the same run on TinyLLM ends at 3.7687. Multi-GPU DDP uses the same code on NCCL.
On two NVIDIA H100 GPUs the equivalence script gives the same answer as on gloo.
$ .venv/bin/torchrun --nproc_per_node 2 c05-pretraining/scripts/ddp_equivalence.pyworld size 2, backend nccl, local batch (4, 32), global batch (8, 32)
max |DDP - single process big batch| 3.73e-09
max |all-reduce by hand - DDP| 0.00e+00
weights identical on every rank: TrueDDP on NCCL matches one process with the whole batch to 3.73e-09, the same gap as on the CPU, and the ranks stay identical. The throughput of the full runs is in the table in step 15. The multi-GPU runs used two GPUs. Larger counts have not been measured.
Sharded training with FSDP and ZeRO
Goal Stop keeping redundant copies, starting with the optimiser state, and measure what each rank stores.
DDP has one weakness: memory. Each rank stores all the weights, all the gradients and both Adam moments. That is four times the model, on every rank, and most of it is a copy of what another rank already holds. ZeRO removes these copies in stages.
Stage 1 is the simplest. Each parameter gets one owner rank, and only that rank keeps its moments. The owner computes the update and broadcasts the new weight. PyTorch ships this, and it runs on gloo.
def wrap_zero1(model: nn.Module, lr: float, weight_decay: float, betas=(0.9, 0.95)) -> ZeroRedundancyOptimizer:
"""Each parameter is owned by one rank. Only the owner keeps moments and computes the update.
The owner then broadcasts the new weight to the others.
"""
return ZeroRedundancyOptimizer(
model.parameters(), optimizer_class=torch.optim.AdamW,
lr=lr, weight_decay=weight_decay, betas=betas,
)$ .venv/bin/torchrun --nproc_per_node 2 c05-pretraining/scripts/zero_train.pyrank 0: optimizer state DDP+AdamW 9.54 MiB, ZeRO-1 4.76 MiB, final-loss gap 0.00e+00, max weight gap 0.00e+00
rank 1: optimizer state DDP+AdamW 9.54 MiB, ZeRO-1 4.78 MiB, final-loss gap 0.00e+00, max weight gap 0.00e+00Optimiser state falls from 9.54 MiB to 4.76 MiB and 4.78 MiB, so about half per rank. The two shares differ a little because whole parameters are assigned to owners. The weights stay identical to DDP, with a gap of 0. So this memory saving costs no accuracy, and it costs an extra broadcast each step.
FSDP goes further and shards the weights too. A rank holds one shard of each block. Just before a block runs, its weights are gathered with an all-gather. Just after, they are freed.
def wrap_fsdp(model: nn.Module, precision: str = "fp32") -> nn.Module:
"""Shard every decoder block on its own, then whatever is left at the root."""
device = next(model.parameters()).device
# An explicit mesh keeps FSDP from probing for an accelerator it will not use.
mesh = init_device_mesh(device.type, (dist.get_world_size(),))
policy = MixedPrecisionPolicy(
param_dtype=torch.bfloat16 if precision == "bf16" else None,
reduce_dtype=torch.float32 if precision == "bf16" else None,
)
for block in decoder_layers(model):
fully_shard(block, mesh=mesh, mp_policy=policy) # the unit of gather and free
return fully_shard(model, mesh=mesh, mp_policy=policy)Move the controls to see the arithmetic for models of several sizes. This is calculation, not measurement. The two runs in this step are the measured part.
The script trains the same seeded steps under DDP and under FSDP on gloo, gathers the shards back, and compares them.
$ .venv/bin/torchrun --nproc_per_node 2 c05-pretraining/scripts/fsdp_train.py --steps 5rank 1: DDP params 4.75 MiB, optimizer state 9.50 MiB; FSDP params 2.37 MiB, optimizer state 4.75 MiB; last loss DDP 8.336046 FSDP 8.336046; max weight gap 3.70e-07
rank 0: DDP params 4.75 MiB, optimizer state 9.50 MiB; FSDP params 2.38 MiB, optimizer state 4.76 MiB; last loss DDP 8.318911 FSDP 8.318911; max weight gap 3.70e-07Each rank stores half of the weights, 2.38 MiB and 2.37 MiB against 4.75 MiB, and half of the optimiser state. The final losses match to all printed digits, and the largest weight gap is 3.70e-07. This run proves that the shards are right. It says nothing about speed or GPU memory.
The GPU memory is on a larger model, with 141M parameters, 100 steps and two NVIDIA H100 GPUs.
$ .venv/bin/torchrun --nproc_per_node 2 c05-pretraining/scripts/fsdp_train.py --steps 100 --hidden-size 1024 --num-layers 12rank 1: DDP params 544.00 MiB, optimizer state 1088.01 MiB, peak 2769.1 MiB; FSDP params 272.00 MiB, optimizer state 544.00 MiB, peak 1854.4 MiB; last loss DDP 8.580338 FSDP 8.580379; max weight gap 9.52e-04
rank 0: DDP params 544.00 MiB, optimizer state 1088.01 MiB, peak 2769.1 MiB; FSDP params 272.00 MiB, optimizer state 544.00 MiB, peak 1854.4 MiB; last loss DDP 8.532455 FSDP 8.532420; max weight gap 9.52e-04Per GPU, parameters fall from 544 to 272 MiB and optimiser state from 1,088 to 544 MiB. Peak memory falls from 2,769 to 1,854 MiB, which is a smaller drop than the parameters and optimiser state, because activations and the temporary full copy of each block remain. The weight gap against DDP is 9.52e-04, larger than the 3.70e-07 on the CPU. We did not investigate the cause. DeepSpeed was not run, so ZeRO-2 and ZeRO-3 remain not yet measured.
Stages 2 and 3 of ZeRO need DeepSpeed. Its config for the same kind of run is short. It uses a learning rate of 3e-3 and no schedule, so it is a sketch and not a copy of the main run.
{
"train_micro_batch_size_per_gpu": 16,
"gradient_accumulation_steps": 2,
"gradient_clipping": 1.0,
"bf16": {
"enabled": true
},
"zero_optimization": {
"stage": 3
},
"optimizer": {
"type": "AdamW",
"params": {
"lr": 0.003,
"betas": [
0.9,
0.95
],
"weight_decay": 0.1
}
}
}$ .venv/bin/torchrun --nproc_per_node 2 c05-pretraining/scripts/deepspeed_train.py --stage 3 --steps 50
Break it on purpose
Goal Cause each failure for real, see what the guard does, and find where the guard is weak.
A long run will hit these failures eventually. Each one gets a detector and a planned response. We wrote the guards earlier in the loop, and now we test them by causing each failure. These runs are on CPU with the small config.
| Failure | Detector | Response | Tried here |
|---|---|---|---|
| Bad batch | check_batch | Stop with a clear message | Yes, CPU |
| NaN or Inf | train_step, NonFiniteGuard | Skip the update. Stop after 3 in a row | Yes, CPU |
| Exploding gradients | grad_norm, clipping | Scale down, and log the real norm | Yes, CPU |
| Loss spike | SpikeDetector | Flag it in the log | Yes, CPU |
| Out of memory | step_with_oom_retry | Split the micro-batches and retry | Yes, CPU, under a memory cap |
| Corrupt checkpoint | latest_valid_checkpoint | Fall back to an older one | Yes, CPU |
| Dead process | torchrun --max-restarts | Restart all ranks, then auto-resume | dead_process_demo.py |
Out of memory needs one more idea. When a step fails, we free memory, split each micro-batch in two and retry. The token-weighted rule from step 9 makes this safe, because the split step has the same gradient.
def step_with_oom_retry(step_fn, micro, opt, empty_cache, max_splits: int = 3):
"""Run step_fn(micro); on OOM free memory, split the micro-batches and retry.
Because train_step normalises by the step's total token count, the split step has
the same gradient as the original one: only memory use and speed change.
"""
for attempt in range(max_splits + 1):
try:
return step_fn(micro), len(micro)
except (torch.OutOfMemoryError, RuntimeError) as err:
if not is_oom(err) or attempt == max_splits:
raise
# Outside the except block on purpose: until it ends, the traceback keeps every tensor
# of the failed attempt alive, and emptying the cache there would free nothing.
opt.zero_grad(set_to_none=True) # drop partial gradients from the failed attempt
gc.collect()
empty_cache()
micro = split_micro_batches(micro)
print(f"[oom] retrying with {len(micro)} micro-batches of {micro[0][0].size(0)}")To cause a real failure on the CPU, the script caps the process memory at 1,024 MiB above its current use. Then it asks for one micro-batch of 128 sequences.
$ .venv/bin/python c05-pretraining/scripts/break_it.py --case oommemory cap 1024 MiB above current use, one micro-batch of 128
[oom] retrying with 2 micro-batches of 64
[oom] retrying with 4 micro-batches of 32
[oom] retrying with 8 micro-batches of 16
[oom] retrying with 16 micro-batches of 8
finished with 16 micro-batches, loss 8.3717, tokens 32,768 (all of them)The step succeeds at 16 micro-batches of 8 sequences. All 32,768 tokens were used, so this is still the same global batch.
Read the listing and this output together. step_with_oom_retry defaults to max_splits=3, which stops at 8 micro-batches. The demo passes max_splits=5 to reach 16, because at 8 the CPU cap still fails. With the default, this batch of 128 would raise instead of recovering. The test uses a fake out-of-memory error raised before any backward pass. So the path where a real failure leaves partial gradients is exercised only by this demo.
The same demo ran on a GPU. With the process capped at 1 GiB of GPU memory, a real CUDA out-of-memory error was recovered with 8 micro-batches of 16. Every one of the 32,768 tokens was used.
$ .venv/bin/python c05-pretraining/scripts/break_it.py --case oom --device cuda=== oom (cuda) ===
memory cap 1024 MiB for the whole process, one micro-batch of 128
[oom] retrying with 2 micro-batches of 64
[oom] retrying with 4 micro-batches of 32
[oom] retrying with 8 micro-batches of 16
finished with 8 micro-batches, loss 8.3717, tokens 32,768 (all of them)The last failure is a process that dies. torchrun --max-restarts 1 restarts the whole group, and the same train call finds the newest checkpoint.
$ .venv/bin/torchrun --nproc_per_node 2 --max-restarts 1 c05-pretraining/scripts/dead_process_demo.pyattempt 0 rank 0: starting
attempt 0 rank 1: starting
time 0 event start params 353088 flops_per_token 2216832 tokens_per_step 2048 device cpu world_size 2
time 0.1700 step 1 loss 8.3329 lr 0.0003 grad_norm 0.6234 param_norm 21.4684 tok_s 1.23e+04 step_ms 164.9058 mem_mb 495.8047 epoch 0
time 1.1700 step 10 loss 7.5073 lr 0.003 grad_norm 0.9604 param_norm 22.4051 tok_s 1.85e+04 step_ms 110.5127 mem_mb 500.5938 epoch 0
rank 1: simulated crash at step 15
attempt 1 rank 0: starting
attempt 1 rank 1: starting
[resume] ckpt_000010.pt: step 10, data epoch 0 batch 20
[resume] ckpt_000010.pt: step 10, data epoch 0 batch 20
time 1.1000 step 20 loss 6.4415 lr 0.00186 grad_norm 0.8014 param_norm 26.5493 tok_s 1.88e+04 step_ms 108.9750 mem_mb 504.1172 epoch 0
time 2.2800 step 30 loss 6.0912 lr 0.000317 grad_norm 0.7556 param_norm 27.9602 tok_s 1.81e+04 step_ms 108.9697 mem_mb 504.1680 epoch 0
time 2.3200 step 30 val_loss 6.1583 val_ppl 472.6136 tokens_seen 61440
finished after restartRank 1 dies at step 15. Rank 0 sees the broken connection and fails too, so torchrun starts attempt 1 with both ranks. Both load the newest checkpoint, from step 10, repeat five steps and finish at step 30. The demo shows that the run recovers. It does not compare the final weights with an unbroken run. Step 14 made that comparison in one process.
The strategies compared
The first table compares ways to make sequences. The numbers are from the full corpus at L = 256. Read across for what each choice costs. No strategy wins on every column.
| Strategy | Utilisation | Tokens cut | Documents split | Windows with a boundary | Needs a loss mask | Loader |
|---|---|---|---|---|---|---|
| Pad to L | 73.0% | 8.1% | Cut, not split | 0% | Yes | Simple |
| Pad to batch max | 73.0% | 8.1% | Cut, not split | 0% | Yes | Simple |
| Greedy packing | 100.0% | 0.0% | 72.7% | 91.9% | No | Simplest: a fixed slice |
| Best-fit packing | 78.6% | 0.0% | 12.7% | Not measured | Yes, for the gaps | Needs a stored plan |
The second table compares the distributed strategies along the costs from steps 17 and 18. Per-rank memory is arithmetic, with P as the size of the weights and N as the rank count. The last column is what this post has really run.
| Strategy | Weights | Gradients | Optimiser state | Added communication | Needs | Run here |
|---|---|---|---|---|---|---|
| One process | P | P | 2P | None | Nothing | Yes |
| DDP | P | P | 2P | All-reduce per step | PyTorch | Yes, gloo and NCCL on 2 H100 GPUs |
| ZeRO-1 | P | P | 2P / N | Plus a broadcast of new weights | PyTorch | Yes, gloo |
| ZeRO-2 | P | P / N | 2P / N | Reduce-scatter of gradients | DeepSpeed, GPU | Not yet measured |
| ZeRO-3 | P / N | P / N | 2P / N | Plus all-gather per block | DeepSpeed, GPU | Not yet measured |
| FSDP | P / N | P / N | 2P / N | All-gather per block | PyTorch | Yes, gloo, and memory on 2 H100 GPUs |
The pattern to notice: moving down the table buys memory with communication. So move down only when memory is the real limit. For a model that fits, DDP is simpler and is usually enough.
Run everything
The final folder, and every command that produced a number in this post. Outputs are saved in c05-pretraining/results/. Data and checkpoints are left out of git, so prepare_data.py comes first.
c05-pretraining/ final tree
c05-pretraining/
├── README.md
├── conftest.py
├── configs/
│ ├── smoke.yaml
│ ├── tinystories.yaml
│ ├── ddp_cpu.yaml
│ └── deepspeed_zero3.json
├── pretrain/
│ ├── config.py
│ ├── corpus.py
│ ├── tokenizer.py
│ ├── shards.py
│ ├── packing.py
│ ├── loader.py
│ ├── streaming.py
│ ├── model.py
│ ├── optim.py
│ ├── schedule.py
│ ├── step.py
│ ├── activation_ckpt.py
│ ├── rng.py
│ ├── checkpoint.py
│ ├── metrics.py
│ ├── trainer.py
│ ├── mfu.py
│ ├── distributed.py
│ ├── fsdp.py
│ ├── zero.py
│ ├── guards.py
│ └── utils.py
├── scripts/
│ ├── prepare_data.py
│ ├── inspect_tokens.py
│ ├── naive_train.py
│ ├── plot_schedule.py
│ ├── check_accumulation.py
│ ├── resume_test.py
│ ├── train.py
│ ├── sample.py
│ ├── ddp_equivalence.py
│ ├── compare_hf_trainer.py
│ ├── compare_init.py
│ ├── zero_train.py
│ ├── fsdp_train.py
│ ├── deepspeed_train.py
│ ├── dead_process_demo.py
│ └── break_it.py
├── benchmarks/
│ ├── bench_packing.py
│ ├── bench_loader.py
│ ├── bench_precision.py
│ ├── bench_checkpointing.py
│ └── bench_mfu.py
├── results/
└── tests/
├── conftest.py
├── test_data.py
├── test_loader.py
├── test_training.py
└── test_systems.py
$ .venv/bin/python -m pytest c05-pretraining -m "not slow and not gpu and not network"
$ .venv/bin/python c05-pretraining/scripts/prepare_data.py
$ .venv/bin/python c05-pretraining/scripts/inspect_tokens.py
$ .venv/bin/python c05-pretraining/scripts/naive_train.py --steps 200
$ .venv/bin/python c05-pretraining/benchmarks/bench_packing.py
$ .venv/bin/python c05-pretraining/benchmarks/bench_loader.py
$ .venv/bin/python c05-pretraining/scripts/plot_schedule.py
$ .venv/bin/python c05-pretraining/scripts/check_accumulation.py
$ .venv/bin/python c05-pretraining/benchmarks/bench_precision.py --config c05-pretraining/configs/smoke.yaml --device cpu --steps 30
$ .venv/bin/python c05-pretraining/benchmarks/bench_checkpointing.py --device cpu --steps 6
$ .venv/bin/python c05-pretraining/benchmarks/bench_checkpointing.py --device cpu --steps 6 --model tinyllm
$ .venv/bin/python c05-pretraining/scripts/resume_test.py --steps 40
$ .venv/bin/python c05-pretraining/scripts/train.py --config c05-pretraining/configs/tinystories.yaml --precision fp32 --device cpu --threads 8
$ .venv/bin/python c05-pretraining/scripts/train.py --config c05-pretraining/configs/tinystories.yaml --precision fp32 --device cpu --threads 8 --model tinyllm --out-dir runs/tinyllm
$ .venv/bin/python c05-pretraining/scripts/compare_init.py
$ .venv/bin/python c05-pretraining/scripts/compare_hf_trainer.py --steps 20
$ .venv/bin/python c05-pretraining/scripts/sample.py --ckpt c05-pretraining/runs/tinystories/ckpt_000800.pt --device cpu
$ .venv/bin/python c05-pretraining/benchmarks/bench_mfu.py --device cpu --metrics runs/tinystories/metrics.jsonl
$ .venv/bin/torchrun --nproc_per_node 2 c05-pretraining/scripts/ddp_equivalence.py
$ .venv/bin/torchrun --nproc_per_node 2 c05-pretraining/scripts/train.py --config c05-pretraining/configs/ddp_cpu.yaml --threads 4
$ .venv/bin/torchrun --nproc_per_node 2 c05-pretraining/scripts/zero_train.py
$ .venv/bin/torchrun --nproc_per_node 2 c05-pretraining/scripts/fsdp_train.py --steps 5
$ .venv/bin/torchrun --nproc_per_node 2 --max-restarts 1 c05-pretraining/scripts/dead_process_demo.py
$ .venv/bin/python c05-pretraining/scripts/break_it.py --case all
Key insights and nuances
- Read utilisation next to tokens cut. At L = 128, padding shows 99.6% utilisation and discards 37.3% of all tokens. Step 5
- EOS matters more as a stop signal than as a tokenizer boundary. Only 2 of 1,999 real neighbouring pairs tokenize differently when joined. Step 4
- Best-fit packing depends on how L relates to your documents. Its utilisation is 78.6% at L = 256 and 95.1% at L = 512 on the same corpus. Step 5
- Packed data hides the mean-of-means bug. The error is at float32 noise until target counts differ, then it reaches 8.25e-03. Step 9
- A wrong resume can look like an improvement. The weights-only restart reports a lower training loss. It replays batches the model has already seen, and it also restarts warmup and the Adam moments. Step 14
- Exact resume is a testable claim. The stopped and restarted run matches the straight run with a gap of exactly 0, on a CPU and on one H100. Other GPUs and multi-GPU runs have not been measured. Step 14
- The optimiser is twice the model. That is why the two Adam moments are the first thing ZeRO shards. Step 7 and step 18
- An MFU from a measured peak is for comparing runs on one machine. It is not comparable with a value computed from a datasheet. Step 16
- Equal shares make DDP equal to one batch. Packing and an equal-share sampler are what keep a plain average correct. Step 17
- A guard needs testing as well. Our first spike detector missed a jump to 10.586, because its variance still held the early fall in loss. A median over a short window catches it. Step 19
- More workers can be slower. On memory-mapped tokens, one process gave 1,910 batches per second and two workers gave 718. Step 6
- bf16 is not automatically faster. On a CPU that emulates it, a step takes about 11 times as long, with a loss gap of only 0.0010. Step 10
- Saved tensors are not peak memory. Activation checkpointing cut saved tensors to 0.18 times, and process peak growth to only 0.70 times. Step 12
- The same architecture can train differently.
TinyLLMends at 2.2611 and HF Llama at 2.6135. Scaling the residual projections at init brings Llama to 2.2529, on one seed, which is consistent with the start being the cause. Step 15 - An independent implementation checks the step. Our
train_stepand Hugging Face Trainer, given the same optimiser, schedule and loss, end 20 steps with a weight gap of exactly 0. It does not cover the loader or the guards. Step 15
Exercises
- Measure the block-causal maskMedium Train the same config twice with the same seed. In one run, block attention across documents using
block_causal_maskand restart positions withposition_ids. Compare validation loss and step time, and report whether the difference is larger than the gap between two seeds.Hint
The mask has shape (L, L) per window. A model usually wants (B, 1, L, L), with one mask per row, so check what your model accepts.
- Train with best-fit packingHard Write a dataset from the best-fit plan, with padding in the gaps and
IGNOREin the targets.train_stepalready handles unequal token counts. Compare validation loss per token seen with greedy packing, as Ding et al. did on their larger models. - Resume on a different rank countHard
ResumableLoader.load_state_dictrefuses a change inworld_size. Remove that limit. Save a position that does not depend on the rank count, and prove that no window is skipped or repeated when going from 2 ranks to 3.Hint
Count samples consumed in the shared permutation, across all ranks, instead of batches on one rank.
- Make recovery automaticMedium
TrainingDivergedstops the run today. Catch it in the trainer, reload the newest valid checkpoint, halve the learning rate and continue. Test it with the NaN hook frombreak_it.py, and record the rollback in the log. Decide what the config check should do, since the LR has now changed. - Let the gains decayEasy Move the RMSNorm gains into the decay group. Log the mean gain during training, and compare the final validation loss with the normal run. Use a larger
weight_decayto make any effect easier to see.
Continue reading
- Post-Train an LLM: the next tutorial moves from raw text to instructions and preferences, with supervised fine-tuning (SFT), direct preference optimisation (DPO) and group relative policy optimisation (GRPO).
- Build a Modern LLM From Scratch: the architecture this tutorial trains, written module by module.
- How LLMs are pretrained: data sourcing, filtering and mixing at the scale this tutorial leaves out.
- Inside a training step: the memory ledger and timing behind steps 9 to 12.
- The parallelism playbook: everything past FSDP, including tensor and pipeline parallelism.
- Scaling laws from first principles: how to reason about what a larger run would buy.
References
Grouped by topic. Every entry links to its primary source.
Data and tokenization
- TinyStories: How Small Can Language Models Be and Still Speak Coherent English? · Eldan and Li, 2023. The corpus.
- Neural Machine Translation of Rare Words with Subword Units · Sennrich et al., 2015. BPE.
- Fewer Truncations Improve Language Modeling · Ding et al., 2024. Best-fit packing.
Optimisation
- Decoupled Weight Decay Regularization · Loshchilov and Hutter, 2017. AdamW.
- SGDR: Stochastic Gradient Descent with Warm Restarts · Loshchilov and Hutter, 2016. Cosine decay.
- Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour · Goyal et al., 2017. Warmup and large batches.
- On the Difficulty of Training Recurrent Neural Networks · Pascanu et al., 2012. Gradient clipping.
Memory and precision
- Training Deep Nets with Sublinear Memory Cost · Chen et al., 2016. Activation checkpointing.
- Mixed Precision Training · Micikevicius et al., 2017.
Scale
- PaLM: Scaling Language Modeling with Pathways · Chowdhery et al., 2022. The FLOP formula for MFU.
- PyTorch Distributed: Experiences on Accelerating Data Parallel Training · Li et al., 2020. DDP.
- ZeRO: Memory Optimizations Toward Training Trillion Parameter Models · Rajbhandari et al., 2019.
- PyTorch FSDP: Experiences on Scaling Fully Sharded Data Parallel · Zhao et al., 2023.
Code
- blog-coding-tutorials: c05-pretraining · the code for this tutorial.