TL;DR
You can build and train a small GPT in plain JAX on a CPU in about 150 lines. This guide follows nanoGPT's design, trains on Tiny Shakespeare, and explains each part, from causal self-attention to a jit-compiled training step. The result writes lines that look like a play, mostly real words included, so Shakespeare's job is safe for now.
Where to start reading:
Say an engineer has used large language models through an API for a year and wants to know what actually happens inside one. Reading papers helps, but the parts only click once they write the attention mask, watch the loss fall and see the first words come out. They do not have a GPU, only a laptop.
You can build and train a small GPT in plain JAX on a CPU in about 150 lines. The model in this guide follows the design of Andrej Karpathy’s nanoGPT: token and position embeddings, a stack of transformer blocks with causal self-attention, and a linear layer that predicts the next character. We trained it on Tiny Shakespeare for 3,000 steps. Validation loss fell from 3.879 to 1.610, and the model learned to write lines that look like a play, with character names, line breaks and mostly real words.
Key Takeaways
- A GPT is a next-token predictor: embeddings, a stack of attention and MLP blocks, and a final layer that scores every token in the vocabulary.
- In JAX the whole model can be plain functions over a dictionary of arrays.
jax.gradcomputes the gradients,jax.vmapadds the batch dimension andjax.jitcompiles the training step. - Our model has 818,241 parameters, 4 layers, 4 attention heads and a 64-character context window.
- On Tiny Shakespeare (1,115,394 characters, 65 distinct characters), validation loss went from 3.879 at the start to 1.610 after 3,000 steps of batch size 32.
- Training took 759 seconds on a 4-core cloud machine that was running other jobs at the same time. Your time will differ.
- Watch validation loss, not training loss. On a 687-character text we wrote first, training loss fell to 0.148 while validation loss rose to 3.325: the model memorized the text instead of learning from it.
What nanoGPT Is and Why Rebuild It in JAX
nanoGPT is a small, readable PyTorch codebase for training and fine-tuning GPT-style models. Its repository describes it as the simplest, fastest repository for training and fine-tuning medium-sized GPTs, and its character-level Shakespeare example is a common first exercise for learning how these models work.
JAX is a Python library for numerical computing from Google. It looks like NumPy, but it can differentiate functions (jax.grad), vectorize them over a batch (jax.vmap) and compile them with XLA (jax.jit). Rebuilding the model in JAX is a good exercise because nothing is hidden. There is no layer class that stores its own weights: every parameter is an array you create, pass in and update yourself.
We use Optax, the gradient processing library from the JAX ecosystem, for the AdamW optimizer and the cross-entropy loss. Everything else is JAX itself. The versions we ran were Python 3.13.17, JAX 0.12.0.1 and Optax 0.2.8, on CPU.
Setup and Data
Install JAX for CPU and Optax in a fresh virtual environment:
python3 -m venv venv
venv/bin/pip install "jax[cpu]" optax The data is Tiny Shakespeare, a 1.1 MB text file of plays that nanoGPT and the earlier char-rnn project both use. Each character is one token. The script downloads the file once, builds a mapping from characters to integers and keeps the last 10% of the text for validation.
import time
import jax
import jax.numpy as jnp
import optax
# 1. Data: Tiny Shakespeare (about 1.1 million characters), one character per token.
import os
import urllib.request
URL = "https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt"
if not os.path.exists("input.txt"):
urllib.request.urlretrieve(URL, "input.txt")
text = open("input.txt", encoding="utf-8").read()
chars = sorted(set(text))
stoi = {c: i for i, c in enumerate(chars)}
itos = {i: c for c, i in stoi.items()}
data = jnp.array([stoi[c] for c in text], dtype=jnp.int32)
n = int(0.9 * len(data))
train_data, val_data = data[:n], data[n:]
vocab_size = len(chars) That gives 65 distinct characters: letters, digits, punctuation, spaces and line breaks. The training split has 1,003,854 characters and the validation split 111,540.
A training example is a window of 64 characters, and the target is the same window shifted one character to the right. The model learns to predict every next character in the window at once.
# 2. Settings.
block_size = 64 # characters of context
n_embd = 128 # width of each token vector
n_head = 4
n_layer = 4
batch_size = 32
steps = 3000
lr = 1e-3
def get_batch(key, split):
d = train_data if split == "train" else val_data
ix = jax.random.randint(key, (batch_size, 1), 0, len(d) - block_size - 1)
pos = ix + jnp.arange(block_size)
return d[pos], d[pos + 1] JAX has no global random state. Every random call takes a key, and you split keys to get new ones. That is why get_batch takes a key as its first argument, and why the same seed always gives the same run.
The Parameters as a Dictionary
All the weights live in one nested dictionary. JAX calls a structure like this a pytree, and its functions (gradients, optimizers, tree maps) work on the whole tree at once.
# 3. Parameters: a plain dictionary of arrays (a "pytree").
def init_params(key):
def dense(key, n_in, n_out):
return {"w": jax.random.normal(key, (n_in, n_out)) * 0.02, "b": jnp.zeros(n_out)}
keys = jax.random.split(key, 3 + 4 * n_layer)
params = {
"tok": jax.random.normal(keys[0], (vocab_size, n_embd)) * 0.02,
"pos": jax.random.normal(keys[1], (block_size, n_embd)) * 0.02,
"ln_f": {"g": jnp.ones(n_embd), "b": jnp.zeros(n_embd)},
"head": dense(keys[2], n_embd, vocab_size),
"blocks": [],
}
for l in range(n_layer):
k = keys[3 + 4 * l: 3 + 4 * (l + 1)]
params["blocks"].append({
"ln1": {"g": jnp.ones(n_embd), "b": jnp.zeros(n_embd)},
"qkv": dense(k[0], n_embd, 3 * n_embd),
"proj": dense(k[1], n_embd, n_embd),
"ln2": {"g": jnp.ones(n_embd), "b": jnp.zeros(n_embd)},
"fc": dense(k[2], n_embd, 4 * n_embd),
"out": dense(k[3], 4 * n_embd, n_embd),
})
return params Each block has two layer norms, the attention weights (qkv for queries, keys and values together, and proj for the output) and a two-layer MLP that widens to four times the embedding size, the same ratio GPT-2 uses. With these settings the model has 818,241 parameters. GPT-2 small has about 124 million, so this is roughly 150 times smaller.
Causal Self-Attention, Step by Step
Self-attention lets each position look at earlier positions and decide which ones matter for predicting the next character. It was introduced for translation in “Attention Is All You Need” (Vaswani and others, 2017). A GPT uses the decoder side of that design with one change that makes it a language model: the causal mask.
def layer_norm(p, x):
mean = x.mean(-1, keepdims=True)
var = x.var(-1, keepdims=True)
return (x - mean) / jnp.sqrt(var + 1e-5) * p["g"] + p["b"]
def attention(p, x):
T, C = x.shape
q, k, v = jnp.split(x @ p["qkv"]["w"] + p["qkv"]["b"], 3, axis=-1)
hs = C // n_head
q = q.reshape(T, n_head, hs).transpose(1, 0, 2)
k = k.reshape(T, n_head, hs).transpose(1, 0, 2)
v = v.reshape(T, n_head, hs).transpose(1, 0, 2)
att = (q @ k.transpose(0, 2, 1)) / jnp.sqrt(hs)
mask = jnp.tril(jnp.ones((T, T), dtype=bool))
att = jnp.where(mask, att, -jnp.inf)
att = jax.nn.softmax(att, axis=-1)
y = (att @ v).transpose(1, 0, 2).reshape(T, C)
return y @ p["proj"]["w"] + p["proj"]["b"] Here is what each line does, for one sequence of T characters:
- One matrix multiply produces the queries, keys and values, which are then split into three arrays.
- Each is reshaped into 4 heads of 32 dimensions, so each head can attend to different patterns.
- The score between two positions is the dot product of a query and a key, divided by the square root of the head size so the softmax does not saturate.
- The mask is a lower-triangular matrix. Scores above the diagonal (future positions) become minus infinity, so after the softmax they get zero weight. Without this line the model could read the answer it is supposed to predict.
- The weighted sum of values from all heads is joined back together and passed through the output projection.
The function handles a single sequence. We never write a batch dimension; jax.vmap adds it later.
The Full GPT Forward Pass
A transformer block is attention followed by an MLP, each wrapped in a residual connection and preceded by a layer norm. This pre-norm layout is what GPT-2 and nanoGPT use.
def mlp(p, x):
h = jax.nn.gelu(x @ p["fc"]["w"] + p["fc"]["b"])
return h @ p["out"]["w"] + p["out"]["b"]
def forward(params, idx):
T = idx.shape[0]
x = params["tok"][idx] + params["pos"][:T]
for b in params["blocks"]:
x = x + attention(b, layer_norm(b["ln1"], x))
x = x + mlp(b, layer_norm(b["ln2"], x))
x = layer_norm(params["ln_f"], x)
return x @ params["head"]["w"] + params["head"]["b"] The input is a list of character IDs. Each ID picks a row from the token embedding table, and each position adds a learned position vector, because attention on its own has no sense of order. After the blocks, a final layer norm and a linear layer turn each position’s vector into 65 scores, one per character. These scores are called logits.
Training With jit and AdamW
The loss is cross-entropy between the logits and the true next characters, averaged over every position in the batch. jax.vmap runs forward over the 32 sequences of a batch without changing its code.
def loss_fn(params, x, y):
logits = jax.vmap(forward, in_axes=(None, 0))(params, x)
return optax.softmax_cross_entropy_with_integer_labels(logits, y).mean()
optimizer = optax.adamw(lr)
@jax.jit
def train_step(params, opt_state, x, y):
loss, grads = jax.value_and_grad(loss_fn)(params, x, y)
updates, opt_state = optimizer.update(grads, opt_state, params)
return optax.apply_updates(params, updates), opt_state, loss
eval_loss = jax.jit(loss_fn) jax.value_and_grad returns the loss and the gradient of the loss for every array in the parameter dictionary, in the same nested shape. Optax turns those gradients into updates with AdamW and applies them. The @jax.jit decorator compiles the whole step the first time it runs, so later steps skip the Python overhead.
The training loop draws a batch, takes a step and every 500 steps prints the training loss and the average validation loss over 20 batches:
key = jax.random.PRNGKey(0)
key, init_key = jax.random.split(key)
params = init_params(init_key)
opt_state = optimizer.init(params)
n_params = sum(p.size for p in jax.tree_util.tree_leaves(params))
print(f"jax {jax.__version__}, optax {optax.__version__}, device {jax.devices()[0]}")
print(f"characters: {len(text)}, vocabulary: {vocab_size}, parameters: {n_params:,}")
start = time.perf_counter()
for step in range(steps + 1):
key, bkey = jax.random.split(key)
x, y = get_batch(bkey, "train")
params, opt_state, loss = train_step(params, opt_state, x, y)
if step % 500 == 0:
key, vkey = jax.random.split(key)
val = jnp.mean(jnp.array([eval_loss(params, *get_batch(k, "val")) for k in jax.random.split(vkey, 20)]))
print(f"step {step:5d} train loss {float(loss):.3f} val loss {float(val):.3f}")
print(f"training time: {time.perf_counter() - start:.1f} s") The Results
This is the output of our run:
jax 0.12.0.1, optax 0.2.8, device cpu:0
characters: 1115394, vocabulary: 65, parameters: 818,241
step 0 train loss 4.239 val loss 3.879
step 500 train loss 1.962 val loss 2.032
step 1000 train loss 1.716 val loss 1.841
step 1500 train loss 1.585 val loss 1.737
step 2000 train loss 1.480 val loss 1.701
step 2500 train loss 1.426 val loss 1.648
step 3000 train loss 1.390 val loss 1.610
training time: 759.2 s Two checks tell you the model is learning and not broken:
- The starting loss matches random guessing. A model that spreads its guesses evenly over 65 characters has a loss of ln(65), about 4.17. The first training loss was 4.239, close to that, so the setup is sound.
- Validation loss falls with training loss. Both dropped steadily, and validation stayed 0.1 to 0.2 above training. The model is learning patterns that carry over to text it has not seen.
The loss was still falling at step 3,000, so more steps, a longer context or a wider model would improve it further, at the cost of more time on a CPU.
Generating Text
To generate, the model takes a prompt, predicts scores for the next character, samples one character from those scores, adds it to the input and repeats. Only the last 64 characters are fed back in, because that is the context the model was trained on.
def generate(params, key, prompt, length):
idx = [stoi[c] for c in prompt]
for _ in range(length):
ctx = jnp.array(idx[-block_size:], dtype=jnp.int32)
logits = forward(params, ctx)[-1]
key, sub = jax.random.split(key)
idx.append(int(jax.random.categorical(sub, logits)))
return "".join(itos[i] for i in idx)
print(generate(params, jax.random.PRNGKey(42), "ROMEO:", 300)) These are the first lines it wrote after “ROMEO:”, unedited:
ROMEO:
Misvernonies their will be you;
A kindness, we is discoredo! Ah, I'ld and therefore?
The most to stabpe't too:
This is king, our seticiations of here.
KING EDWARD IV:
I wrong you'llo keep soully Bold was him;
Grame to do peace, Clifford, his two of his anon,
So miltieves, be your heaven au tormast The model has learned the shape of a play: a speaker’s name in capitals, a colon, short lines, and a new speaker after a blank line. It uses real names from the source (King Edward IV and Clifford both appear in Henry VI) and many real words. It has not learned meaning or grammar beyond a few words at a time, which is what you would expect from 818,241 parameters, one character per token and about 13 minutes of training.
The Mistake to Watch For: Memorizing Instead of Learning
Before using Tiny Shakespeare, we trained a smaller version of the same model on a 687-character paragraph we wrote ourselves. Training loss fell from 3.532 to 0.148. Validation loss went from 3.293 down to 2.483 at step 300, then rose to 3.325 by step 1,500. Asked to write, the model repeated whole sentences from the paragraph word for word.
That is overfitting: a model with about 100,000 parameters and 687 characters to learn from will memorize them. Training loss alone would have suggested a great model. The validation split is what showed the problem. If your validation loss stops falling while training loss keeps going down, you need more data or a smaller model, or you need to stop training earlier.
From Here to a Real Language Model
The structure of this model is the same one large models use. The differences are scale and engineering:
- Tokens: real models use subword tokenizers (GPT-2 has a vocabulary of 50,257 tokens), so each step predicts a piece of a word instead of a single letter.
- Size: more layers, wider embeddings and contexts of thousands of tokens, trained on billions of tokens on many GPUs or TPUs.
- Training details: learning rate warmup and decay, dropout, gradient clipping, mixed precision and checkpointing. nanoGPT includes most of these and is a good next read.
- Faster code: fused attention kernels and memory tricks. Our guide to writing GPU kernels in Python with Triton shows what that work looks like.
The same attention block also works on images. Our Vision Transformer walkthrough applies it to image patches instead of characters, and our explainer on Mamba state space models covers an alternative to attention for long sequences. For a study plan beyond this exercise, see how to learn large language models, and for what changes when you take a model to production, our review of Building LLMs for Production.
Back to the Laptop
The engineer from the opening did not need a GPU to see how a GPT works. They needed about 150 lines of JAX, a 1 MB text file and 13 minutes. The loss started where random guessing would put it, fell to 1.610 on text the model had never seen, and the model wrote a scene with a speaker named King Edward IV. Every part of a large language model was there, just smaller.
Frequently Asked Questions
Do I Need a GPU to Train a GPT in JAX?
Not for a model this size. The same code runs on a GPU or TPU if you install the matching JAX build, and jax.jit compiles it for that device without changes. A GPU becomes necessary once you scale up the model, the context or the data.
Why Use Plain JAX Instead of Flax?
Plain JAX keeps every parameter and operation visible, which is the point of a learning exercise. Libraries such as Flax add module classes, parameter management and checkpointing that make larger projects easier. Once the plain version makes sense, moving to one of them is mostly a change in how parameters are stored.
What Does a Loss of 1.6 Mean?
The loss is the average negative log probability the model gives to the correct next character. A loss of 1.610 means the model gives the right character a probability of about e to the power of minus 1.61, roughly 0.2 on average, compared with 1 in 65 (about 0.015) for random guessing. Lower is better, and only validation loss tells you how the model does on new text.
How Is This Different From nanoGPT?
nanoGPT is written in PyTorch and includes dropout, weight tying between the embedding and output layers, learning rate schedules, gradient accumulation, distributed training and GPT-2 weight loading. This version keeps only the model and a basic training loop, written in JAX, so each part can be read on its own.




