GPT & Autoregressive Language Modeling

Imagine trying to teach a machine to finish any sentence you start, in any style, on any topic. This is precisely the problem autoregressive language modeling solves. It is the engine underneath GPT-style systems that write essays, translate languages, and hold conversations. The core trick is deceptively simple: predict the next token given everything before it, then repeat. Training on this single objective, applied to enormous unlabeled text corpora, produces a model that implicitly learns grammar, facts, reasoning patterns, and style. All this happens without a human ever labeling a single example. The importance of this idea for real systems is hard to overstate. Every major deployed large language model — GPT-3, GPT-4, LLaMA, and their descendants — is trained with some variant of this same next-token prediction loss. This loss is computed over a decoder-only Transformer Decoder Stack. The objective is self-supervised: the "label" for each position is just the next word in the training text. This means the model can bootstrap from raw web-scale corpora rather than curated datasets. This scalability, more than any single architectural trick, is why these models have grown from millions to hundreds of billions of parameters. The big picture is a chain of three ideas fitting together. First, Masked Self-Attention gives the decoder a way to attend only to past tokens. This enforces the left-to-right causal constraint. Second, Tokenization at Scale converts raw text into a sequence of discrete units the model can assign probabilities to. Third, autoregressive factorization turns the impossibly hard problem of modeling a joint distribution over entire documents into something simpler. It becomes a long sequence of much simpler next-token classification problems. These are chained together by the chain rule of probability. This article develops the autoregressive language modeling objective precisely: how the loss is defined, how a decoder-only Transformer computes it efficiently in parallel during training, and why the same causal mask that enables fast training also enables coherent left-to-right generation at inference time. We walk through the training loop and sampling loop with pseudocode. We verify the complexity claims, trace a concrete example, and catalogue the pitfalls that break naive implementations.

Key takeaways
  • Autoregressive LMs factor the probability of a sequence into a product of next-token conditionals via the chain rule.
  • GPT uses a decoder-only Transformer with causal (masked) self-attention so position ii never sees positions >i>i.
  • Training computes cross-entropy loss at every position in parallel using teacher forcing, giving O(n)O(n) effective supervision signals per sequence of length nn.
  • Inference is inherently sequential: generation requires one forward pass per new token, though KV-caching avoids recomputation.
  • The objective is task-agnostic; it produces a general-purpose model later adapted via the Pretraining-Finetuning Paradigm.
  • Model quality improves predictably with scale, foreshadowing formal Scaling Laws relating loss to parameters, data, and compute.
The core insight

GPT learns to model language by turning the single task "predict the next token" into billions of free, self-supervised training signals extracted from raw text.

The idea

An autoregressive language model defines a probability distribution over a sequence of tokens x1,x2,…,xnx_1, x_2, \dots, x_n by applying the chain rule of probability:

P(x1,…,xn)=∏t=1nP(xt∣x1,…,xt−1)P(x_1, \dots, x_n) = \prod_{t=1}^{n} P(x_t \mid x_1, \dots, x_{t-1})

Each factor P(xt∣x<t)P(x_t \mid x_{<t}) is a next-token distribution conditioned only on preceding tokens, never on future ones. This is the left-to-right or causal constraint that gives the family its name. Modeling the full joint distribution over a document directly is intractable — the vocabulary of possible documents is astronomically large — but modeling one conditional distribution over a fixed vocabulary at a time is a well-posed classification problem, solvable by a neural network trained with cross-entropy loss. GPT (Generative Pretrained Transformer) instantiates this idea with a decoder-only Transformer: a stack of Transformer blocks in which every self-attention layer is causally masked, so that the representation at position tt can only be a function of tokens x1,…,xtx_1, \dots, x_t. This is what makes the same architecture usable both for computing all nn conditional distributions in one parallel forward pass during training, and for autoregressive generation at inference time, where tokens are produced one at a time and fed back as input. The term "pretraining" refers to the fact that this objective requires no labels beyond the raw text itself — it is trained once on a broad corpus and then adapted downstream, foreshadowing the Pretraining-Finetuning Paradigm.

How it works

Setup. Given a corpus, we first apply Tokenization at Scale (typically byte-pair encoding or a similar subword scheme) to convert raw text into sequences of integer token IDs from a fixed vocabulary VV. Training sequences are fixed-length windows of nn tokens (e.g., n=2048n=2048 or larger) drawn from the corpus, often by concatenating documents with separator tokens and chunking.

Model. The decoder-only Transformer maps a token sequence to a sequence of probability distributions over VV: 1. Token embeddings E∈R∣V∣×dE \in \mathbb{R}^{|V| \times d} and positional embeddings are added to form the input representations ht(0)h^{(0)}_t. 2. LL Transformer decoder blocks are applied, each consisting of causally-masked multi-head self-attention followed by a position-wise feedforward network, with residual connections and layer normalization. 3. A final linear projection (often tied to E⊤E^\top) plus softmax converts the last layer's hidden state ht(L)h^{(L)}_t into P^(xt+1∣x≤t)\hat{P}(x_{t+1} \mid x_{\le t}).

The causal mask. In self-attention, each position computes attention scores over all positions in the sequence. To enforce the left-to-right constraint, GPT adds −∞-\infty (or a large negative number) to the attention scores for any key position j>ij > i before the softmax, exactly the Masked Self-Attention mechanism. This zeroes out attention probability to future tokens without changing the shape or asymptotic cost of the attention computation.

Training via teacher forcing. During training, the entire ground-truth sequence is fed into the model at once. Because the mask makes position tt's output depend only on inputs 1,…,t1, \dots, t, this single forward pass simultaneously computes the correct conditional distribution for every position, using the true (not model-generated) prefix as context — this is teacher forcing. The loss is the average negative log-likelihood of the true next token at every position:

L=−1n∑t=1nlog⁡P^(xt+1∣x1,…,xt)\mathcal{L} = -\frac{1}{n}\sum_{t=1}^{n} \log \hat{P}(x_{t+1} \mid x_1, \dots, x_t)

This gives nn supervised signals per sequence from a single unlabeled example, which is the central efficiency trick behind self-supervised pretraining.

Inference / generation. At generation time there is no ground truth to condition on, so the process must be sequential: sample or pick xt+1x_{t+1} from P^(⋅∣x≤t)\hat{P}(\cdot \mid x_{\le t}), append it to the context, and repeat. Naively this recomputes attention over the whole growing prefix at every step; in practice, KV-caching stores previously computed key/value vectors so each new token only requires attention against the cache plus one new query, avoiding redundant computation. ```

# ---- TRAINING (teacher forcing, one gradient step) ---- function TRAIN_STEP(model, batch_of_token_sequences):

# batch_of_token_sequences: tensor of shape (B, n), integer token ids inputs = batch_of_token_sequences[:, 0 : n-1] # x_1 ... x_{n-1} targets = batch_of_token_sequences[:, 1 : n] # x_2 ... x_n (shifted by 1) logits = model.forward(inputs) # shape (B, n-1, |V|)

# internally: causal mask ensures logits[:, t, :] depends only on inputs[:, 0..t] loss = 0 for b in range(B): for t in range(n-1): probs = softmax(logits[b, t, :]) loss += -log(probs[targets[b, t]]) loss = loss / (B * (n-1)) gradients = backward(loss) optimizer.apply(gradients) return loss

# ---- CAUSAL SELF-ATTENTION (core mechanism enabling the above) ---- function CAUSAL_SELF_ATTENTION(X): # X: (n, d) hidden states Q = X @ W_Q # (n, d_k) K = X @ W_K # (n, d_k) V = X @ W_V # (n, d_v) scores = (Q @ K^T) / sqrt(d_k) # (n, n) for i in range(n): for j in range(n): if j > i: scores[i, j] = -infinity # mask future positions weights = softmax(scores, axis=-1) # row-wise softmax return weights @ V # (n, d_v)

# ---- INFERENCE (autoregressive generation with KV cache) ---- function GENERATE(model, prompt_tokens, max_new_tokens): cache = KVCache() # empty per-layer key/value store tokens = prompt_tokens

# prime the cache with the prompt in one forward pass logits, cache = model.forward(tokens, cache=cache) output = [] for step in range(max_new_tokens): next_token_probs = softmax(logits[-1, :]) # distribution for next token next_token = sample(next_token_probs) # greedy / top-k / nucleus output.append(next_token) if next_token == END_OF_SEQUENCE: break

# only the ONE new token needs a forward pass; cache holds the rest logits, cache = model.forward([next_token], cache=cache) return output ``` Notice the asymmetry: `TRAIN_STEP` processes an entire sequence of length nn in one parallel pass because all targets are known in advance (teacher forcing). `GENERATE` cannot do this, because token t+1t{+}1 is not known until the model itself produces it — hence the loop.

Figure
Decoder-only GPT: causal attention mask and the training/inference asymmetry
Causal Mask (attention allowed = shaded) key j → query i ↓ x1x2x3 x4x5 x1x2x3 x4x5 Blue = attention allowed (j ≤ i). Gray = masked (j > i, set to −∞ before softmax). Training: 1 parallel pass x1 x2 x3 x4 x5 → all 5 next-token losses at once Inference: n sequential passes x1 →x2 →x3(cache) →x4(cache) Each step reuses cached K/V; only 1 new token processed per step.

Complexity & correctness

Time complexity, training. For one sequence of length nn with model dimension dd and LL layers, the dominant costs per layer are:

  • Self-attention score computation and weighted sum: O(n2d)O(n^2 d), since every pair of positions computes a dd-dimensional dot product and the value aggregation.
  • Feedforward sublayers: O(nd2)O(n d^2) (typically the hidden dimension is 4d4d, a constant factor).

Total per sequence: O(L(n2d+nd2))O(L(n^2 d + n d^2)). Crucially, this entire cost is paid once per training step, not once per position, because the causal mask allows all nn positions' losses to be computed in a single forward/backward pass — this is the payoff of teacher forcing plus parallel matrix operations on a GPU/TPU. Without masking and parallel computation, one would need nn separate forward passes (one per prefix length), costing O(n)O(n) times more.

Space complexity, training. Storing all attention matrices for backpropagation costs O(Ln2)O(L n^2) (or O(Ln2h)O(Ln^2 h) per head before summation, though implementations often fuse heads). Activations for the backward pass cost O(Lnd)O(Lnd). Memory is the binding constraint that limits maximum context length nn in practice, motivating techniques like gradient checkpointing and, at inference, KV-caching.

Time complexity, inference. Generating mm new tokens with KV-caching costs O(m⋅L⋅(nctxd+d2))O(m \cdot L \cdot (n_{\text{ctx}} d + d^2)) where nctxn_{\text{ctx}} is the current context length, since each step attends over the cached keys/values (linear in context length) rather than recomputing the full O(n2)O(n^2) attention from scratch. Without caching, naive re-processing of the whole growing sequence at every step costs O(m2Ld)O(m^2 L d) overall — quadratically worse in the number of generated tokens. This is why KV-caching is not an optimization detail but a practical necessity for usable generation latency.

Correctness argument. The claim to justify is: does minimizing the average per-position cross-entropy loss over a large corpus actually recover a good approximation to the true conditional distribution of language? The argument proceeds in two parts: 1. Chain rule exactness. The factorization P(x1,…,xn)=∏tP(xt∣x<t)P(x_1, \dots, x_n) = \prod_t P(x_t \mid x_{<t}) is an identity of probability theory — it holds for any joint distribution, with no independence assumptions. So if the model's conditionals P^(xt∣x<t)\hat P(x_t \mid x_{<t}) were exactly correct for every tt and every prefix, the induced joint distribution over sequences would be exactly correct too. This licenses reducing "model all of language" to "model one next token well," with no loss of expressiveness in principle. 2. Cross-entropy minimization recovers the true conditional. For a fixed context c=x<tc = x_{<t}, minimizing Ext∼P∗[−log⁡P^(xt∣c)]\mathbb{E}_{x_t \sim P^*}[-\log \hat P(x_t \mid c)] over all valid distributions P^(⋅∣c)\hat P(\cdot \mid c) is minimized exactly when P^(⋅∣c)=P∗(⋅∣c)\hat P(\cdot \mid c) = P^*(\cdot \mid c), the true data-generating conditional. This follows from Gibbs' inequality: the cross-entropy H(P∗,P^)=H(P∗)+DKL(P∗∥P^)H(P^*, \hat P) = H(P^*) + D_{KL}(P^* \| \hat P), and KL divergence is minimized (at zero) only when the two distributions coincide. Since the training loss averages exactly this cross-entropy over all observed contexts, gradient descent on it pushes the model toward the true conditional distribution, subject to the model's representational capacity and the finiteness of training data. The causal mask is what guarantees the induced factorization is valid — that P^(xt∣x<t)\hat P(x_t \mid x_{<t}) genuinely does not depend on x≥tx_{\ge t}, so that sampling autoregressively at inference (where future tokens genuinely do not exist yet) matches the conditional structure the model was trained under. Without masking, a bidirectional model trained the same way would leak future information into position tt's prediction during training, making it inconsistent with — and far too optimistic compared to — the sequential generation process it must perform at test time.

Tradeoffs. The quadratic-in-nn attention cost is the well-known scalability bottleneck of vanilla Transformers, motivating a large literature on sparse, linear, and windowed attention. Autoregressive generation is fundamentally sequential and cannot be parallelized across the output length the way training can, which is the main latency bottleneck of deployed generative systems (encoder-only or masked models like BERT trade this generative capability away for cheaper bidirectional training).

Worked example

Take the toy corpus sentence `"the cat sat on the mat"`, tokenized (for simplicity) at the word level into IDs:

tokenthecatsatonthemat
id123415

Training input/target pairs (shift-by-one), with n=6n=6:

position ttinput prefix x≤tx_{\le t}target xt+1x_{t+1}
1thecat
2the, catsat
3the, cat, saton
4the, cat, sat, onthe
5the, cat, sat, on, themat

All five rows are produced from a single 6-token sentence, and — thanks to the causal mask — a single forward pass through the model computes all five predicted distributions simultaneously. Suppose after some training the model assigns these (illustrative) probabilities to the correct next token at each position:

position tttargetP^(target)\hat P(\text{target})−log⁡P^-\log \hat P
1cat0.053.00
2sat0.301.20
3on0.500.69
4the0.700.36
5mat0.102.30

Average loss L=(3.00+1.20+0.69+0.36+2.30)/5=7.55/5=1.51\mathcal{L} = (3.00+1.20+0.69+0.36+2.30)/5 = 7.55/5 = 1.51 nats/token. Notice position 1 has low confidence (0.05) because "the" alone is a weak predictor of the next word — many words can follow "the." Position 4 is highly confident (0.70) because after "the cat sat on," the word "the" is a very likely continuation (English strongly favors an article there). This illustrates that the loss is not measuring memorization of this one sentence, but the model's calibrated uncertainty given limited context — exactly what a good conditional probability model should produce. Perplexity, a standard reporting metric, is simply exp⁡(L)=exp⁡(1.51)≈4.5\exp(\mathcal{L}) = \exp(1.51) \approx 4.5, interpretable as the model being as "confused" as if choosing uniformly among about 4.5 equally likely tokens per position. At generation time, given the prompt `"the cat"`, the model would sample from P^(⋅∣the, cat)\hat P(\cdot \mid \text{the, cat}) — say it draws `"sat"` — then feed `"the cat sat"` back in (using the KV cache from the prompt plus one new key/value for "sat") to get P^(⋅∣the, cat, sat)\hat P(\cdot \mid \text{the, cat, sat}), and so on, never seeing ahead of where it currently is, matching exactly the conditional structure it was trained on.

Common pitfalls & traps

PitfallWhy it happensConsequence
Forgetting the causal mask (using bidirectional attention)Copy-pasting encoder attention codeModel "cheats" by seeing the answer, trains to near-zero loss but generates garbage at inference
Off-by-one in the input/target shiftConfusing x≤tx_{\le t} input with xtx_{t} as its own targetModel trained to predict the current token from itself, trivially solvable, no real learning
Ignoring padding tokens in the lossBatching variable-length sequences with paddingLoss diluted or corrupted by predicting meaningless pad tokens
Mismatched training vs. inference context lengthPosition embeddings only trained up to length nnSevere degradation ("length generalization" failure) beyond training context
Recomputing full attention every generation stepNot implementing a KV cacheInference cost blows up quadratically in output length, unacceptably slow serving
Exposure bias from teacher forcingModel never sees its own mistakes during trainingErrors compound during free-running generation ("degeneration"), especially over long outputs

Pioneers & history

Origins · 1 minAlec Radford and how this was discovered
AR
Alec Radford
active researcher, OpenAI, b. late 20th century · Lead author of the original 2018 GPT paper demonstrating that a decoder-only Transformer, pretrained purely on next-token prediction over unlabeled text, produces representations that transfer effectively to a wide range of downstream language tasks with minimal task-specific architecture changes.

History
1948
— Claude Shannon formalizes language as a stochastic process and introduces entropy and n-gram prediction as a way to quantify "surprise" in text.
1980
s-1990s — Statistical n-gram language models become the dominant approach to next-word prediction in speech recognition and machine translation.
2003
— Bengio et al. introduce a neural probabilistic language model, replacing count-based n-grams with a learned distributed representation.
2017
— Vaswani et al. introduce the Transformer architecture with self-attention, replacing recurrence for sequence modeling.
2018
— Radford et al. (OpenAI) introduce GPT, combining a decoder-only causally-masked Transformer with large-scale generative pretraining, establishing the recipe scaled up in GPT-2, GPT-3, and beyond.

Shannon's early framing of language modeling as sequential prediction — measuring how well a model anticipates the next symbol — is the direct conceptual ancestor of the cross-entropy objective used to train GPT. What changed over seven decades was not the objective itself but the representational power available to model P(xt∣x<t)P(x_t \mid x_{<t}): from fixed-order n-gram counts, to neural embeddings, to deep self-attention over the entire preceding context.

Where this matters

Every modern general-purpose text-generation system — chatbots, coding assistants, drafting tools, and API-based completion services — is built on a decoder-only Transformer trained with this exact autoregressive objective. The pretrained model produced by this process is rarely used in isolation: it is the starting point for the Pretraining-Finetuning Paradigm, where the same weights are further adapted via supervised finetuning, instruction tuning, or reinforcement learning from human feedback to make outputs more useful and safe, without discarding the linguistic and world knowledge acquired during pretraining. The predictable improvement in this pretraining loss as model size, data size, and compute grow is precisely the empirical regularity formalized by Scaling Laws, which now guide the design and budget allocation of frontier model training runs. Beyond natural language, the same left-to-right factorization underlies autoregressive models of code, protein sequences, symbolic music, and even images represented as token sequences, making it one of the most widely reused algorithmic templates in modern machine learning.

Ask the tutor: How does the causal mask interact with positional encodings to determine how far a GPT model can generalize beyond its trained context length?

Why is GPT called "decoder-only" if there's no encoder?

The name comes from the original Transformer architecture, which had an encoder (bidirectional, for reading an input sequence) and a decoder (causally masked, for generating an output sequence conditioned on the encoder). GPT keeps only the decoder half, including its causal self-attention, but drops the cross-attention layers that would connect it to an encoder, since there is no separate source sequence to condition on — the "source" and "target" are the same text, shifted by one position. The label "decoder-only" signals that every layer uses masked, autoregressive-compatible attention, distinguishing it from encoder-only models like BERT, which use full bidirectional attention and cannot generate text left-to-right in the same way.

How does this relate to n-gram language models?

N-gram models estimate P(xt∣xt−k,…,xt−1)P(x_t \mid x_{t-k}, \dots, x_{t-1}) using raw frequency counts over a fixed, small context window kk, suffering badly from data sparsity as kk grows. GPT keeps the same chain-rule factorization but replaces counting with a learned neural function that conditions on the entire preceding context (up to the model's maximum length) through self-attention, and generalizes across similar contexts via continuous embeddings rather than treating every context as an unrelated bucket. The objective — predict the next token, measured by cross-entropy — is conceptually identical; what changed is the expressive power and generalization ability of the conditional estimator.

Does teacher forcing cause problems, and if so, why keep using it?

Yes — teacher forcing trains the model always conditioned on the true prefix, but at generation time the model conditions on its own, possibly imperfect, previous outputs. This mismatch, called exposure bias, can let small errors compound into larger ones during long free-running generation. It is kept because it is what makes parallel training over full sequences possible and stable; without it, training would require sequential rollouts as slow as generation itself. In practice, sufficiently large models trained on sufficiently diverse data are robust enough that exposure bias is a secondary concern compared to model capacity and data quality, though it remains an active research topic.

Why use cross-entropy loss specifically, rather than some other loss function?

Cross-entropy loss is the negative log-likelihood of the correct token under the model's predicted distribution, and minimizing it is mathematically equivalent to minimizing the KL divergence between the true and predicted conditional distributions (since the entropy of the true distribution is a constant with respect to the model's parameters). This gives cross-entropy a precise probabilistic justification: it is the loss whose minimizer, in the limit of infinite data and capacity, is exactly the true data-generating distribution. It is also convenient computationally, since its gradient with respect to the logits has a simple closed form (predicted probability minus one-hot target), making backpropagation efficient and numerically stable when combined with softmax.

Why does context length matter so much, and why can't it just be made arbitrarily large?

Context length determines how much preceding text the model can condition on when predicting the next token, directly bounding how much information — a paragraph, a whole document, a codebase — the model can use. However, self-attention costs O(n2)O(n^2) in time and memory for a context of length nn, so doubling the context roughly quadruples the compute and memory required per layer. This quadratic wall is why extending context length is a major engineering challenge, addressed by techniques like sparse attention patterns, sliding windows, and specialized positional encodings, rather than simply increasing nn in the vanilla formulation.

Is next-token prediction "understanding" language, or just pattern matching?

This is a genuinely debated question, but the objective itself only specifies what is being optimized — predicting the next token accurately — not how the model internally achieves it. Empirically, models trained purely on this objective at large scale develop internal representations that support tasks far removed from raw prediction, such as arithmetic, translation, and multi-step reasoning, suggesting the training signal incentivizes learning structure in the data (syntax, semantics, world facts) as a means to lower loss. Whether this constitutes "understanding" in a deeper sense remains a matter of ongoing scientific and philosophical discussion, separate from the purely mechanical correctness of the algorithm.

How does this connect to encoder-only models like BERT?

BERT is trained with a masked language modeling objective — predicting randomly masked tokens using bidirectional context from both directions — rather than strict left-to-right autoregression. This makes BERT's representations rich for understanding tasks (classification, extraction) but structurally unsuited to free generation, since at inference time there is no way to reveal "future" tokens the way training assumed. GPT's autoregressive, causally masked objective sacrifices some bidirectional context during training in exchange for a generative capability that matches exactly how text must be produced at inference time, one token after another.

Before this

Where this leads