GPT Family: Autoregressive Language Modeling
What You'll Learn
- 1Factor an autoregressive model into per-token conditionals and measure perplexity
- 2Apply temperature, top-k, and nucleus sampling to a logit vector
- 3Use the Kaplan scaling law to predict loss after a parameter increase
- 4Explain compute optimal training and in-context learning
GPT removes every objective except the next token prediction, and that single change scaled from 117 million parameters to 175 billion without redesigning the architecture. This lesson derives the factorization and its loss, the decoding rules that turn probabilities into text, the power laws that predict loss from compute, and what in-context learning adds on top of the trained weights.
Autoregressive Factorization
A decoder-only transformer with causal masking produces a joint distribution over a sequence as a product of per-token conditionals:
Training minimizes the negative log likelihood of the corpus, which is exactly cross entropy over the vocabulary at every position:
Perplexity reports that loss as an effective branching factor, so a model that assigns the true next token probability 0.1 at every step has perplexity 10:
Sampling and Decoding
Greedy decoding takes the argmax at every step, but a trained model assigns a distribution and the decoding rule decides how much of it to keep. Temperature rescales the logits before the softmax:
with below 1 sharpening the distribution and above 1 flattening it. Top-k keeps the most likely tokens and renormalizes, while nucleus sampling keeps the smallest set whose cumulative probability reaches , so the candidate set grows when the model is uncertain and shrinks when it is confident.
| Model | Parameters | Layers and width | Context | Training tokens |
|---|---|---|---|---|
| GPT-1 (2018) | 117 million | 12 layers, 768 | 512 | BooksCorpus, 0.8 billion words |
| GPT-2 (2019) | 1.5 billion | 48 layers, 1600 | 1024 | WebText, 40 GB of text |
| GPT-3 (2020) | 175 billion | 96 layers, 12288 | 2048 | 300 billion tokens |
| LLaMA (2023) | 65 billion | 80 layers, 8192 | 2048 | 1.4 trillion tokens |
Scaling Laws and In-Context Learning
Kaplan, McCandlish, and colleagues (2020) found that loss follows a smooth power law in the parameter count over seven orders of magnitude:
The same family applies to dataset size and compute, which turns training decisions into arithmetic. Hoffmann et al. (2022) then showed that compute is best split evenly between parameters and data, giving the practical rule of about 20 training tokens per parameter:
Chinchilla used that rule to beat the larger Gopher model, and LLaMA followed it by training a 65 billion parameter model on 1.4 trillion tokens. In-context learning then adds a capability the loss never mentions directly: a prompt with a few worked examples shifts the output distribution without any gradient step, so the same weights act as a task conditioned predictor.
Worked Examples
Worked Code
import numpy as np
def softmax(x, tau=1.0):
z = x / tau
e = np.exp(z - z.max())
return e / e.sum()
def top_k_sample(logits, k, rng, tau=1.0):
probs = softmax(logits, tau)
keep = np.argsort(probs)[::-1][:k]
chosen = rng.choice(keep, p=probs[keep] / probs[keep].sum())
return int(chosen)
def nucleus_sample(logits, p, rng, tau=1.0):
probs = softmax(logits, tau)
order = np.argsort(probs)[::-1]
cumulative = np.cumsum(probs[order])
cut = int(np.searchsorted(cumulative, p)) + 1
keep = order[:cut]
return int(rng.choice(keep, p=probs[keep] / probs[keep].sum()))
logits = np.array([2.0, 1.0, 0.5, -1.0, -2.0])
rng = np.random.default_rng(0)
print("greedy:", int(np.argmax(logits)))
print("tau 0.5 top2:", top_k_sample(logits, 2, rng, tau=0.5))
print("nucleus 0.9:", nucleus_sample(logits, 0.9, rng))
print("uniform top2:", top_k_sample(logits, 2, rng, tau=5.0))
import torch
import torch.nn as nn
class CausalSelfAttention(nn.Module):
def __init__(self, d_model, heads, block_size):
super().__init__()
self.qkv = nn.Linear(d_model, 3 * d_model)
self.proj = nn.Linear(d_model, d_model)
mask = torch.tril(torch.ones(block_size, block_size))
self.register_buffer("mask", mask)
def forward(self, x):
_, T, C = x.shape
q, k, v = self.qkv(x).split(C, dim=2)
scores = (q @ k.transpose(-2, -1)) / C ** 0.5
scores = scores.masked_fill(self.mask[:T, :T] == 0, float("-inf"))
return self.proj(torch.softmax(scores, dim=-1) @ v)
class Block(nn.Module):
def __init__(self, d_model=256, heads=4, block_size=128):
super().__init__()
self.ln1 = nn.LayerNorm(d_model)
self.attn = CausalSelfAttention(d_model, heads, block_size)
self.ln2 = nn.LayerNorm(d_model)
self.ff = nn.Sequential(nn.Linear(d_model, 4 * d_model), nn.GELU(),
nn.Linear(4 * d_model, d_model))
def forward(self, x):
x = x + self.attn(self.ln1(x))
return x + self.ff(self.ln2(x))
model = Block()
print("block params:", sum(p.numel() for p in model.parameters()))
Real-World Applications
- Code generation: decoder-only models trained on repositories emit complete functions, and infill variants extend the same factorization with a span objective.
- Summarization and extraction: a single prompt formats the task, which replaced separate fine-tuned models for many narrow jobs.
- On-device language models: LLaMA style recipes train smaller models on more tokens, so a 7 billion parameter checkpoint fits consumer hardware at usable quality.
đĄCompute optimal training beats parameter count
Common Mistakes
Comparing perplexity across tokenizers
Fix: Perplexity depends on token granularity, so compare only models that share the same vocabulary.
Applying temperature twice
Fix: Scale logits once before sampling, since a second division sharpens the distribution twice.
Ignoring the prompt when computing evaluation loss
Fix: Exclude prompt tokens or you reward the model for predicting context it was given.
Best Practices
- Use nucleus sampling near p = 0.9 for open ended text and greedy for exact tasks such as extraction
- Hold context length constant between baseline and candidate runs so loss stays comparable
- Log both validation loss and a small human preference set, since loss stops predicting quality early
Key Takeaways
- Autoregressive training minimizes cross entropy at every position, and perplexity is exp of that loss per token
- Kaplan law says loss falls as N raised to minus 0.076, so doubling parameters buys about 5 percent
- Compute optimal training needs roughly 20 tokens per parameter, as Chinchilla demonstrated
- In-context examples change the output distribution with no gradient update, so task conditioning lives in the forward pass
Frequently Asked Questions
What does perplexity actually measure?
It is the exponential of the average negative log likelihood per token, so it reads as the effective number of equally likely next tokens. A perplexity of 11.94 corresponds to 2.48 nats or 3.58 bits per token, and it is only comparable under one tokenizer.
Why does temperature change the text style?
Dividing logits by a value below one amplifies the gap between the top candidates, which yields shorter and more deterministic continuations. Raising it above one flattens the gaps, so less likely words enter the candidate pool and the text becomes varied but riskier.
Is in-context learning the same as fine-tuning?
No gradient step happens, so the weights are unchanged. The prompt reweights activations inside the forward pass, which acts like conditioning on a task distribution, and removing the examples shifts the behavior back to the pretrained default.
Interview Questions
Q1: Why is loss smooth in parameter count over seven orders of magnitude?
Kaplan and colleagues fit a power law with exponent 0.076 that held from tiny models to 1.5 billion parameters, and later work extended it far beyond, which makes loss predictable before training starts.
Q2: How does nucleus sampling differ from top-k?
Top-k always keeps a fixed number of candidates, while nucleus keeps the smallest set reaching a cumulative probability p, so the candidate count adapts to how uncertain the model is.