small-model-lab · Part 1 · Pre-training

Build a tiny GPT — from scratch

This is the build: we train a language model from nothing (no pre-trained weights, no magic) and watch it learn to write, walking through the real code line by line, for someone who is curious but doesn't necessarily write Python.

New to the ideas? Read Part 0 · Concepts first. With no code, it explains what a model is, how text becomes numbers, what “learning” means, and how the pieces fit (with all the diagrams). This page assumes that groundwork and focuses on building it; each step links back to the matching idea in Part 0.

How to read this. Top to bottom. Each step is the plain idea in a line or two, then the actual code in a dark box, then a “what this says” translation. You can skip the code boxes entirely and still follow along, or read them closely and learn to recognise what Python is doing. One tip up front: the muted grey text after a # in the code is a comment, a note for you that the computer ignores entirely (and this project comments generously, on purpose). A one-page Python primer at the end explains the handful of symbols that recur. Every code box is real, pulled straight from the project's Jupyter notebooks (code, notes, and live results in one document you run in your browser), which you can read and run yourself: the full source is on GitHub (with each notebook and a from-zero setup guide at the foot of the page).

Stage 1 · Orientation

0

What we're actually building

This page is the build. For what a model is and how it works (next-token prediction, tokens, embeddings, attention, training) see Part 0 · Concepts (no code); we lean on it throughout. The one thing worth restating here: a real model is the same idea at enormous scale, so building a tiny one where every part is visible teaches the shape of the whole field.

We do it in two passes, which separates knowing the parts from knowing what matters:

PassWhat it doesResult
Notebook 01 (from scratch) The simplest possible GPT, working one character at a time, built from raw parts so every moving piece is visible. English-shaped gibberish, on purpose. The goal is transparency, not quality.
Notebook 02 (tuned) Same architecture, plus the handful of upgrades that genuinely move quality (chiefly: working in word-chunks, not letters). Recognisable little stories, the ceiling of a from-scratch model on a laptop.

Stage 2 · Building it from scratch (notebook 01)

1

Setup: the toolbox

Every program starts by laying its tools on the bench. Here we load the array library, the neural-network building blocks, and the optimizer (the part that will adjust the model as it learns). One line prints the compute device, confirming the Mac's GPU is in play.

notebook 01
import math, time
import numpy as np
import mlx.core as mx
import mlx.nn as nn
import mlx.optimizers as optim
from mlx.utils import tree_flatten
import matplotlib.pyplot as plt

print("MLX device:", mx.default_device())   # should say Device(gpu, 0) on your M5
what this says

Reading it: the import lines bring in pre-written toolkits. np is NumPy, Python's classic, decades-old library for arrays of numbers, the workhorse under most of scientific computing (here it does a little data prep on the CPU). mx is MLX, Apple's array library that runs on the Mac's GPU; it's deliberately NumPy-like, so the two look almost identical in use. nn holds the neural-net building blocks (layers and such), and optim is the optimizer, the part that adjusts the model as it learns. The last line prints which device will run the maths; on an M-series Mac it reports the GPU.

2

Turning text into numbers

A model can't read letters; it does arithmetic. So the very first job is tokenisation, a fixed dictionary that maps text to whole numbers and back. Notebook 01 uses the simplest scheme imaginable: one number per character. Every distinct character it sees (every letter, space, comma) gets its own id. It's inefficient, but maximally transparent: you can see exactly what the model sees.

(Part 0 described a token as a word or word-piece; here we start one notch simpler, one token per character, for maximum transparency, then switch to word-chunks in §12.)

The text itself is TinyStories: thousands of very simple children's stories, written with a small vocabulary on purpose, so that a small model can actually learn coherent English from them.

notebook 01
# Pull a few thousand TinyStories. Streaming = we don't download the whole dataset.
N_STORIES = 4000
try:
    from datasets import load_dataset
    ds = load_dataset("roneneldan/TinyStories", split="train", streaming=True)
    stories = []
    for i, ex in enumerate(ds):
        stories.append(ex["text"].strip())
        if len(stories) >= N_STORIES:
            break
    text = "\n\n".join(stories)
    print(f"Loaded {len(stories)} stories from TinyStories.")
except Exception as e:
    # Fallback so the notebook never hard-fails (e.g. offline). Tiny + repetitive.
    print("Dataset load failed, using fallback corpus. Reason:", e)
    text = ("Once upon a time there was a little girl who lived near a big forest. "
            "Every day she walked to the river and played with her friend the fox. "
            "They liked to watch the birds and tell happy stories. ") * 2000
    stories = [text[:300]]

print(f"Total characters: {len(text):,}")
# Show one COMPLETE story rather than the first 300 characters, so the shape of a single
# training example is obvious. Any index works; this one is a charmer.
SAMPLE = 1
print(f"---- sample: story #{SAMPLE} of {len(stories):,} ----")
print(stories[SAMPLE][:300])
Stream a few thousand stories (no full download).
what this says

Reading it: N_STORIES = 4000 sets how many stories to grab. The try: / except: pair is a safety net (“attempt this; if anything goes wrong, do that instead”) so the notebook never hard-fails if you happen to be offline.

  • load_dataset(..., streaming=True): open the TinyStories dataset as a stream: pull stories one at a time on demand, rather than downloading the whole thing.
  • the for ... in ds: loop walks through the stream, tidies each story (.strip() trims stray whitespace) and adds it to a growing stories list. if len(stories) >= N_STORIES: break means “once we have 4,000, stop.”
  • text = "\n\n".join(stories) glues all the stories into one big string, with a blank line between each. That single string is the raw material everything downstream learns from.
  • the except branch only runs if the download failed; it swaps in a tiny built-in corpus so the rest of the notebook still works.

(The “unauthenticated requests” warning you'll see in the output below is harmless: the dataset is public and needs no login; setting a token just lifts rate limits.)

what it prints
Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.
Loaded 4000 stories from TinyStories.
Total characters: 3,394,018
---- sample: story #1 of 4,000 ----
Once upon a time, there was a little car named Beep. Beep loved to go fast and play in the sun. Beep was a healthy car because he always had good fuel. Good fuel made Beep happy and strong.

One day, Beep was driving in the park when he saw a big tree. The tree had many leaves that were falling. Bee

Now we build the dictionary and convert the entire corpus into one long ribbon of integers. The last 10% is held back as a validation set (text the model never trains on) which later lets us tell genuine learning apart from mere memorising.

notebook 01
chars = sorted(set(text))
vocab_size = len(chars)
stoi = {c: i for i, c in enumerate(chars)}
itos = {i: c for c, i in stoi.items()}

def encode(s): return [stoi[c] for c in s]
def decode(ids): return "".join(itos[int(i)] for i in ids)

data = np.array(encode(text), dtype=np.int32)
n_train = int(0.9 * len(data))
train_data, val_data = data[:n_train], data[n_train:]

print(f"vocab_size = {vocab_size} distinct characters")
print(f"the vocab:  {''.join(chars)!r}")
print(f"train tokens = {len(train_data):,}   val tokens = {len(val_data):,}")
print(f'encode("hi") = {encode("hi")}  ->  decode back = {decode(encode("hi"))!r}')
what this says

Line by line:

  • chars = sorted(set(text)) finds every distinct character and puts them in a fixed order. That ordered list is the vocabulary.
  • stoi / itos are two lookup tables: string-to-integer and back. (“a is 27,” “27 is a.”)
  • encode / decode are small recipes that run those lookups over a whole string. Encode turns text into numbers; decode turns numbers back into text.
  • train_data, val_data split the encoded ribbon 90/10. The model studies the first part and is tested on the held-out tail.
what it prints
vocab_size = 90 distinct characters
the vocab:  '\n !"$\',-.0123456789:;?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz¡¦©«±³»ÂÃ✘“”€™'
train tokens = 3,054,616   val tokens = 339,402
encode("hi") = [55, 56]  ->  decode back = 'hi'
3

The task: predict the next character

How do you turn “a long ribbon of numbers” into a learning task? You slice out short windows and set up a fill-in-the-blank exercise. For each window of text x, the correct answer y is the same window shifted one step to the right. So at every single position, the model's job is: “given everything up to here, what's the next character?” One window quietly contains hundreds of these little quizzes at once.

notebook 01
def get_batch(split):
    d = train_data if split == "train" else val_data
    ix = np.random.randint(0, len(d) - block_size - 1, size=batch_size)
    x = np.stack([d[i : i + block_size] for i in ix])
    y = np.stack([d[i + 1 : i + 1 + block_size] for i in ix])  # shifted by one
    return mx.array(x), mx.array(y)
Grab a stack of random windows; the target is shifted by one.
what this says

In plain terms: pick batch_size random starting points in the data. For each, take a window of block_size characters as the input x, and the same window slid one place forward as the answer y. Stacking many windows together (a “batch”) lets the GPU practise on all of them simultaneously, which is what makes training fast.

4

The dials (hyperparameters)

Before building the model we choose its size and how hard it will train. These are hyperparameters: settings we pick, as opposed to the millions of numbers the model will learn on its own. A founding principle of this lab is “no magic numbers,” so each one carries a note on what it does and which way to push it.

notebook 01
# --- reproducibility ---
# Seed both generators this notebook draws from: MLX initialises the weights, NumPy picks
# the training batches. Without this, every re-run trains a different model AND re-rolls the
# sample text below it — so the outputs committed here could never be reproduced. Same fix as
# notebook 02; see docs/DECISIONS.md ADR-0013.
SEED = 1337
mx.random.seed(SEED); np.random.seed(SEED)

# --- model shape ---
block_size = 128     # context length: chars of history the model conditions on. Bigger = more context, more compute.
n_embd     = 256     # width: size of each token's vector. Bigger = more capacity, slower.
n_head     = 8       # attention heads (must divide n_embd). More heads = more independent "relationships" learned.
n_layer    = 4       # depth: stacked transformer blocks. Deeper = more abstraction, more compute, harder to train.

# --- training ---
batch_size    = 48     # windows processed per step. Bigger = steadier gradients, more memory.
learning_rate = 3e-3   # step size for weight updates. Too high = unstable/NaN; too low = crawls.
max_steps     = 2500   # total update steps. More = lower loss (to a point) + longer wait.
eval_every    = 250    # how often we measure validation loss.

assert n_embd % n_head == 0, "n_head must divide n_embd"
print(f"context={block_size}  width={n_embd}  heads={n_head}  depth={n_layer}")
what this says

The four shape dials decide capacity: block_size is how far back the model can see; n_embd is how many numbers describe each token: that list of numbers is the token's vector (a vector being simply an ordered list of numbers, e.g. [0.31, -1.20, 0.05, …]) and n_embd (256) is how long it is (the token's “richness”); n_head is how many relationships attention tracks in parallel; n_layer is how many times the whole reasoning block is stacked (depth). The training dials (batch_size, learning_rate, max_steps) decide how steadily and how long it learns. Bigger or longer is generally better and always slower; the art is the balance.

5

Attention: the heart of it

This is the one idea that makes a transformer a transformer. Everything else is plumbing.

The intuition. To predict the next word, a position needs to pull in relevant context from earlier words, but which earlier words matters, and it depends on the sentence. In “the dragon looked at the boy and it…”, the word “it” should pay attention to “dragon.” Attention is the mechanism that lets every position decide, on the fly, how much to listen to each earlier position.

The standard analogy is a search. Each token emits three things:

  • a query: “here's what I'm looking for,”
  • a key: “here's what I'm about,” and
  • a value: “here's what I'll hand over if you attend to me.”

A token compares its query against every earlier token's key. Good matches get high attention; the token then takes a weighted blend of those tokens' values. Strong match → big say in the blend. That blend is how information moves between positions.

notebook 01
def causal_mask(T):
    # Lower-triangular 1s (allowed: current + past) -> 0; upper triangle (future) -> -1e9.
    # Added to attention scores before softmax, so future positions get ~0 weight.
    return (1 - mx.tril(mx.ones((T, T)))) * -1e9

class CausalSelfAttention(nn.Module):
    def __init__(self):
        super().__init__()
        self.c_attn = nn.Linear(n_embd, 3 * n_embd)  # one matmul produces query, key, value
        self.c_proj = nn.Linear(n_embd, n_embd)      # mixes the heads' outputs back together
        self.nh = n_head

    def __call__(self, x, mask):
        B, T, C = x.shape           # batch, time(context), channels(width)
        hd = C // self.nh           # per-head dimension
        q, k, v = mx.split(self.c_attn(x), 3, axis=-1)
        # split each into heads and move the head axis up front: (B, nh, T, hd)
        q = mx.transpose(q.reshape(B, T, self.nh, hd), (0, 2, 1, 3))
        k = mx.transpose(k.reshape(B, T, self.nh, hd), (0, 2, 1, 3))
        v = mx.transpose(v.reshape(B, T, self.nh, hd), (0, 2, 1, 3))
        # scores[i,j] = how much token i attends to token j  (scaled for stability)
        scores = (q @ mx.transpose(k, (0, 1, 3, 2))) * (1.0 / math.sqrt(hd)) + mask
        weights = mx.softmax(scores, axis=-1)        # turn scores into probabilities over past tokens
        out = weights @ v                            # weighted sum of values
        out = mx.transpose(out, (0, 2, 1, 3)).reshape(B, T, C)  # re-merge heads
        return self.c_proj(out)
The mask, then attention itself.
what this says

The mask (causal_mask) builds a grid where allowed (past) connections are 0 and forbidden (future) ones are a huge negative number. Added to the raw scores, those −1,000,000,000 entries become effectively zero probability after the next step: future tokens are silenced.

Inside the attention (__call__), reading the important lines:

  • q, k, v = mx.split(self.c_attn(x), 3, …): one matrix multiply produces all three vectors (query, key, value) for every token at once, then splits them apart.
  • the reshape/transpose lines split the work across several attention heads, so the model can track multiple kinds of relationship in parallel (one head might follow grammar, another who-did-what).
  • scores = q @ transpose(k) … + mask compares every query against every key (that's the match score), scales for stability, and adds the mask to block the future.
  • weights = mx.softmax(scores) turns raw scores into clean percentages that sum to 100% across the allowed past.
  • out = weights @ v is the weighted blend of values. This single line is where information actually flows between positions.
6

The block, and the whole model

Attention gathers information across positions. The other half of a transformer block is a small MLP (multilayer perceptron), also called the feedforward network: two linear layers with a nonlinear “bend” (a GELU activation) between them. The same learned weights are applied to each position independently, giving the model room to “think” about what attention just collected. A block is simply: attention, then MLP. A GPT is just this block stacked n_layer times.

Two supporting tricks make deep stacks trainable, and they're worth naming because they're everywhere in modern models:

  • Residual connections (x = x + sublayer(x)). Instead of replacing its input, each sub-layer adds an adjustment to it. This keeps a clean signal flowing through even a deep stack, which is what makes deep networks learnable at all.
  • LayerNorm: normalises the feature values within each token's vector, then applies learned scales and shifts. This helps keep the maths stable; it does not mix information between token positions.

Almost all of a block is two operations: a linear layer (y = Wx + b, a weighted sum) and a nonlinear activation (a “bend,” GELU here). Stacked with attention, an embedding at the bottom and a head at the top, that's the whole network. The why, with the diagrams (what a linear layer computes, what an embedding is, how the numbers form a “meaning space”) is in Part 0 · Concepts. Here we build the block in code.

notebook 01
class Block(nn.Module):
    def __init__(self):
        super().__init__()
        self.ln1 = nn.LayerNorm(n_embd)
        self.ln2 = nn.LayerNorm(n_embd)
        self.attn = CausalSelfAttention()
        self.mlp = nn.Sequential(
            nn.Linear(n_embd, 4 * n_embd), nn.GELU(), nn.Linear(4 * n_embd, n_embd)
        )
    def __call__(self, x, mask):
        x = x + self.attn(self.ln1(x), mask)   # residual + attention
        x = x + self.mlp(self.ln2(x))          # residual + MLP
        return x

class GPT(nn.Module):
    def __init__(self):
        super().__init__()
        self.tok = nn.Embedding(vocab_size, n_embd)   # token id -> vector
        self.pos = nn.Embedding(block_size, n_embd)   # position -> vector
        self.blocks = [Block() for _ in range(n_layer)]
        self.lnf = nn.LayerNorm(n_embd)
        self.head = nn.Linear(n_embd, vocab_size)     # vector -> score per next char
    def __call__(self, idx):
        B, T = idx.shape
        x = self.tok(idx) + self.pos(mx.arange(T))    # combine token + position info
        mask = causal_mask(T)
        for b in self.blocks:
            x = b(x, mask)
        return self.head(self.lnf(x))                 # logits: (B, T, vocab_size)

model = GPT()
mx.eval(model.parameters())   # MLX is lazy; this forces the weights to actually materialize
n_params = sum(p.size for _, p in tree_flatten(model.parameters()))
print(f"Model built: {n_params/1e6:.2f}M parameters")
One block, then the full GPT assembled from blocks.
what this says

The block is the two-line heart: x = x + self.attn(self.ln1(x), mask) (normalise, attend, add back) then x = x + self.mlp(self.ln2(x)) (normalise, think, add back). That “add back” is the residual connection.

The full GPT wires the ends on:

  • self.tok is an embedding table turning each token id into a vector of n_embd learnable numbers (its meaning, to be discovered during training).
  • self.pos is a second embedding for position: the token's index in the sequence (0, 1, 2, …). It looks up a learned vector for that index and adds it to the token's embedding vector, giving the model information about where the token sits.
  • self.blocks is the stack of transformer blocks, run in sequence.
  • self.head is a final layer that turns each position's vector into a score for every possible next character. Those scores are called logits; they're the model's raw opinion about what comes next.

The print line counts the model's learnable numbers, its parameters. This tiny one has about 3.2 million. (Frontier models have hundreds of billions: same parts, more of them.)

Running an input all the way through these layers to produce the logits (that whole left-to-right journey, model(idx)) is the model's forward pass (“forward propagation”). Right now it produces nonsense, because the weights are random. The next section is about fixing that, and the forward pass becomes step one of the loop that does it.

what it prints
Model built: 3.24M parameters

Our model, by the numbers

So how big is the thing we just built? (“How many neurons?” has no clean answer for a transformer: the honest measures are its width, its depth, and its parameter count.)

PropertyNotebook 01 (this model)
Transformer blocks, the depth (n_layer)4
Width, numbers describing each token (n_embd)256
Attention heads (n_head)8
MLP hidden units per block (4 × width)1,024
Total learnable parameters (every W and b)≈ 3.24 million

Where do those 3.24 million parameters live? Almost all (~3.16 million) are in the four blocks' Wx + b layers; only ~56k in the two embedding tables and ~24k in the output head. (Notebook 02 scales every row up to 6 blocks, width 384, ≈17 million, and that extra capacity is much of what makes its writing better.)

Two things about that number. First, it is the model's “size”, the same count meant by “a 7-billion-parameter model” (distinct from the file size on disk, which is roughly the count × a few bytes per number). Second, who picks those millions of values? Not us. We choose the architecture and the count, and start them as small random numbers; training then sets every value by gradient descent, nudging each toward whatever lowers the loss. So the process is no black box; it's the loop in the next section. What stays opaque is what any single parameter means: the knowledge is smeared across all of them, not stored in readable slots. We know precisely how they're set; we mostly can't read them, which is the open research field of interpretability.

7

Training: making the guesses less wrong

A freshly built model is random; its guesses are no better than chance. Training is the loop that fixes that: measure how wrong each guess is (the loss, read it as “surprise”), then nudge every parameter a little to lower it (gradient descent). The why (loss, gradients, backpropagation, the downhill-in-a-landscape picture) is in Part 0 · Concepts. Here is that loop, in code.

notebook 01
def loss_fn(model, x, y):
    logits = model(x)
    B, T, Vv = logits.shape
    return nn.losses.cross_entropy(logits.reshape(B * T, Vv), y.reshape(B * T)).mean()

def eval_val_loss(n_batches=20):
    losses = [loss_fn(model, *get_batch("val")).item() for _ in range(n_batches)]
    return sum(losses) / len(losses)

optimizer = optim.AdamW(learning_rate=learning_rate)
loss_and_grad = nn.value_and_grad(model, loss_fn)

print(f"loss at init = {loss_fn(model, *get_batch('train')).item():.3f}  "
      f"(uniform-guess baseline ~ ln(vocab) = {math.log(vocab_size):.3f})\n")

train_hist, val_hist = [], []   # (step, loss) records for the curve
t0 = time.time()
for step in range(1, max_steps + 1):
    x, y = get_batch("train")
    loss, grads = loss_and_grad(model, x, y)
    optimizer.update(model, grads)
    mx.eval(model.parameters(), optimizer.state)
    train_hist.append((step, loss.item()))
    if step % eval_every == 0 or step == 1:
        vl = eval_val_loss()
        val_hist.append((step, vl))
        print(f"step {step:4d}/{max_steps}  train {loss.item():.3f}  val {vl:.3f}  "
              f"({time.time()-t0:.0f}s elapsed)")
print(f"\nDone in {time.time()-t0:.0f}s.")
The loss function, then the training loop.
what this says

The loop is four steps, and every one is a line of code (the for step in range(...) block, plus the loss_fn above it):

  1. Forward pass: logits = model(x) (inside loss_fn). Run the batch of windows through the network to get its predictions. This is the same forward pass you met when we built the model.
  2. Loss: cross_entropy(...). Score how wrong those predictions are, the surprise, one number.
  3. Backward pass: loss, grads = loss_and_grad(model, x, y). Work backwards through the network to get the gradient for every parameter: which way to nudge each one to lower the loss. Doing this efficiently, end to end, is backpropagation, the central algorithm of deep learning. (One call returns both the loss and all the gradients.)
  4. Gradient-descent step: optimizer.update(model, grads). Take one small step downhill, every parameter at once. The step size is the learning_rate.

mx.eval(...) just tells the GPU to actually run all of that now (MLX is lazy by default). Repeat a couple of thousand times: each pass the model is microscopically less wrong, and in aggregate, language emerges.

watching it learn (loss falling)
loss at init = 4.672  (uniform-guess baseline ~ ln(vocab) = 4.500)

step    1/2500  train 4.657  val 4.000  (1s elapsed)
step  250/2500  train 2.507  val 2.530  (22s elapsed)
step  500/2500  train 2.441  val 2.455  (43s elapsed)
step  750/2500  train 2.369  val 2.392  (64s elapsed)
step 1000/2500  train 2.345  val 2.376  (86s elapsed)
step 1250/2500  train 2.328  val 2.349  (107s elapsed)
step 1500/2500  train 2.330  val 2.389  (128s elapsed)
step 1750/2500  train 2.390  val 2.372  (149s elapsed)
step 2000/2500  train 2.268  val 2.308  (172s elapsed)
step 2250/2500  train 2.270  val 2.295  (194s elapsed)
step 2500/2500  train 2.308  val 2.336  (216s elapsed)

Done in 216s.

Read that output top to bottom: the loss starts near the “knows nothing” baseline (~4.5) and falls fast to ~2.3 as the model picks up the statistics of English. The validation loss falls alongside the training loss: proof it's learning the language, not just memorising these particular stories.

8

The loss curve: the single most important plot

This plot has a name: the loss curve (sometimes learning curve). It is the loss from the last section, tracked across the whole training run, so don't confuse it with the loss function: the function is the formula that scores a single batch; the curve is that score plotted step after step. Reading it is how every practitioner judges the health of a run at a glance. The blue line is the training loss; the orange line (with dots) is the validation loss; the grey dashed line is the “knows nothing” baseline.

Notebook 01: both losses falling together toward the floor for a model this size.
Fig. 1Notebook 01: both losses falling together toward the floor for a model this size.
what this says

How to read it: a healthy run drops fast, then flattens. The crucial signal is the gap between the two lines. While validation loss keeps falling, the model is genuinely learning. If validation loss ever turned upward while training loss kept dropping, that widening gap would be overfitting: the model memorising its study material instead of learning the general pattern. Here both fall together: no overfitting, just the natural floor for a model this small.

9

Generating text, and the honest result

Now we let it write. Generation is a loop: feed in a prompt, look at the model's scores for the next character, turn them into probabilities, and sample one. Append it, then feed the whole thing back in and repeat. This one-step-at-a-time process is called autoregressive generation, and it's exactly how the largest models write too.

Once upon a time, there was a little boy ① the menu is scored ② the weighted die rolls ③ the pick joins the sentence step 1 of 6 — the menu for what comes next , 86.9% there 12.9% in 0.1% on <0.1% everything else (~8,000 chunks) 0.1% ▸, step 2 of 6 — the menu for what comes next there 98.7% a 0.7% in 0.4% the 0.1% everything else (~8,000 chunks) 0.1% ▸there step 3 of 6 — the menu for what comes next was 97.3% were 1.8% lived 0.9% is <0.1% everything else (~8,000 chunks) <0.1% ▸was step 4 of 6 — the menu for what comes next a 99.1% an 0.9% once <0.1% something <0.1% everything else (~8,000 chunks) <0.1% ▸a step 5 of 6 — the menu for what comes next little 81.1% boy 4.4% big 2.4% girl 2.3% everything else (~8,000 chunks) 9.8% ▸little step 6 of 6 — the die lands on the underdog girl 72.5% boy 19.5% bunny 2.7% bird 2.1% everything else (~8,000 chunks) 3.2% ▸boy outlined row = the die’s pick · click the figure to pause / resume Measured, not staged: the model’s real menus — the upgraded word-chunk checkpoint (§11–14) continuing the prompt at temperature 0.8. Step 6 is the lesson: sampling rolls a weighted die; it does not simply take the favourite. A 19.5% chunk wins about one roll in five, and this was that roll. Temperature (§17) sets how daring the die is. Reproduce it: gen_generation_trace.py (seed 3). , there was a little boy
Fig. 2The loop, replaying live (a slow ~47 s cycle): score the menu, roll the weighted die, watch the pick lift into the sentence, feed the whole line back in. Every probability is real — and so is step 6's surprise, where the die lands on a 19.5% underdog. That's what sampling means; §17 (temperature) is the dial that tunes it. Reproduce the trace: docs/walkthrough/gen_generation_trace.py.
notebook 01
def generate(prompt, n_new=400, temperature=0.7):
    idx = mx.array([encode(prompt)])
    for _ in range(n_new):
        logits = model(idx[:, -block_size:])[:, -1, :] / temperature
        next_id = mx.random.categorical(logits).reshape(1, 1)
        idx = mx.concatenate([idx, next_id], axis=1)
    return decode(idx[0].tolist())

print(generate("Once upon a time", n_new=400, temperature=0.7))
Predict one character, append, repeat.
what this says

Step by step: encode the prompt to numbers, then loop n_new times. Each pass takes the scores for the last position, divides by temperature (more on that under temperature, below), and mx.random.categorical rolls a weighted die to pick the next character (likelier characters chosen more often, but not always). Glue it on and continue.

what a from-scratch char-level model writes
Once upon a time and at ang anded he sitho an hen le, t so arerrd f s t ferey bit te s an huns.






Once a bo a ha an was athi s nd t to, nome s th t us t the bone f t't so to the mulare ton t t he is theak. She ryoute as t that'wamand t het bain her te ace fathil.


Me andad theled t s s m t are they t thed ze am l athe?" he foy ale oy tthe s id b t the tokele.
Son, The ap annd il pe s s aly thecheng hed w a t

Stage 3 · The upgrades that move quality (notebook 02)

10

The upgrades that move quality

This stage exists because the last one disappointed. Notebook 01 did exactly what it was designed to do — every part visible, nothing hidden — and then produced text nobody could read. That raised the obvious question: what is actually holding it back? The question came from the output, not from the plan.

Notebook 02 keeps the same transformer design, with a wider, deeper model, and combines six changes in one run. The comparison shows what the bundle achieves; it does not isolate how much each change contributes. That would require controlled comparisons, changing one thing at a time.

UpgradeNotebook 01Notebook 02Why it helps
Tokenizerone per character8k word-chunks (BPE) the big win: the model reasons in word-pieces, not letters
Weight initframework defaultscaled init stops a deep stack from blowing up at the start
Learning rateconstantwarm-up → decay reliably reaches a lower final loss
Gradient clippingnoneclip to a limit insurance against sudden training blow-ups
Capacity / context3.2M params, 12817M params, 256 more room to learn; a whole story fits in view
Training corpus4,000 stories25,000 stories more text to learn from; a one-line change to the loader

Why 8,192 tokens, 384 embedding dimensions and six layers? These were practical design choices, refined after seeing the first model’s output; we did not establish that they were optimal. In a production project, a team would start by defining what the model needs to do and the limits on data, training compute, memory and response time. It would use experience and prior research to choose a baseline, then run targeted comparisons: does a different tokenizer represent the text more efficiently, does extra depth improve performance enough to justify its cost, or would the same budget be better spent on more training data? Evaluations on unseen examples and realistic tasks would guide those decisions. The aim is to find a design that meets the application’s needs reliably within its constraints. Our small model illustrates the training mechanics; a production development process adds the evidence needed to justify the design.

11

Inside the tuned model: architecture & parameters

Before looking at the individual upgrades, put their model in view. Notebook 02 uses 8,192 tokens, a width of 384 and six transformer blocks. Those dimensions describe different parts of the same path from text to a next-token prediction.

  1. 1 · Embed Token + position

    Look up the two learned vectors and add them.

    384 values per token position
  2. 2 · Process Six transformer blocks

    Attention shares context; the MLP transforms each position.

    384 values in and out of each block
  3. 3 · Predict Normalise, then score

    Final LayerNorm, then the separate output head.

    8,192 scores; softmax gives probabilities, sampling picks the next token
The model reuses this path for every next-token prediction. The six blocks have the same structure and separate learned weights.

Where all 17.05 million parameters live

8,192 tokens × 384 numbers = 3,145,728 parameters counts only the token embedding table. The position table, six blocks, final normalisation and separate output head bring the total to 17,045,504. This is Notebook 02's tuned model, separate from Notebook 01's smaller character-level model in §6.

ComponentCalculationParameters
Token embeddings8,192 × 3843,145,728
Learned position embeddings256 × 38498,304
Six transformer blocks6 × 1,774,46410,646,784
Final layer normalisation2 × 384768
Separate output head384 × 8,192 + 8,192 biases3,153,920
TotalAll five components17,045,504 ≈ 17.05 million

The transformer blocks hold most of the parameters. All six have the same architecture and parameter count, but each block has its own learned weights. Within a block, those weights are shared across token positions: there is no separate set for every token.

Inside each transformer block

Every block receives and returns 384 values per token position. The flowing vectors are activations: values computed from the current input using the learned parameters. They are not another set of learned weights. Each block contains attention and a feedforward MLP, with normalisation and a residual connection around each stage.

First · Gather context
NormAttention+
incoming vector

Use information from the current and earlier positions, never future tokens.

Then · Transform features
NormMLP+
this stage’s incoming vector

The same feedforward weights work on each position independently.

384 → 1,536 → 384; GELU between the layers
Each stage normalises its input, computes an adjustment, then adds that stage's incoming vector back. This addition is the residual connection. The MLP is one part of the block.

The MLP expands 384 values to 1,536 and brings them back to 384. Together, attention, the MLP and the two layer norms contain 1,774,464 parameters per block. Six blocks account for 10,646,784 of the model's parameters. The full reference breaks down the matrices, biases and layer norms and explains how width, depth, heads and context affect the count.

After the blocks, final LayerNorm and a separate output head produce 8,192 scores. At generation time, softmax turns the last position's temperature-adjusted scores into probabilities, and sampling chooses the next token. The output-head reference explains why its 384-to-8,192 shape means 3,153,920 learned parameters.

With that structure in mind, the next sections return to the upgrades themselves: first the tokenizer, then initialization and the training schedule.

12

The big win: word-chunks, not letters

Working one character at a time forces the model to waste most of its capacity re-learning how to spell. Real models (and notebook 02) use sub-word tokenisation, specifically BPE (Byte-Pair Encoding). Starting from raw bytes (essentially the individual characters), BPE repeatedly merges the most common adjacent pair into a single new token. After enough merges, frequent chunks like " the", "ing", or " robot" each become one token. The model then reasons over meaningful units, and coherence appears far faster at the same size.

Crucially, we train the tokenizer on our own corpus, so all 8,192 tokens are relevant to these stories: no wasted vocabulary.

notebook 02
tok = Tokenizer(models.BPE(unk_token="[UNK]"))
tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=True)
tok.decoder = decoders.ByteLevel()
trainer = trainers.BpeTrainer(vocab_size=8192, special_tokens=["[UNK]"], show_progress=False)

t0 = time.time()
tok.train_from_iterator([text], trainer)
vocab_size = tok.get_vocab_size()
print(f"Trained BPE in {time.time()-t0:.1f}s — vocab_size = {vocab_size}")

data = np.array(tok.encode(text).ids, dtype=np.int32)
n_train = int(0.9 * len(data))
train_data, val_data = data[:n_train], data[n_train:]
print(f"tokens: {len(data):,}  (compression {len(text)/len(data):.1f} chars/token)")
print(f"train {len(train_data):,}  val {len(val_data):,}")
print("example tokens for ' Once upon a time':", tok.encode(" Once upon a time").ids)
print("roundtrip:", repr(tok.decode(tok.encode(" Once upon a time, the fox ran.").ids)))
Train a byte-level BPE tokenizer on the corpus.
what this says

What's happening: set up a BPE tokenizer, then train_from_iterator learns the merges from our text, building an 8,192-token vocabulary. We then re-encode the whole corpus with it. The print-outs report the compression ratio (characters per token) and a round-trip check (encode then decode gets the original text back). At ~4 characters per token, sequences are roughly 4× shorter, so the model effectively sees 4× more story within the same context window.

what it prints
Trained BPE in 3.6s — vocab_size = 8192
tokens: 5,478,621  (compression 4.1 chars/token)
train 4,930,758  val 547,863
example tokens for ' Once upon a time': [5381, 284, 103, 240]
roundtrip: ' Once upon a time, the fox ran.'
13

Init & stability: why deep stacks blow up

The model code in notebook 02 is the same architecture, but with one substantive change: how the parameters start out. With a deeper stack, the framework's default starting values can make the loss rise in the first steps. The reason is the residual connections we praised earlier: every block adds its output back into the running signal, so without damping, the signal compounds layer over layer and explodes.

The fix is the standard recipe: start all weights from a narrow random spread, and specifically shrink the output of each block's residual path by a factor that depends on depth. Tiny change, decisive effect.

notebook 02
STD = 0.02
def _normal(shape, std=STD): return mx.random.normal(shape) * std

class CausalSelfAttention(nn.Module):
    def __init__(self):
        super().__init__()
        self.c_attn = nn.Linear(n_embd, 3*n_embd); self.c_proj = nn.Linear(n_embd, n_embd); self.nh = n_head
        self.c_attn.weight = _normal(self.c_attn.weight.shape); self.c_attn.bias = mx.zeros((3*n_embd,))
        # residual projection: extra 1/sqrt(2*n_layer) damping
        self.c_proj.weight = _normal(self.c_proj.weight.shape, STD/math.sqrt(2*n_layer)); self.c_proj.bias = mx.zeros((n_embd,))
    def __call__(self, x, mask):
        B,T,C = x.shape; hd = C//self.nh
        q,k,v = mx.split(self.c_attn(x), 3, axis=-1)
        q = mx.transpose(q.reshape(B,T,self.nh,hd),(0,2,1,3))
        k = mx.transpose(k.reshape(B,T,self.nh,hd),(0,2,1,3))
        v = mx.transpose(v.reshape(B,T,self.nh,hd),(0,2,1,3))
        att = mx.softmax((q @ mx.transpose(k,(0,1,3,2)))*(1/math.sqrt(hd)) + mask, axis=-1)
        return self.c_proj(mx.transpose(att @ v,(0,2,1,3)).reshape(B,T,C))

class Block(nn.Module):
    def __init__(self):
        super().__init__()
        self.ln1=nn.LayerNorm(n_embd); self.ln2=nn.LayerNorm(n_embd); self.attn=CausalSelfAttention()
        l1=nn.Linear(n_embd,4*n_embd); l2=nn.Linear(4*n_embd,n_embd)
        l1.weight=_normal(l1.weight.shape); l1.bias=mx.zeros((4*n_embd,))
        l2.weight=_normal(l2.weight.shape, STD/math.sqrt(2*n_layer)); l2.bias=mx.zeros((n_embd,))  # residual proj
        self.mlp=nn.Sequential(l1, nn.GELU(), l2)
    def __call__(self, x, mask):
        x = x + self.attn(self.ln1(x), mask)
        x = x + self.mlp(self.ln2(x))
        return x

class GPT(nn.Module):
    def __init__(self):
        super().__init__()
        self.tok=nn.Embedding(vocab_size,n_embd); self.pos=nn.Embedding(block_size,n_embd)
        self.tok.weight=_normal(self.tok.weight.shape); self.pos.weight=_normal(self.pos.weight.shape)
        self.blocks=[Block() for _ in range(n_layer)]; self.lnf=nn.LayerNorm(n_embd)
        self.head=nn.Linear(n_embd,vocab_size); self.head.weight=_normal(self.head.weight.shape); self.head.bias=mx.zeros((vocab_size,))
    def __call__(self, idx):
        B,T = idx.shape
        x = self.tok(idx) + self.pos(mx.arange(T))
        mask = (1 - mx.tril(mx.ones((T,T)))) * -1e9
        for b in self.blocks: x = b(x, mask)
        return self.head(self.lnf(x))

model = GPT(); mx.eval(model.parameters())
n_params = sum(p.size for _,p in tree_flatten(model.parameters()))
print(f"Model: {n_params/1e6:.1f}M parameters  (uniform-guess baseline ln(vocab) = {math.log(vocab_size):.2f})")
Same architecture, now with scaled initialisation.
what this says

What to notice (you don't need every line): _normal(...) sets a parameter's starting values to small random numbers. The important detail is the STD / math.sqrt(2 * n_layer) on the c_proj and second MLP layer, the two places where each block writes back into the residual stream. Scaling those down by an amount that grows with depth keeps the signal's size stable from the first layer to the last. Everything else (attention, the block, the embeddings, the head) is identical to notebook 01.

model size
Model: 17.0M parameters  (uniform-guess baseline ln(vocab) = 9.01)
14

A smarter training schedule

Two upgrades live in the training loop. Both are about stability: letting us train harder without things breaking.

  • Learning-rate schedule. Instead of a constant step size, we warm up (start near zero and ramp up over the first stretch; a cold, random model hates big steps), then cosine-decay smoothly back down. The gentle landing lets the model settle into a better solution.
  • Gradient clipping. Before each update, if the proposed change is freakishly large, scale it back to a ceiling. Cheap insurance against one bad batch blowing up the run.
notebook 02
def loss_fn(model, x, y):
    logits = model(x); B,T,V = logits.shape
    return nn.losses.cross_entropy(logits.reshape(B*T,V), y.reshape(B*T)).mean()

def eval_val_loss(n=20):
    return sum(loss_fn(model, *get_batch("val")).item() for _ in range(n)) / n

# schedule: linear warmup, then cosine decay
warm  = optim.linear_schedule(0.0, peak_lr, warmup)
cos   = optim.cosine_decay(peak_lr, max_steps - warmup, end_lr)
sched = optim.join_schedules([warm, cos], [warmup])
optimizer = optim.AdamW(learning_rate=sched, weight_decay=weight_decay)
loss_and_grad = nn.value_and_grad(model, loss_fn)

train_hist, val_hist, lr_hist = [], [], []
t0 = time.time()
for step in range(1, max_steps + 1):
    x, y = get_batch("train")
    loss, grads = loss_and_grad(model, x, y)
    grads, gnorm = optim.clip_grad_norm(grads, grad_clip)   # <-- gradient clipping
    optimizer.update(model, grads)
    mx.eval(model.parameters(), optimizer.state)
    train_hist.append((step, loss.item())); lr_hist.append((step, optimizer.learning_rate.item()))
    if step % eval_every == 0 or step == 1:
        vl = eval_val_loss(); val_hist.append((step, vl))
        print(f"step {step:4d}/{max_steps}  train {loss.item():.3f}  val {vl:.3f}  "
              f"lr {optimizer.learning_rate.item():.2e}  ({time.time()-t0:.0f}s)")
print(f"\nDone in {(time.time()-t0)/60:.1f} min.")
Warm-up + cosine decay, plus gradient clipping.
what this says

The new parts vs notebook 01: the three schedule lines build the learning-rate curve (ramp up, then ease down), handed to the optimizer instead of a fixed number. Inside the loop, optim.clip_grad_norm(grads, grad_clip) is the one extra line, which caps the size of each update. The rest of the loop is the same grab-batch → measure → nudge rhythm from before.

Left: a longer, steadier descent than notebook 01. Right: the learning rate ramping up, then decaying.
Fig. 3Left: a longer, steadier descent than notebook 01. Right: the learning rate ramping up, then decaying.
what this says

The right-hand panel is the schedule made visible: the rate climbs during warm-up, then follows a smooth cosine curve down to its floor. The left panel shows the payoff: a cleaner, deeper descent than the constant-rate run. (The loss values aren't directly comparable to notebook 01's, because the vocabulary is different now; it's the shape that matters.)

15

The payoff: from gibberish to little stories

Same generation loop as before, but now each step samples a word-chunk, not a single letter. Here is what the tuned model writes, at two different temperatures:

the tuned model at two temperatures — generated from the saved checkpoint that chat.py loads, at the seeds shown, so you can reproduce them exactly
--- temperature 0.6 (seed 13) ---
Once upon a time, there was a boy named Timmy. Timmy loved to play outside in the sunshine. One day, Timmy's mom gave him a bag of candy. Timmy was so happy!

At the store, Timmy saw a big, shiny jar of candy. He wanted to buy it, but he had an idea. He took a bite and it tasted really yummy. Timmy ate the candy and felt very happy.

After he finished eating, Timmy's dad gave him a big hug. Timmy was so happy and ate the candy. He had a great time playing with his toys and playing with his friends. The end.

--- temperature 0.9 (seed 0) ---
Once upon a time there was a little boy named Jack. Jack was three years old and loved to explore. One day, Jack was very excited to go on an adventure with his mom. As he walked through the park, he spotted something shiny in the grass. Jack opened it, and saw a silver necklace! He was very excited.

Suddenly, Jack heard a voice! Jack's dad looked at it. He said: "What is that pretty things?". Jack smiled, "I'm going to catch the necklace and enjoy it!"

Jack took the necklace home and he took it home with him. He said: "This is my precious present for you at home!" Jack was so excited he couldn't wait to get married!
16

The honest ceiling, and where this leads

Even fully tuned, this is a 17-million-parameter model that trained for about twenty minutes on simple children's stories. It will produce believable words and short phrases, never reasoning or reliable facts. That gap, between “looks like language” and “is actually useful,” is exactly the gap a pretrained model closes: it has already done the equivalent of this training across trillions of tokens and thousands of GPU-hours.

And that is the whole point of building the tiny one first. You've now seen, in real code, every mechanism a frontier model uses: tokenisation, embeddings, attention, the transformer block, the loss, backpropagation, the optimizer, sampling. The giants are not different in kind. They are this, scaled.

Stage 4 · Use the thing you built (notebook 03)

17

Using the model you built

Training took twenty-odd minutes. You should only ever pay that once. The last cell of notebook 02 saves the trained model (its parameters, its tokenizer, and its configuration) to a folder on disk. After that, a separate, tiny program can reload it in under a second and generate text without any retraining at all.

notebook 02
# --- Save this trained model so you never retrain just to *use* it ---
# Writes weights + tokenizer + config to notebooks/checkpoints/tiny_gpt_v2/ (gitignored).
# Reload it in ~1s anywhere with:  model, tok, cfg = tiny_gpt.load("checkpoints/tiny_gpt_v2")
# (that's what notebook 03 and chat.py do). tiny_gpt.GPT is a structural twin of the
# GPT class above, so the saved weights load straight back in.
import tiny_gpt
CKPT_DIR = "checkpoints/tiny_gpt_v2"
cfg = dict(block_size=block_size, n_embd=n_embd, n_head=n_head, n_layer=n_layer, vocab_size=vocab_size)
tiny_gpt.save_checkpoint(model, tok, cfg, CKPT_DIR)
# Print the RELATIVE path: save_checkpoint returns an absolute one, and this notebook's
# outputs are committed to a public repo — no local filesystem paths in the trail.
print("saved checkpoint →", CKPT_DIR)
Save the trained model so you never retrain just to use it.
what this says

What's happening: bundle up the three things you need to reuse a model (the learned weights, the tokenizer so new text is chunked the same way, and the config, the shape of the model) and write them to a checkpoint folder. That trio is, in miniature, exactly what “downloading a model” gives you anywhere.

Reloading is the mirror image. A small library, tiny_gpt.py, rebuilds the model from the config, pours the saved weights back in, and loads the tokenizer:

tiny_gpt.py
def load(ckpt_dir):
    """Load a saved checkpoint. Returns (model, tokenizer, cfg). Takes ~1s, no training."""
    ckpt = Path(ckpt_dir)
    cfg = SimpleNamespace(**json.load(open(ckpt / "config.json")))
    model = GPT(cfg)
    model.load_weights(str(ckpt / "weights.safetensors"))
    mx.eval(model.parameters())
    model.eval()  # inference mode (no dropout etc.)
    tok = Tokenizer.from_file(str(ckpt / "tokenizer.json"))
    return model, tok, cfg
tiny_gpt.load: rebuild and reload in under a second.
what this says

The shape of it: read the config, construct an empty model of that shape, load_weights fills it with the trained numbers, and the tokenizer is read back from its file. model.eval() flips it into inference mode. From here, generating text is instant.

notebook 03
import time
import tiny_gpt   # local module (notebooks/tiny_gpt.py) — the model class + load/generate

t0 = time.time()
model, tok, cfg = tiny_gpt.load("checkpoints/tiny_gpt_v2")
print(f"loaded in {time.time()-t0:.2f}s  |  config = {vars(cfg)}")
In a notebook: load once, then generate freely.
what this says

In plain terms: one line, tiny_gpt.load("checkpoints/tiny_gpt_v2"), does all the rebuilding above and hands back three things: the model, its tokenizer, and its cfg (configuration). The time calls around it just measure how long it took, to make the point: a fraction of a second, versus the twenty minutes of training. Load once at the top of a session, then generate as often as you like.

load time
loaded in 0.01s  |  config = {'block_size': 256, 'n_embd': 384, 'n_head': 6, 'n_layer': 6, 'vocab_size': 8192, 'eos_token': '<|endstory|>'}
18

The one knob worth feeling: temperature

You met temperature in the generation code. It's the single most tangible dial in all of language modelling, and the cheapest to experiment with: no retraining, just re-run. It controls how boldly the model samples: low temperature makes it play it safe (pick the likeliest token almost every time, coherent but repetitive); high temperature makes it adventurous (give unlikely tokens a real chance, creative but loopier).

notebook 03
for temp in (0.4, 0.7, 1.0, 1.2):
    print(f"--- temperature {temp} ---")
    print(tiny_gpt.generate(model, tok, cfg, "Once upon a time", n_new=120, temperature=temp))
    print()
Same prompt, rising temperature.
what this says

What's happening: run the same opening at four temperatures and print each. Reading the results from low to high, you can watch the text loosen: tighter and more repetitive at 0.4, freer and stranger by 1.2. It's the most direct way to feel what sampling does, and the same knob you'll find in every model's API.

There's also a small terminal program, chat.py, that wraps all of this into an interactive prompt: type an opener, watch the story stream in token by token, adjust the temperature on the fly. It's the from-scratch model turned into something you can actually play with.

19

Knowing when to stop: the end-of-story token

You can now generate text and shape it with temperature, but how does the model know when a story is over? Left alone, it never stops: it just keeps predicting the next token until you cut it off at a token limit. So every reply comes out the same length, and a long one runs two stories together.

The fix is the one every real language model uses: a dedicated end-of-text token (GPT-2 calls it <|endoftext|>; here it's <|endstory|>). A tempting shortcut is to treat the blank line between stories as the boundary, but that fails, because the blank line is also the paragraph break inside almost every story, so the model can't tell “end of paragraph” from “end of story.” A reserved token that appears only between stories has no such ambiguity.

train_v2_checkpoint.py
trainer = trainers.BpeTrainer(vocab_size=8192, special_tokens=["[UNK]", EOS], show_progress=False)
t0 = time.time()
tok.train_from_iterator([text], trainer)
tok.add_special_tokens([EOS])           # match "<|endstory|>" atomically when encoding
eos_id = tok.token_to_id(EOS)
cfg.vocab_size = tok.get_vocab_size()
print(f"Trained BPE in {time.time()-t0:.1f}s — vocab_size={cfg.vocab_size}  eos_id={eos_id}")

# Build the token stream story-by-story, dropping the eos token after each.
ids = []
for s in stories:
    ids.extend(tok.encode(s).ids)
    ids.append(eos_id)
data = np.array(ids, dtype=np.int32)
Reserve a special token, then drop it after every story in the training stream.
what this says

What's happening: we add <|endstory|> to the tokenizer as a special token (matched as one atomic unit, never split into characters) then build the training stream story-by-story, appending that token's id after each one. The model now sees, thousands of times over, that a finished story is followed by this exact marker. So it learns to produce it precisely when a story is complete.

tiny_gpt.py
def stream(model, tok, cfg, prompt, n_new=200, temperature=0.8, stop_at_eos=True):
    """Yield text deltas as tokens are produced — for a live 'typing' feel.

    Stops when the model emits its end-of-story token (if it has one and stop_at_eos=True),
    or after at most `n_new` tokens. Set stop_at_eos=False to keep going past story ends.
    """
    eos = _eos_id(tok, cfg) if stop_at_eos else None
    out = list(tok.encode(prompt).ids)
    idx = mx.array([out])
    prompt_text = tok.decode(out)
    emitted = 0  # chars of generated (post-prompt) text already yielded
    for _ in range(n_new):
        logits = model(idx[:, -cfg.block_size:])[:, -1, :] / temperature
        next_id = int(mx.random.categorical(logits).item())
        if next_id == eos:          # story finished — stop before emitting the marker
            return
        idx = mx.concatenate([idx, mx.array([[next_id]])], axis=1)
        out.append(next_id)
        gen = tok.decode(out)[len(prompt_text):]
        if len(gen) > emitted:
            yield gen[emitted:]
            emitted = len(gen)
At generation time, stop the instant that token appears.
what this says

The payoff in code: each step samples the next token; if it's the end-of-story token we return immediately (before emitting it) so the story ends cleanly on its last real word. If the model never emits it, the n_new cap still ends things eventually. That single check is the whole mechanism behind “the model decided it was done.”

a complete story from chat.py: it stopped on its own at <|endstory|> after ~147 tokens, well short of the 300-token cap (seed 1, temp 0.8)
Once upon a time, there was a little girl named Lily. She loved to play outside in the sunshine. One day, she went to the park with her mom and saw lots of things. The grass was red and blue. 

Lily saw a bird and asked her mom, "Can we get some fresh apples?" 

Her mom replied, "Yes, but be careful not to reach the fruits and juice far away." 

Lily got a long stick and took a big bite. It was so fun, her mom said, "Lily, it is sour! You need to eat lots of apples!" 

Lily thought for a moment and then said, "Thank you, Mommy! I love the apples all!"

Reference appendix

↪

Python primer

You don't need this to follow the walk-through; the “what this says” boxes translate everything. But if you want to read the code itself, here are the few patterns that show up again and again. Learn these seven and Python stops looking like noise.

# a comment, like this
A comment. Anything from a # to the end of the line is ignored by the computer entirely: it's a note for the human reader, nothing more. In the dark code boxes, comments are the muted grey text. This project comments heavily on purpose (the “no magic numbers” rule: every setting carries a note on what it does), so a good share of what you'll see in the code is notes, not instructions.
name = something
Assignment. Give a value a name so you can refer to it later. vocab_size = 90 means “from now on, vocab_size is 90.” The = is “set to,” not “equals” in the maths sense.
def do_thing(a, b):
Define a function, a named, reusable recipe. a, b are its inputs. Everything indented underneath belongs to it. Later, do_thing(2, 3) runs the recipe with those inputs.
class GPT:
A blueprint for an object that bundles data and behaviour together. The model itself is one of these. __init__ is the setup that runs once when the object is created; __call__ is “what happens when you use it like a function”; so model(x) runs the model on input x.
for item in things:
A loop. Do the indented steps once for each item: the engine of training (“for each step, improve a little”) and of generation (“for each new word, predict one”).
[ ... ] and indentation
Square brackets make a list (an ordered collection). Indentation is meaningful in Python: the spaces aren't decoration, they show what belongs inside a function, loop, or block.
x @ y and “shapes”
The data flowing through the model lives in arrays, grids of numbers. An array's shape is its dimensions, e.g. (B, T, C) = (how many examples at once, how many positions in each, how many numbers per position). @ is matrix multiplication, the bulk-arithmetic operation that does almost all the work in a neural network. mx is Apple's array library (MLX); think “the thing that does fast maths on the GPU.”