Lesson 4.4 — Autoregressive Language Modeling
Previous lesson · 4.3 Transformer Architecture · Course overview · Next lesson · 4.5 Vision Transformer
Autoregressive Language Modeling from Joint Distributions
Lesson 4.3 built a Transformer block. This lesson uses that block in a decoder-only language model, which predicts a conditional probability distribution over the vocabulary. Let x₁, …, xₙ denote a sequence of tokens. BOS marks the start of the sequence and EOS marks its end.
The chain rule factors the joint probability into one conditional distribution per token. Maximizing the log-likelihood, as in Lesson 2.5, is equivalent to minimizing the negative log-likelihood. Each synthetic command in this lesson contains exactly five tokens, including BOS and EOS.
Training
Feed the observed tokens in parallel and predict the next token at every position.
Inference
Start from a known prefix, sample the next token and append it to the prefix. Repeat until a stopping condition is met.
Vocabulary
Each position predicts one of V vocabulary entries. The logits have shape (B, T, V).
Tokenization · Vocabulary & Byte Pair Encoding
A tokenizer converts text into integer IDs for the model. Character tokenization gives a small vocabulary and long sequences. Word tokenization gives shorter sequences but can encounter out-of-vocabulary words. Subword tokenization balances vocabulary size and sequence length.
Byte Pair Encoding (BPE)
Start with a set of base symbols. At each iteration, count adjacent symbol pairs in the training corpus, merge the most frequent pair and record the merge order. Continue until the vocabulary reaches the chosen size. To encode new text, apply the learned merge ranks. This lab starts from characters and the explicit word boundary ▁, merges only within words, and breaks ties by sorting the symbol-pair strings. Byte-level tokenizers also handle byte encoding, special tokens and pre-tokenization rules.
BPE Tokenization Player
Characters and word boundary
Token Embedding · ID to Continuous Representation
A token ID indexes a row of the embedding table E. Each row is a trainable vector. During backpropagation, gradients from positions with the same ID accumulate in the same row. Different IDs update different rows.
The integer input has shape (B, T) and the embedding output has shape (B, T, D). The additive position encoding P follows Lesson 4.3. Weight tying uses the transpose of E as the language-model head. This model uses a separate output matrix W_R so you can trace the two parameter sets independently.
Token Embedding Lookup
Causal Language Modeling · Teacher Forcing & Label Shift
Take the recorded command [BOS, move, left, slow, EOS]. Read each row below as one prediction. The four middle columns are the input positions of a single forward pass. A dash means that this row cannot read that position.
| Prediction made at | Input 0 | Input 1 | Input 2 | Input 3 | Target for the loss |
|---|---|---|---|---|---|
| BOS | BOS | — | — | — | move |
| move | BOS | move | — | — | left |
| left | BOS | move | left | — | slow |
| slow | BOS | move | left | slow | EOS |
Focus on the move row. The target is left, but its input column is blocked. Changing the recorded continuation to right fast changes this row's training target. Its input prefix is identical, so a fixed model in evaluation mode must give the same distribution at this row for both commands. At the following row the prefixes differ, and the predictions can differ too.
To construct the training tensors, slice the same stored sequence twice. In Python's half-open indexing, s[:-1] is the input and s[1:] supplies one target for each input row. Without the shift, the visible diagonal would expose the answer. Without the mask, a shifted target could be read from the next input column wherever that column exists.
At training time all four true prefixes are available, so the triangular attention pattern can be computed in parallel. During generation, the row after move is built only after the model or the user supplies the next token.
Inspect the shifted input and target tensors
Next-token Target Shift
When batching variable-length sequences, mask padding keys in attention and exclude padded targets from the loss. Split the underlying documents or trajectories before building windows so overlapping samples stay in one split. All sequences in this lab have the same length. A causal mask controls access within a sequence, while the data split controls what examples are available during training.
GPT Architecture · Decoder-only Transformer
The teaching model uses one pre-norm Transformer block with a learned embedding table, fixed sinusoidal position encoding, two causal attention heads, a GELU feed-forward network, two layer normalizations, residual connections and a separate language-model head. Its architecture is decoder-only, with the parameter count shown below.
The shared language-model head maps each contextual representation Z to V logits. The training loss takes these logits directly and computes cross-entropy stably. For prediction and sampling, softmax converts the logits to probabilities.
Causal Language Model Dataflow
| Stage | Shape | Parameters |
|---|---|---|
| Token table | (13,8) | 104 |
| Q/K/V/O | 4 × (8,8) | 256 |
| FFN up/down | (8,16), (16,8) | 256 |
| Two LayerNorms | 4 × (8,) | 32 |
| LM head + bias | (8,13), (13,) | 117 |
| Total | 1 block, 2 heads | 765 |
Language Model Training · Cross Entropy & Perplexity
Average the negative log probability over valid target tokens. Natural logarithms give the loss in nats. Computing cross-entropy with log-sum-exp avoids the underflow that can occur when taking the logarithm of a rounded softmax probability.
Perplexity is the reciprocal of the geometric mean probability assigned to the observed next tokens. Lower perplexity means the model assigns them higher probability when the evaluation data, tokenizer and averaging rule are held fixed. A uniform distribution over V tokens has perplexity V. Perplexity measures token prediction on the evaluation data. Factual accuracy, reasoning and generation safety require separate evaluation.
Cross Entropy & Perplexity
Cross-entropy scores the probability assigned to the observed token. A prefix can have several plausible continuations, so even the true conditional distribution can yield top-1 accuracy below 100%.
Autoregressive Generation · Temperature, Top-k & Top-p
At each generation step, read the logits at the last position, select a token and append it to the prefix. Greedy decoding selects the highest-scoring token. Sampling draws from a probability distribution. Temperature controls how concentrated that distribution is. Top-k keeps the k highest-scoring tokens. Top-p keeps the smallest set of highest-probability tokens whose cumulative mass reaches p. Renormalize the retained probabilities before sampling.
This lab applies temperature, retains the top-k candidates if k is nonzero, normalizes over those candidates, then applies top-p and renormalizes again. Other implementations may order these operations differently. Greedy decoding selects the highest logit directly. Top-p uses cumulative probability mass across retained tokens. The sampling lab repeats independent draws from fixed logits. The generation lab recomputes the distribution after each appended token.
Sampling Strategy Explorer
Training can evaluate all positions in parallel. During generation, each new token becomes part of the next input, so the steps run in sequence. This implementation recomputes the full prefix at every step. Lesson 6.1 covers KV caching. Generation stops at EOS or at the length limit, and the resulting command can violate the training grammar.
Engineering Experiment · Robot Command Language Model
The synthetic grammar chooses move, pick or place uniformly, then selects one of two objects or directions. For move, left maps to slow and right to fast. For pick, red maps to gentle and blue to firm. For place, those two modifiers are reversed. EOS completes every target sequence. The training and validation sets use independent seeds and draw from the same six commands, so the validation metrics measure prediction on that shared grammar.
| Training commands | Validation commands | Trainable parameters |
|---|---|---|
| 36 | 24 | 765 |
The default run uses seed 3 and 100 full-batch Adam updates with a learning rate of 0.02. The training loss averages 144 target tokens and the validation loss averages 96. Start training to run the forward pass, backward pass and Adam updates in the browser. The timeline replays a saved checkpoint every 10 updates. Generation uses the latest checkpoint by default and can also use the initial weights.
Live Tiny GPT Training
Actual default benchmark
| Metric | Initialization | After 100 updates |
|---|---|---|
| Training CE | 2.722097 | 0.441156 |
| Validation CE | 2.724423 | 0.465407 |
| Validation PPL | 15.247614 | 1.592662 |
| Validation token accuracy | 13.54% | 67.71% |
The grammar has three equally likely verbs and two equally likely objects or directions given the verb. The modifier and EOS are deterministic. The true conditional model therefore has expected mean cross-entropy (ln 3 + ln 2) / 4 ≈ 0.44794. Bayes-optimal expected top-1 accuracy is (1/3 + 1/2 + 1 + 1) / 4 ≈ 70.83%. A finite validation sample can fall above or below these expectations.
Autoregressive Generation Player
Reproducible PyTorch implementation
Save the script as gpt0404.py and run python gpt0404.py in an environment with PyTorch. The script implements training and generation with scaled_dot_product_attention and cross_entropy. It uses float64 for comparison with the browser’s manual backward pass.
import math
import torch
from torch import nn
from torch.nn import functional as F
torch.set_default_dtype(torch.float64)
torch.set_num_threads(1)
VOC = ['BOS','EOS','move','pick','place','left','right','red','blue','slow','fast','gentle','firm']
V=len(VOC)
class RNG:
def __init__(self,seed): self.s=seed & 0xffffffff
def __call__(self):
self.s=(1664525*self.s+1013904223)&0xffffffff
return self.s/4294967296
def dataset(n,seed):
r=RNG(seed); rows=[]
for _ in range(n):
verb=int(r()*3); obj=int(r()*2)
modifier=(9+obj if verb==0 else 11+(obj if verb==1 else 1-obj))
rows.append([0,2+verb,(5 if verb==0 else 7)+obj,modifier,1])
return torch.tensor(rows,dtype=torch.long)
def posenc(T,D):
return torch.tensor([[math.sin(t/10000**(2*(j//2)/D)) if j%2==0 else math.cos(t/10000**(2*(j//2)/D)) for j in range(D)] for t in range(T)])
class TinyGPT(nn.Module):
def __init__(self,seed=3,D=8,H=2):
super().__init__(); self.D=D; self.H=H
r=RNG(seed+2000); self.p=nn.ParameterDict()
for n,a,b in [('E',V,D),('Q',D,D),('K',D,D),('V',D,D),('O',D,D),('U',D,2*D),('W',2*D,D),('g1',1,D),('b1',1,D),('g2',1,D),('b2',1,D),('R',D,V),('rb',1,V)]:
self.p[n]=nn.Parameter(torch.tensor([1. if n.startswith('g') else 0. if n in ('b1','b2','rb') else (r()-.5)*.8 for _ in range(a*b)]).reshape(a,b))
def forward(self,ids,position=True):
p=self.p; B,T=ids.shape; D,H=self.D,self.H; d=D//H
X=p['E'][ids]
if position: X=X+posenc(T,D).to(X)
N=F.layer_norm(X,(D,),p['g1'].flatten(),p['b1'].flatten(),1e-5)
split=lambda x:x.reshape(B,T,H,d).transpose(1,2)
q,k,v=[split(N@p[n]) for n in ('Q','K','V')]
a=F.scaled_dot_product_attention(q,k,v,is_causal=True,dropout_p=0.)
Y=X+a.transpose(1,2).reshape(B,T,D)@p['O']
M=F.layer_norm(Y,(D,),p['g2'].flatten(),p['b2'].flatten(),1e-5)
Z=Y+F.gelu(M@p['U'],approximate='tanh')@p['W']
return Z@p['R']+p['rb']
def metrics(m,seq,position):
logits=m(seq[:,:-1],position); y=seq[:,1:]
return F.cross_entropy(logits.reshape(-1,V),y.reshape(-1)),(logits.argmax(-1)==y).double().mean().item()
def run(seed=3,updates=100,lr=.02,position=True):
tr=dataset(36,seed); va=dataset(24,seed+1000)
m=TinyGPT(seed); opt=torch.optim.Adam(m.parameters(),lr=lr); hist=[]
for t in range(updates+1):
loss,acc=metrics(m,tr,position)
if t%10==0 or t==updates:
with torch.no_grad():
vl,ac=metrics(m,va,position)
hist.append(dict(t=t,train=loss.item(),val=vl.item(),acc=ac,p={k:p.detach().tolist() for k,p in m.p.items()}))
if t<updates:
opt.zero_grad(); loss.backward(); opt.step()
return m,hist
@torch.no_grad()
def generate(m,prefix=(0,),temperature=1.,top_k=0,top_p=1.,seed=42,greedy=False,position=True):
# Max 4 generated positions including any given prefix after BOS.
r=RNG(seed); ids=list(prefix)
while len(ids)<5 and ids[-1]!=1:
logits=m(torch.tensor([ids]),position)[0,-1].tolist()
order=sorted(range(V),key=lambda j:(-logits[j],j))
if greedy: nxt=order[0]
else:
order=order[:top_k] if top_k else order
scores=[math.exp((logits[j]-logits[order[0]])/temperature) for j in order]
probs=[s/sum(scores) for s in scores]; keep=[]; mass=0.
for j,p in zip(order,probs):
keep.append((j,p)); mass+=p
if mass>=top_p: break
u=r()*mass; c=0.; nxt=keep[-1][0]
for j,p in keep:
c+=p
if u<c: nxt=j; break
ids.append(nxt)
return [VOC[j] for j in ids]
if __name__=='__main__':
m,h=run(); print('parameters',sum(p.numel() for p in m.parameters())); print('initial',h[0]['train'],h[0]['val'],h[0]['acc']);print('final',h[-1]['train'],h[-1]['val'],h[-1]['acc'],math.exp(h[-1]['val']))
for s in range(3): print(generate(m,seed=s+42))
x=torch.tensor([[0,2,5,9],[0,2,6,10]])
print('causal prefix diff', (m(x)[0,:2]-m(x)[1,:2]).abs().max().item())
AI-native verification workflow
Derive the target shift, the (B, T, V) output shape and the cross-entropy before generating an implementation with AI. Verify that changing future tokens leaves prefix logits unchanged, repeated IDs accumulate embedding gradients, the loss agrees with the reference, and sampling probabilities sum to one. In an implementation, follow the tokenizer, input IDs, token embeddings, causal block, language-model head, logits and shifted labels. Evaluate generation across multiple commands rather than drawing conclusions from a single sample.
Authoritative References & Next Lesson
Attention Is All You Need
Vaswani et al. (2017) introduced the Transformer architecture and causal masking in its decoder.
Original paperNeural Machine Translation of Rare Words with Subword Units
Sennrich et al. (2016) describe BPE for subword segmentation.
Original paperLanguage Models are Unsupervised Multitask Learners
Radford et al. (2019) describe the GPT-2 language model.
Technical reportThe Curious Case of Neural Text Degeneration
Holtzman et al. (2020) introduce nucleus sampling.
Original paperPyTorch & Learning Resources
Embedding · CrossEntropyLoss · Neural Networks: Zero to Hero · Understanding Deep Learning
Lesson 4.5, Vision Transformer, applies the same architecture to image patches and examines visual tokens, position encoding and self-attention.
Previous lesson · 4.3 Transformer Architecture · Course overview · Next lesson · 4.5 Vision Transformer