Skip to content

Train nanoGPT from scratch

This character-level GPT learns to predict the next character in a short passage. For the fragment para, one training sequence has inputs p a r and targets a r a. At the second position, the model can see p a and must predict r. A causal mask enforces that rule even though the model computes predictions for every position at once.

The six Python blocks below make one complete file. You can copy them in order into train_gpt.py and run python train_gpt.py, or run the same file from the repository. To run the repository version, use Python 3.11 or newer and a C compiler.

git clone https://github.com/iskandr/parakeet.git
cd parakeet
python -m pip install -e .
python -m examples.nanogpt

The text is embedded in the script. The default run trains on batches of 16 sequences, each 32 characters long, for 60 steps.

Normalize one position at a time

One input sequence becomes a matrix of shape (context, width). Each row holds one character's embedding. layer_norm normalizes across the features of that row. Later, each row passed to softmax contains the attention scores from one position to every position in the sequence. Subtracting the row maximum keeps the exponential stable.

"""A character-level GPT trained with parakeet.value_and_grad.

The model is a function over a tuple of parameter arrays: token and position
embeddings, a stack of pre-norm transformer blocks (causal self-attention and
an MLP), and a linear head.  ``value_and_grad`` differentiates the loss of a
batch with respect to all of them, and plain Python applies Adam.
"""

import time

import numpy as np

import parakeet

N_HEAD = 2


def layer_norm(x, gain, bias):
  mu = np.mean(x, axis=1, keepdims=True)
  var = np.mean((x - mu) ** 2, axis=1, keepdims=True)
  return (x - mu) / np.sqrt(var + 1e-5) * gain + bias


def softmax(x):
  e = np.exp(x - np.max(x, axis=1, keepdims=True))
  return e / np.sum(e, axis=1, keepdims=True)

Mix information across visible characters

Each attention head uses part of the model width. For each position, q represents what it is looking for, k what each position can match, and v what that position contributes. Their score matrix has shape (context, context). In the para example, row two may give weight to the first two inputs. The mask suppresses the score of the third before softmax.

The heads contribute to a shared output through wo. A transformer block adds this attention output back to its input. It then applies a two-layer network to each position and adds that result back too.

def attention(x, wq, wk, wv, wo, causal):
  """Causal self-attention over one sequence: x is (T, C)."""
  head_width = x.shape[1] // N_HEAD
  q, k, v = x @ wq, x @ wk, x @ wv
  out = x * 0.0
  for h in range(N_HEAD):
    lo, hi = h * head_width, (h + 1) * head_width
    scores = q[:, lo:hi] @ k[:, lo:hi].T / np.sqrt(head_width)
    weights = softmax(np.where(causal, scores, -1e9))
    # Add this head’s contribution to the output embedding.
    out = out + (weights @ v[:, lo:hi]) @ wo[lo:hi]
  return out


def block(x, p, causal):
  g1, b1, wq, wk, wv, wo, g2, b2, w1, c1, w2, c2 = p
  x = x + attention(layer_norm(x, g1, b1), wq, wk, wv, wo, causal)
  h = np.tanh(layer_norm(x, g2, b2) @ w1 + c1)
  return x + h @ w2 + c2

Score one sequence, then a batch

wte[tokens] looks up one embedding per character ID. Adding wpe gives each position its own embedding as well. After the transformer blocks, the output matrix head maps each position to one score per character in the vocabulary. sequence_loss converts those scores to log probabilities, picks the entry for the actual next character at each position, and averages the negative values.

In loss, both tokens and targets have shape (batch, context). The two arguments to loss_for_sequence are matching rows, and every sequence shares the same params and causal mask. parakeet.map maps loss_for_sequence across the batch to produce one scalar loss per sequence, and np.mean averages them into the batch loss. parakeet.value_and_grad(loss) compiles a function returning both that scalar loss and its gradient with respect to params (the first argument of loss).

def sequence_loss(params, tokens, targets, causal):
  wte, wpe, blocks, gf, bf, head = params
  x = wte[tokens] + wpe
  for p in blocks:
    x = block(x, p, causal)
  logits = layer_norm(x, gf, bf) @ head
  z = logits - np.max(logits, axis=1, keepdims=True)
  logp = z - np.log(np.sum(np.exp(z), axis=1, keepdims=True))
  return -np.mean(logp[np.arange(len(targets)), targets])


def loss(params, tokens, targets, causal):
  def loss_for_sequence(input_ids, next_ids):
    return sequence_loss(params, input_ids, next_ids, causal)

  per_sequence = parakeet.map(loss_for_sequence, tokens, targets)
  return np.mean(per_sequence)


loss_and_grad = parakeet.value_and_grad(loss)

Build the parameter arrays

init constructs the tuple that sequence_loss unpacks. In order, it contains the token embedding table, the position embedding table, the tuple of transformer blocks, the final normalization gain and bias, and the output matrix. With the defaults, the token embedding table has shape (vocab, 32) and the output matrix has shape (32, vocab).

Inside one_block, the first gain and bias normalize the input to attention. The next four matrices project queries, keys, values and the combined output. A second gain and bias precede the two weight–bias pairs of the position-wise network. This is the order in which block unpacks them.

def init(vocab, context, width, layers, rng):
  def w(*shape):
    return rng.normal(0.0, 0.02, shape)

  def one_block():
    ones, zeros = np.ones(width), np.zeros(width)
    return (
      ones, zeros, w(width, width), w(width, width), w(width, width), w(width, width),
      ones.copy(), zeros.copy(), w(width, 4 * width), np.zeros(4 * width), w(4 * width, width), zeros.copy(),
    )  # fmt: skip

  blocks = tuple(one_block() for _ in range(layers))
  return (w(vocab, width), w(context, width), blocks, np.ones(width), np.zeros(width), w(width, vocab))

Update every parameter with Adam

A call to loss_and_grad returns the batch loss and a gradient array for each parameter array. The gradients follow the same nested tuple structure as the parameters. tree_map walks corresponding leaves together so Adam can update an embedding, a bias or a projection matrix with the same formula. m tracks a moving average of the gradients and v tracks a moving average of their squares. Both travel with the parameters into the next step.

def tree_map(f, *trees):
  if isinstance(trees[0], tuple):
    return tuple(tree_map(f, *parts) for parts in zip(*trees))
  return f(*trees)


def adam(params, grads, m, v, step, lr=3e-3, b1=0.9, b2=0.99):
  m = tree_map(lambda m, g: b1 * m + (1 - b1) * g, m, grads)
  v = tree_map(lambda v, g: b2 * v + (1 - b2) * g * g, v, grads)
  scale = lr * np.sqrt(1 - b2**step) / (1 - b1**step)
  params = tree_map(lambda p, m, v: p - scale * m / (np.sqrt(v) + 1e-8), params, m, v)
  return params, m, v


def train_step(params, m, v, step, tokens, targets, causal):
  value, grads = loss_and_grad(params, tokens, targets, causal)
  params, m, v = adam(params, grads, m, v, step)
  return value, params, m, v

Train on shifted character windows

main assigns one integer ID to each distinct character in TEXT. For a sample starting at offset i, tokens starts at i and targets starts at i + 1. Stacking those windows gives the two arrays consumed by the batch map. The lower triangle of causal includes the diagonal, so a position can read its own input when predicting the following character.

TEXT = (
  "parakeet compiles numerical python. it fuses array expressions into loops, "
  "runs them on every core, and now differentiates them too. "
) * 8


def main(steps=60, batch=16, context=32, width=32, layers=2, seed=0, verbose=False):
  rng = np.random.default_rng(seed)
  chars = sorted(set(TEXT))
  data = np.array([chars.index(c) for c in TEXT])
  params = init(len(chars), context, width, layers, rng)
  m = tree_map(np.zeros_like, params)
  v = tree_map(np.zeros_like, params)
  causal = np.tril(np.ones((context, context))) > 0
  first = last = None
  start = time.perf_counter()
  for step in range(1, steps + 1):
    at = rng.integers(0, len(data) - context - 1, batch)
    tokens = np.stack([data[i : i + context] for i in at])
    targets = np.stack([data[i + 1 : i + context + 1] for i in at])
    value, params, m, v = train_step(params, m, v, step, tokens, targets, causal)
    first = value if first is None else first
    last = value
    if verbose and (step == 1 or step % 20 == 0):
      print(f"step {step:3d}  loss {value:.3f}  ({time.perf_counter() - start:.1f}s)")
  assert last < 0.8 * first, (first, last)
  return first, last


if __name__ == "__main__":
  main(verbose=True)

The first training step compiles the forward and gradient kernels; subsequent steps reuse the compiled native code. With --verbose (the default when run as a script), main prints the cross-entropy loss at steps 1, 20, 40, and 60 and asserts that training makes progress (final loss below 80% of step 1). Using the fixed seed=0 above, the printed loss drops from 3.173 at step 1 to 2.307 (step 20), 1.796 (step 40), and 1.250 (step 60) on GPU (with nearly identical values on CPU).

For larger four-head training runs where the Adam update is also compiled into the training step, see the nanoGPT training benchmark. The compact two-head walkthrough above keeps Adam in plain Python so every line is easy to follow.