QuiddityML

By · 11 November 2026 · 13 min read

Build a small GPT from scratch in PyTorch

A complete GPT-style model in about 90 lines of PyTorch: the parts and their shapes, weight tying, where the parameters go, a training loop on a tiny batch and a generation loop, with every number checked by running the code.

A GPT-style language model is a stack of decoder transformer layers that reads a sequence of token ids and returns, at every position, a score for each token in the vocabulary as the next token. Large chat models are built on this wiring, so a small version that fits on a laptop shows how they work inside. The small version has far fewer layers, narrower vectors and much less training. Models read tokens, which can be whole words or pieces of words, and the examples here use short words as tokens.

The parts of a GPT

A GPT has five parts, in this order:

  1. token ids enter the model
  2. token embeddings and position embeddings turn them into the first stream of vectors
  3. a stack of decoder layers updates that stream
  4. a final normalization cleans up the last stream
  5. the language-modeling head turns each vector into one score per vocabulary token

The shapes use three letters. $B$ is the number of sequences in a batch, $T$ is the number of tokens in each sequence and $d_{model}$ is the number of features in each token vector, also called the model width. The ids come in with shape $(B, T)$, the stream keeps the shape $(B, T, d_{model})$ through every layer, and the head returns $(B, T, \text{vocab size})$. For the input the cute, the final position should give a high score to axolotl.

The GPT parts: 1 token ids 4, 7, 9 enter the model with shape (B, T), 2 token embeddings plus positional encodings make the first stream with shape (B, T, d_model), 3 many decoder layers refine the stream, 4 a final normalization cleans up the last stream, 5 the language-modeling head produces vocabulary logits with shape (B, T, vocab size). For the cute, the final position should give a high logit to axolotl.

The layer the model repeats

Each decoder layer has two parts. Causal self-attention lets every position mix in information from itself and the earlier positions, and a mask blocks the later ones. The feed-forward network then transforms each position's vector on its own. Each part first normalizes its input with LayerNorm, and its output is added back onto the stream it read from. The code below builds the layer from those pieces:

1import torch
2import torch.nn as nn
3import torch.nn.functional as F
4 
5 
6def scaled_dot_product_attention(q, k, v, mask=None):
7    d_k = q.size(-1)
8    scores = q @ k.transpose(-2, -1)
9    scores = scores / (d_k ** 0.5)
10    if mask is not None:
11        scores = scores.masked_fill(~mask, float("-inf"))
12    weights = torch.softmax(scores, dim=-1)
13    return weights @ v
14 
15 
16class CausalSelfAttention(nn.Module):
17    def __init__(self, d_model, num_heads):
18        super().__init__()
19        self.num_heads = num_heads
20        self.head_dim = d_model // num_heads
21        self.qkv_proj = nn.Linear(d_model, 3 * d_model)
22        self.out_proj = nn.Linear(d_model, d_model)
23 
24    def forward(self, x):
25        B, T, C = x.shape
26        q, k, v = self.qkv_proj(x).chunk(3, dim=-1)
27        q = q.view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
28        k = k.view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
29        v = v.view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
30        mask = torch.tril(torch.ones(T, T, device=x.device)).bool()
31        out = scaled_dot_product_attention(q, k, v, mask)
32        out = out.transpose(1, 2).contiguous().view(B, T, C)
33        return self.out_proj(out)
34 
35 
36class FeedForward(nn.Module):
37    def __init__(self, d_model, d_ff):
38        super().__init__()
39        self.fc1 = nn.Linear(d_model, d_ff)
40        self.fc2 = nn.Linear(d_ff, d_model)
41 
42    def forward(self, x):
43        return self.fc2(F.gelu(self.fc1(x)))
44 
45 
46class TransformerLayer(nn.Module):
47    def __init__(self, d_model, num_heads, d_ff):
48        super().__init__()
49        self.ln1 = nn.LayerNorm(d_model)
50        self.attn = CausalSelfAttention(d_model, num_heads)
51        self.ln2 = nn.LayerNorm(d_model)
52        self.ffn = FeedForward(d_model, d_ff)
53 
54    def forward(self, x):
55        x = x + self.attn(self.ln1(x))
56        x = x + self.ffn(self.ln2(x))
57        return x

The attention class splits the width into several heads, and multi-head attention explained walks through each reshape. The torch.tril line builds the causal mask, which causal masking explained covers with a worked example. A layer takes a stream of shape $(B, T, d_{model})$ and returns one of the same shape, so layers can be stacked as deep as needed.

Vocabulary logits

After the last layer, the model has one hidden vector per position:

$$h \in \mathbb{R}^{B \times T \times d_{model}}$$

The language-modeling head is a linear layer from $d_{model}$ features to one score per vocabulary token:

$$\text{logits} \in \mathbb{R}^{B \times T \times \text{vocab size}}$$

These scores are logits, raw numbers that can be any size and do not sum to 1. Softmax would turn them into probabilities, and during training the cross-entropy loss takes the logits directly and applies softmax inside.

Vocabulary logits. The stack output h in R to the B × T × d_model goes through the language-modeling head, lm_head, a Linear layer from d_model to vocab size, and gives one score per vocabulary token, logits in R to the B × T × vocab size. These scores are logits, not probabilities, and cross-entropy uses them directly during training.

Weight tying

The model has a token embedding table at the input, which maps each token id to a vector. The language-modeling head does the reverse kind of mapping, from a vector to one score per token. Both hold a matrix of size vocab size by $d_{model}$.

Weight tying makes the head reuse the embedding table instead of learning a second matrix of the same size. A token then has one vector that is used both to read it in and to score it as the next token, and the model drops a whole vocab size by $d_{model}$ matrix. For a GPT-2-sized vocabulary of 50,257 tokens and a width of 768, that matrix holds

$$50{,}257 \times 768 = 38{,}597{,}376$$

parameters, about 38.6 million. In PyTorch the tie is one line in the model's constructor, self.lm_head.weight = self.tok_emb.weight, placed after both layers exist. It makes both modules point at the same parameter matrix, and training updates that one matrix from both uses.

Weight tying in code. self.tok_emb = nn.Embedding(vocab_size, d_model), self.lm_head = nn.Linear(d_model, vocab_size, bias=False), then self.lm_head.weight = self.tok_emb.weight. One shared parameter matrix E_token is used for input lookup by self.tok_emb and for output scoring by self.lm_head, with scores = h E_tokenᵀ. Training updates one shared table, used for input lookup and output scoring.

The model class

The constructor creates every piece, and the forward pass runs them in order:

1class TinyGPT(nn.Module):
2    def __init__(
3        self, vocab_size, max_seq_len, d_model,
4        num_layers, num_heads, d_ff,
5    ):
6        super().__init__()
7        self.tok_emb = nn.Embedding(vocab_size, d_model)
8        self.pos_emb = nn.Embedding(max_seq_len, d_model)
9 
10        layers = []
11        for _ in range(num_layers):
12            layer = TransformerLayer(d_model, num_heads, d_ff)
13            layers.append(layer)
14        self.blocks = nn.ModuleList(layers)
15 
16        self.ln_f = nn.LayerNorm(d_model)
17        self.lm_head = nn.Linear(d_model, vocab_size, bias=False)
18        self.lm_head.weight = self.tok_emb.weight
19 
20    def forward(self, tokens):
21        B, T = tokens.shape
22        positions = torch.arange(T, device=tokens.device)
23        tok = self.tok_emb(tokens)
24        pos = self.pos_emb(positions)[None, :, :]
25        x = tok + pos
26 
27        for block in self.blocks:
28            x = block(x)
29 
30        x = self.ln_f(x)
31        logits = self.lm_head(x)
32        return logits

pos_emb is a learned table with one row per position, up to max_seq_len positions. torch.arange(T) gives the positions $0$ to $T-1$, and [None, :, :] adds a batch axis so the same position vectors are added to every sequence in the batch. Positional encoding explained compares this learned table with the sine and cosine formula.

nn.ModuleList registers the layers as parts of the model. A plain Python list would hide them from model.parameters(), so the optimizer would not update them. It would also hide them from .to(device), so they would stay on the CPU when the model moves to a GPU.

The TinyGPT constructor next to the parts it creates. self.tok_emb is a token table with one row per vocabulary id, self.pos_emb a position table with one row per position up to max_seq_len, self.blocks holds num_layers TransformerLayers, self.ln_f is LayerNorm(d_model), and self.lm_head is Linear(d_model to vocab_size, bias=False). ModuleList registers layers for parameters and device moves.

Forward pass shapes. tokens in Z to the B × T, then tok + pos in R to the B × T × d_model, then the decoder layers and final LayerNorm keep R to the B × T × d_model, and the logits are R to the B × T × vocab size. Each position gets one vocabulary-score vector, and the causal mask is built inside CausalSelfAttention, so the model does not pass one in.

Create the model

The constructor arguments are the configuration knobs. A vocabulary of 10 tokens is enough for a toy example:

1torch.manual_seed(0)
2model = TinyGPT(
3    vocab_size=10,
4    max_seq_len=8,
5    d_model=32,
6    num_layers=2,
7    num_heads=4,
8    d_ff=128,
9)
10print(sum(p.numel() for p in model.parameters()))
11print(model.lm_head.weight is model.tok_emb.weight)
12 
13tokens = torch.tensor([
14    [4, 7, 9, 2],
15    [4, 7, 5, 2],
16])
17inputs = tokens[:, :-1]
18targets = tokens[:, 1:]
19logits = model(inputs)
20print(inputs.shape, targets.shape, logits.shape)
126048
2True
3torch.Size([2, 3]) torch.Size([2, 3]) torch.Size([2, 3, 10])

The model has 26,048 parameters, and the second line confirms that the head and the embedding table share one matrix. The batch and the shift are explained in the training section below. For now the last line shows the shapes: 2 sequences of 3 positions go in, and 10 scores per position come out.

Create the model: model = TinyGPT(vocab_size=10, max_seq_len=8, d_model=32, num_layers=2, num_heads=4, d_ff=128). vocab_size sets the token embedding grid, max_seq_len the position embedding grid, and d_model, num_layers, num_heads and d_ff the decoder layers. tokens in Z to the B × T, logits in R to the B × T × vocab size.

Where the parameters go

Six numbers set the shape of a GPT:

Knob In TinyGPT What it sets
vocab size vocab_size rows of the token table
context length max_seq_len rows of the position table
width d_model features per token vector
layers num_layers number of decoder layers
heads num_heads heads per attention layer
FFN width d_ff hidden size of the FFN

The knobs that set model size: vocab_size, rows in the token embedding and output table; context_length, maximum number of positions the model can use; d_model, feature dimension of each token vector; n_layers, number of transformer blocks; n_heads, number of attention heads per block; d_ff, hidden feature dimension inside the feed-forward network. Some knobs add parameters, and others mostly affect activation memory or attention compute.

Ignoring the small bias vectors, attention in one layer has four $d_{model} \times d_{model}$ matrices: one each for the queries, keys and values plus one for the output projection. That makes $4\,d_{model}^2$ parameters. With $d_{model} = 4$, each matrix is $4 \times 4 = 16$ and the four of them hold 64. The number of heads does not change this, since the heads split the same width.

Attention parameter count with d_model = 4. W_Q, W_K, W_V and W_O are each 4 × 4 = 16, for a total of 16 + 16 + 16 + 16 = 64, and the formula 4 · d_model² = 4 × 4² = 64 agrees. Heads split the feature dimension and do not add four separate attention layers.

The feed-forward network has two matrices, $d_{model} \times d_{ff}$ and $d_{ff} \times d_{model}$, so it holds $2\,d_{model}\,d_{ff}$. A common choice is $d_{ff} = 4\,d_{model}$, which gives $8\,d_{model}^2$, twice the attention count. With $d_{model} = 4$ and $d_{ff} = 16$ that is $64 + 64 = 128$.

FFN parameter count with d_model = 4 and d_ff = 4 · d_model = 16. W_1 is 4 × 16 = 64 and W_2 is 16 × 4 = 64, for 64 + 64 = 128. In this simple block the attention projections hold 64 and the FFN matrices 128, so the FFN holds about twice as many parameters as the attention projections.

The counts for one layer of the model above match, once the biases are added:

1block = model.blocks[0]
2print(sum(p.numel() for p in block.attn.parameters()))
3print(sum(p.numel() for p in block.ffn.parameters()))
14224
28352

Attention holds $4 \times 32^2 = 4{,}096$ weights plus 128 biases, and the FFN holds $2 \times 32 \times 128 = 8{,}192$ weights plus 160 biases.

So one layer holds about $4\,d_{model}^2 + 8\,d_{model}^2 = 12\,d_{model}^2$ parameters, the stack holds $n_{layers}$ times that, and the token table adds vocab size times $d_{model}$. GPT-2 small has $d_{model} = 768$, 12 layers, $d_{ff} = 3072$ and a vocabulary of 50,257:

1d_model, n_layers, vocab_size = 768, 12, 50257
2per_block = 12 * d_model ** 2
3print(f"{per_block:,} {n_layers * per_block:,} {vocab_size * d_model:,} {n_layers * per_block + vocab_size * d_model:,}")
17,077,888 84,934,656 38,597,376 123,532,032

That gives about 123.5 million. The estimate leaves out biases, LayerNorm parameters and the position table, so it sits close to the commonly cited 124 million without matching it. The FFN matrices hold the largest share.

GPT-2 small rough parameter count, total 123.5M: attention projections 28.3M (22.9%), 12 blocks × 2.4M; FFN matrices 56.6M (45.8%), 12 blocks × 4.7M; token embedding table 38.6M (31.3%), 50,257 × 768. Values are approximate and exclude layer norms and biases.

The context length adds few parameters, only the rows of the position table. It costs compute instead. Each attention layer builds one score for every pair of positions, so $T$ positions give $T^2$ scores per head. A context of 1,000 tokens gives 1,000,000 scores, and doubling it to 2,000 gives 4,000,000.

Why long context gets expensive. scores in R to the T × T, number of scores = T². T = 1000 gives 1,000 × 1,000 = 1,000,000 scores, and doubling to T = 2000 gives 2,000 × 2,000 = 4,000,000 scores, 4 times as many. Attention memory and compute grow quadratically with sequence length.

Training on a tiny batch

A training batch is a tensor of token ids. The example uses a five-token vocabulary, where eos is an end-of-sequence token:

$$\text{the} = 4 \qquad \text{cute} = 7 \qquad \text{axolotl} = 9 \qquad \text{friend} = 5 \qquad \text{eos} = 2$$

The batch holds two short sequences:

$$\text{the cute axolotl eos} \qquad \text{the cute friend eos}$$

Next-token training shifts the batch by one position. The inputs drop the last token and the targets drop the first, so each input position is paired with the token after it. That is what tokens[:, :-1] and tokens[:, 1:] did above:

$$\text{inputs} = \begin{bmatrix} 4 & 7 & 9 \\ 4 & 7 & 5 \end{bmatrix} \qquad \text{targets} = \begin{bmatrix} 7 & 9 & 2 \\ 7 & 5 & 2 \end{bmatrix}$$

![A tiny training batch. Vocabulary: the = 4, cute = 7, axolotl = 9, friend = 5, eos = 2. tokens = torch.tensor([[4, 7, 9, 2], [4, 7, 5, 2]]) in Z to the 2 × 4. inputs = tokens[:, :-1] gives [[4, 7, 9], [4, 7, 5]] and targets = tokens[:, 1:] gives [[7, 9, 2], [7, 5, 2]], both 2 × 3. Each input position predicts the target id one step to its right.](images/tinygpt_training_batch.png)

The logits have shape $(2, 3, 10)$, one row of 10 scores per input position. Cross-entropy treats each of the 6 positions as its own classification over the vocabulary, so the batch and position axes are flattened into one before the loss:

1B, T, V = logits.shape
2loss = F.cross_entropy(
3    logits.reshape(B * T, V),
4    targets.reshape(B * T),
5)
6print(loss.shape)
1torch.Size([])

The empty shape means the loss is a single number for the whole batch.

Compute the training loss. inputs (2 x 3) and targets (2 x 3), then logits = model(inputs) in R to the 2 × 3 × 10, then logits.reshape(B * T, V) of shape 6 × 10 and targets.reshape(B * T) of shape 6 go into F.cross_entropy, which outputs one scalar loss for the whole batch.

A training step clears the old gradients, computes new ones with backpropagation and lets the optimizer update every parameter. AdamW is a common optimizer for transformers, and 300 steps on this batch take a few seconds on a laptop:

1optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
2for step in range(300):
3    logits = model(inputs)
4    loss = F.cross_entropy(logits.reshape(-1, V), targets.reshape(-1))
5    optimizer.zero_grad()
6    loss.backward()
7    optimizer.step()
8    if step % 100 == 99:
9        print(step + 1, round(loss.item(), 3))
1100 0.236
2200 0.234
3300 0.233

The loss settles near 0.233 instead of going to zero, and the data explains why. Four of the six targets are certain: the is followed by cute in both sequences, and axolotl and friend are both followed by eos. After the cute, the batch shows axolotl once and friend once. The lowest loss the model can reach there comes from giving each a probability of 0.5, which costs $\ln 2 \approx 0.693$ at each of those two positions. The lowest possible average loss is

$$\frac{2 \times 0.693}{6} \approx 0.231$$

and the model is within 0.002 of it.

One optimizer step. optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4), then optimizer.zero_grad() clears the last step's gradients, loss.backward() computes gradients for every parameter, and optimizer.step() updates every parameter: token embeddings, position embeddings, attention projections, FFN weights, LayerNorm parameters and the output head. With weight tying the token embedding grid and the output head are one matrix, so it receives gradients from both input lookup and output scoring.

Generating text

Generation starts from a prefix and runs the same model again and again. For the prefix the cute, the model returns logits for both positions. Only the last row predicts the token after the whole prefix, so the loop reads logits[:, -1, :]. torch.argmax picks the highest-scoring id, torch.cat appends it to the prefix, and the loop stops at the end-of-sequence token or after max_new_tokens steps:

1def generate(model, tokens, max_new_tokens, eos_id):
2    model.eval()
3    with torch.no_grad():
4        for _ in range(max_new_tokens):
5            logits = model(tokens)
6            next_logits = logits[:, -1, :]
7            next_id = torch.argmax(next_logits, dim=-1)
8            tokens = torch.cat([tokens, next_id[:, None]], dim=1)
9            if next_id.item() == eos_id:
10                break
11    return tokens
12 
13 
14print(generate(model, torch.tensor([[4, 7]]), max_new_tokens=5, eos_id=2))
15with torch.no_grad():
16    probs = torch.softmax(model(torch.tensor([[4, 7]]))[0, -1], dim=-1)
17print(probs[[5, 9]].round(decimals=2))
1tensor([[4, 7, 5, 2]])
2tensor([0.5000, 0.5000])

The model wrote the cute friend eos. The second line shows why it picked friend: it gives friend (id 5) and axolotl (id 9) about 0.50 each, the split it saw in the training batch, and argmax takes whichever is higher by a tiny margin. model.eval() switches the model to inference mode, and torch.no_grad() skips the gradient bookkeeping that only training needs.

![Use the model for generation. The prefix the (4) cute (7), tokens = torch.tensor([[4, 7]]) with B = 1 and T = 2, goes through the decoder layers, final LayerNorm and language-modeling head. logits in R to the 1 × 2 × vocab size has one row for position 0 and one for position 1, the last position. next_logits = logits[:, -1, :] because only the final position predicts the next token after the whole prefix.](images/tinygpt_prefix_logits.png)

Repeat the same call. The loop runs model(tokens), takes logits[:, -1, :], picks next_id with torch.argmax, appends it with torch.cat and breaks when next_id equals eos_id. With the = 4, cute = 7, axolotl = 9 and eos = 2, the prefix [4, 7] gives next_id = 9 and becomes [4, 7, 9], and the model runs again on the longer prefix. The loop stops when next_id == eos_id or when max_new_tokens is reached.

Decoding choices

Argmax is one way to turn logits into a token. The same logits can produce different text with a different rule, and none of these rules change the model's weights. Take four logits for the next token, $[2.0, 1.0, 0.4, 0.1]$:

1logits = torch.tensor([2.0, 1.0, 0.4, 0.1])
2print(torch.softmax(logits, dim=-1).round(decimals=2))
3print(torch.softmax(logits / 2.0, dim=-1).round(decimals=2))
4top_values, top_ids = torch.topk(logits, k=2)
5print(top_ids, torch.softmax(top_values, dim=-1).round(decimals=2))
1tensor([0.5800, 0.2100, 0.1200, 0.0900])
2tensor([0.4100, 0.2500, 0.1800, 0.1600])
3tensor([0, 1]) tensor([0.7300, 0.2700])

Plain softmax gives the top token 0.58. A temperature of 2.0 lowers that to 0.41 and gives the other three more weight, and top-k with $k = 2$ keeps the first two tokens with 0.73 and 0.27. LLM decoding strategies and LLM temperature explained cover these rules in more depth.

Decoding choices: the same logits, three ways of picking the next token. Logits cat 2.0, mat 1.0, sofa 0.4, rug 0.1. Argmax picks cat every time from 0.58, 0.21, 0.12, 0.09. Temperature 2.0 flattens the spread to 0.41, 0.25, 0.18, 0.16. Top-k with k = 2 keeps cat 0.73 and mat 0.27 and drops sofa and rug. These choices do not change the model weights, they change how the next token is selected.

The KV cache

The generation loop above runs the whole prefix through the model at every step, so it recomputes the keys and values of tokens it has already processed. Those tokens do not change, so their keys and values do not change either. A KV cache stores them once and reuses them, and each step then computes keys and values only for the new token. The model still writes one token at a time, and each step does less repeated work in exchange for the memory the cache takes.

KV cache speeds up inference. Without caching, the step recomputes keys and values for all four positions, three prefix tokens and the new token. With a KV cache, the keys and values of the three prefix tokens are stored and the step computes keys and values for the new token only, then reads the stored ones. Past prefix tokens do not change, the cache trades memory for less repeated computation, and the model still generates one token at a time.

The whole model: 1 input token ids 4, 7, 9 for the cute axolotl, 2 token embeddings, 3 a learned positional encoding grid, 4 one decoder layer repeated, with LayerNorm before masked multi-head self-attention, a residual add, LayerNorm before the feed-forward network and a second residual add, 5 a final LayerNorm, 6 vocabulary logits of shape [3, vocab_size]. Larger models use the same wiring with more layers, wider vectors, more data and much more training.

Common mistakes

How transformers work explains the decoder layer that this model stacks, and self-attention explained works through the attention formula with numbers. What is a language model covers the next-token objective that the training loop minimizes, and perplexity explained turns that loss into the usual evaluation number. A GPT is one decoder-only design, and encoder vs decoder vs encoder-decoder transformers compares it with BERT-style and T5-style models.

QuiddityML teaches this model in the Intro to NLP track as four concepts that build the GPT, set its configuration knobs, train it and generate text with it. The exercises include tracing the shapes of a forward pass and checking a parameter count by hand. Others include spotting the bug in a training step and typing the whole model class and its generation loop from scratch.