Autoregressive Models: Token-by-Token Generation
Every text you have read from ChatGPT, Claude, or Llama was produced one token at a time, each conditioned on everything before it. Autoregressive modeling factorizes the probability of a sequence into a chain of conditional probabilities â the next token given all previous tokens â and then learns each link of that chain with next-token prediction. It is the single idea behind GPT and every other decoder-only language model.
The factorization is a mathematical identity, not an approximation: any joint distribution over sequences can be written as a product of conditionals. What makes the approach powerful is that transformers can estimate those conditionals at scale, and what makes it subtle is the asymmetry between training and inference. Training processes all positions in parallel with ground-truth inputs; inference must generate sequentially, feeding its own output back in. Understanding that gap â teacher forcing, sampling strategies, and the KV cache â is the core of this lesson.
You will build a small causal language model, see how teacher-forcing ratios affect training, compare greedy, top-k, and nucleus decoding, and implement the KV cache that makes generation feasible at all.
The factorization, made concrete
Given tokens x_1 through x_n, the model maximizes the log probability of the sequence under the chain rule: sum of log p(x_t | x_1..x_{t-1}) for each position. A transformer computes all of these conditionals in a single forward pass during training by using a causal attention mask that lets position t attend only to positions ⤠t. The output at each position is a logits vector over the vocabulary; a cross-entropy loss against the next token trains the whole network at once.
This is efficient â the entire sequence trains in parallel â but it hides a fiction. At position t the model sees the true preceding tokens, which at inference time will instead be its own possibly-wrong outputs. The training distribution and the inference distribution differ, a problem called exposure bias, and it is why long generations can drift even when per-token training loss looks excellent.
Building a small causal LM
import torch
import torch.nn as nn
import torch.nn.functional as F
class CausalLM(nn.Module):
def __init__(self, vocab_size: int, d_model: int = 256,
n_heads: int = 8, n_layers: int = 6, max_len: int = 512):
super().__init__()
self.tok = nn.Embedding(vocab_size, d_model)
self.pos = nn.Embedding(max_len, d_model)
layer = nn.TransformerEncoderLayer(
d_model=d_model, nhead=n_heads,
dim_feedforward=4 * d_model, batch_first=True,
dropout=0.1,
)
self.blocks = nn.TransformerEncoder(layer, n_layers)
self.ln = nn.LayerNorm(d_model)
self.head = nn.Linear(d_model, vocab_size, bias=False)
def forward(self, ids: torch.Tensor, targets: torch.Tensor = None):
seq = ids.shape[1]
pos = torch.arange(seq, device=ids.device)
h = self.tok(ids) + self.pos(pos)[None, :, :]
mask = nn.Transformer.generate_square_subsequent_mask(seq).to(ids.device)
h = self.ln(self.blocks(h, mask=mask))
logits = self.head(h)
if targets is not None:
loss = F.cross_entropy(
logits.view(-1, logits.size(-1)), targets.view(-1)
)
return logits, loss
return logits
model = CausalLM(vocab_size=32000)
logits, loss = model(input_ids, targets=shifted_ids)
Two details carry real weight. The causal mask is what enforces autoregression during training â without it the model would cheat by reading the answer at each position and training loss would be meaningless. And weight tying (using the embedding matrix as the output projection, or the reverse) is a common regularization that reduces parameters and often improves perplexity, though it is omitted above for clarity.
Teacher forcing and its limits
Teacher forcing feeds ground-truth tokens as inputs during training. It is what enables parallel training, and it works well enough that essentially all modern LMs use it. But a training loop can choose how much to rely on its own predictions, and the teacher-forcing ratio makes that explicit:
class ScheduledTrainer:
def __init__(self, model: nn.Module, optimizer: torch.optim.Optimizer,
ratio: float = 1.0):
self.model = model
self.optimizer = optimizer
self.ratio = ratio
def step(self, ids: torch.Tensor) -> float:
self.model.train()
inputs, targets = ids[:, :-1], ids[:, 1:]
if torch.rand(1).item() < self.ratio:
_, loss = self.model(inputs, targets)
else:
with torch.no_grad():
greedy = self.model(inputs).argmax(dim=-1)
_, loss = self.model(greedy, targets)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
return loss.item()
trainer = ScheduledTrainer(model, optimizer, ratio=1.0)
Scheduled sampling â annealing the ratio down from 1.0 during training â is the textbook response to exposure bias: let the model practice recovering from its own mistakes. The literature is genuinely mixed on whether it helps long-horizon quality (it can introduce inconsistent training signals), and modern practice often prefers alternatives: training on longer contexts, reinforcement-learning-style fine-tuning against sequence-level rewards, or simply scaling data until the drift becomes rare. What remains uncontested is that pure teacher forcing at short context lengths produces models that confidently compound early errors.
Decoding: greedy, top-k, nucleus
At inference the model produces a distribution over the vocabulary for the next token, and a decoding strategy chooses from it. Greedy decoding always takes the argmax â fast and deterministic, but prone to loops and repetitive phrasing because the model never explores a locally worse token that would lead to a better continuation.
Top-k sampling restricts the choice to the k most likely tokens, renormalizes, and samples. Nucleus (top-p) sampling instead takes the smallest set of tokens whose cumulative probability exceeds p, adapting the candidate-set size to the shape of the distribution â sharp distributions yield few candidates, flat ones yield many.
import torch
import torch.nn.functional as F
@torch.no_grad()
def nucleus_sample(model, prompt_ids: torch.Tensor, max_new: int = 128,
temperature: float = 0.8, top_p: float = 0.9) -> torch.Tensor:
model.eval()
ids = prompt_ids.clone()
for _ in range(max_new):
logits = model(ids)[:, -1, :] / max(temperature, 1e-5)
sorted_logits, sorted_idx = torch.sort(logits, descending=True)
probs = F.softmax(sorted_logits, dim=-1)
cumulative = torch.cumsum(probs, dim=-1)
cut = cumulative > top_p
cut[1:] = cut[:-1].clone()
cut[0] = False
sorted_logits[cut] = float("-inf")
probs = F.softmax(sorted_logits, dim=-1)
choice = sorted_idx[torch.multinomial(probs, 1)]
ids = torch.cat([ids, choice], dim=1)
return ids
@torch.no_grad()
def greedy_decode(model, prompt_ids: torch.Tensor, max_new: int = 128) -> torch.Tensor:
model.eval()
ids = prompt_ids.clone()
for _ in range(max_new):
nxt = model(ids)[:, -1, :].argmax(dim=-1, keepdim=True)
ids = torch.cat([ids, nxt], dim=1)
return ids
Temperature applies before everything else: below 1.0 sharpens the distribution toward certainty, above 1.0 flattens it toward uniformity. In practice chat applications run temperature near 0.7â1.0 with top-p around 0.9, while code and extraction tasks often run greedy or near-greedy for determinism. Setting both temperature and aggressive top-k can silently reduce effective diversity to almost nothing â pick one primary control and tune it.
| Strategy | Diversity | Determinism | Failure mode |
|---|---|---|---|
| Greedy | None | Fully deterministic | Repetition loops |
| Top-k | Fixed candidate count | Seeded stochastic | Wrong k for flat distributions |
| Nucleus (top-p) | Adaptive | Seeded stochastic | Under-explores very flat tails |
| Temperature only | Continuous | Seeded stochastic | Can flatten to uniform nonsense |
The KV cache: why generation is fast at all
Without caching, generating each token requires a full forward pass over the entire sequence: attention at every layer recomputes keys and values for all previous positions that it already computed a moment ago. For a 1000-token generation on a 32-layer model, that is quadratic wasted work.
The KV cache stores each layer's keys and values after they are computed. Each new step feeds only the single new token through the network, attends against the cached keys and values, and appends its own K and V to the cache. Cost per token drops from quadratic to linear in sequence length:
class KVCache:
def __init__(self, n_layers: int):
self.keys = [None] * n_layers
self.values = [None] * n_layers
def update(self, layer: int, k: torch.Tensor, v: torch.Tensor):
if self.keys[layer] is None:
self.keys[layer], self.values[layer] = k, v
else:
self.keys[layer] = torch.cat([self.keys[layer], k], dim=2)
self.values[layer] = torch.cat([self.values[layer], v], dim=2)
def get(self, layer: int):
return self.keys[layer], self.values[layer]
def reset(self):
self.keys = [None] * len(self.keys)
self.values = [None] * len(self.values)
@torch.no_grad()
def generate_cached(model, ids: torch.Tensor, steps: int) -> torch.Tensor:
cache = KVCache(model.n_layers)
for _ in range(steps):
logits, cache = model.forward_step(ids[:, -1:], cache)
nxt = logits[:, -1, :].argmax(dim=-1, keepdim=True)
ids = torch.cat([ids, nxt], dim=1)
return ids
The cache is also a real memory cost: it grows linearly with sequence length per layer, and for long-context serving it is often the dominant consumer of GPU memory â more than the weights themselves. That is why modern serving stacks quantize the cache, cap context lengths per request, and batch sequences by similar length. Paged attention (vLLM's core idea) goes further by managing the cache in fixed-size blocks so concurrent requests do not need contiguous allocations.
Measuring whether it learned
Perplexity â the exponent of average negative log-likelihood â is the standard health metric during training. It should fall smoothly on validation data; a train/val gap that widens means overfitting, and a plateau means the learning rate or data is the constraint. But perplexity is a token-level metric, and generation quality is a sequence-level property. The final check is always behavioral: sample continuations, run your downstream eval, and look for the failure modes perplexity cannot see â repetition, contradiction, and drifting away from instructions.
Common Mistakes
Training without a causal mask (or with a leaky mask)
Fix: Verify attention is strictly upper-triangular; a mask bug produces excellent training loss and useless generations.
Using temperature and top-k together aggressively
Fix: Choose one primary diversity control â stacking both often collapses effective temperature to near zero.
Regenerating the whole sequence for every token
Fix: Use a KV cache; recomputing previous positions is the single biggest avoidable inference cost.
Judging a model only by perplexity
Fix: Sample generations regularly â repetition and instruction-following failures are invisible to token-level loss.
Ignoring EOS handling in batched generation
Fix: Track finished sequences per batch item so completed samples stop consuming steps and padding does not leak into outputs.
Key Takeaways
- Autoregressive modeling factorizes sequence probability into next-token conditionals; transformers learn all conditionals in parallel with a causal mask.
- Training uses ground-truth inputs (teacher forcing) while inference feeds its own outputs â exposure bias is the resulting mismatch.
- Nucleus sampling adapts its candidate set to the distribution's shape and is the default for open-ended generation.
- Temperature, top-p, and top-k are related controls; tuning them as a stack often neutralizes each other.
- The KV cache reduces per-token cost from quadratic to linear and is the foundation of every high-throughput serving system.
- Perplexity tracks learning, but sampled generations reveal the sequence-level failures that actually matter.