GPT: Autoregressive Language Models

GPT (Generative Pre-trained Transformer) is a family of autoregressive language models that factorize the probability of a text sequence as a product of conditional distributions, each predicting the next token given all preceding tokens, trained on massive corpora via maximum likelihood. These models matter because they demonstrate that a single unsupervised pre-training objective—next-token prediction—can give rise to emergent capabilities across translation, reasoning, coding, and dialogue without task-specific architecture changes. The counterintuitive fact: GPT-style models are fundamentally left-to-right predictors, yet they can answer questions about the future, solve math problems, and generate coherent long-form arguments—all by reframing every task as text completion.

The core insight

The entire GPT paradigm rests on one elegant observation: if you can model P(token_t | token_1, ..., token_{t-1}) accurately enough, you have implicitly learned to compress and reason about virtually all human knowledge encoded in text. Training is simply maximum likelihood on the next token; inference is sequential sampling from that distribution. The "aha moment" is realizing that the causal (unidirectional) masking in the attention layers is not a limitation but a feature—it means the training objective is well-defined, non-leaky, and scales cleanly with data and parameters. Every downstream capability—summarization, code generation, chain-of-thought—emerges from this single statistical objective applied at scale.

How It Works

Autoregressive Factorization

The foundational equation of GPT is the chain rule decomposition of a joint sequence distribution. Given a sequence of tokens x=(x1,x2,…,xT)x = (x_1, x_2, \ldots, x_T):

1
P(x)=∏t=1TP(xt∣x1,x2,…,xt−1)\quad P(x) = \prod_{t=1}^{T} P(x_t \mid x_1, x_2, \ldots, x_{t-1})

Explanation: The probability of the entire sequence is the product of conditional probabilities, each asking "given everything so far, how likely is this next token?"

Symbols:

  • P(x)P(x): joint probability of the full token sequence
  • xtx_t: the token at position tt (an integer index into the vocabulary)
  • TT: total sequence length

The training objective is to maximize the log-likelihood across a corpus D\mathcal{D}:

2
L(θ)=∑x∈D∑t=1Tlog⁡Pθ(xt∣x1,…,xt−1)\quad \mathcal{L}(\theta) = \sum_{x \in \mathcal{D}} \sum_{t=1}^{T} \log P_\theta(x_t \mid x_1, \ldots, x_{t-1})

Explanation: We sum log-probabilities over every token position and every document in the corpus—every token is simultaneously a supervised training signal.

Symbols:

  • θ\theta: all learnable parameters of the transformer
  • L(θ)\mathcal{L}(\theta): log-likelihood objective (maximized, or equivalently, negative cross-entropy is minimized)
  • PθP_\theta: the model's predicted distribution parameterized by θ\theta

Scaled Dot-Product Attention (Causal)

Each transformer layer applies causal self-attention. For queries QQ, keys KK, values VV derived from the same input, with a causal mask MM:

3
Attention(Q,K,V)=softmax ⁣(QK⊤dk+M)V\quad \text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right)V

Explanation: Each position computes a weighted average over all previous positions' values, where weights are proportional to query-key dot products scaled to prevent gradient vanishing in the softmax.

Symbols:

  • Q∈RT×dkQ \in \mathbb{R}^{T \times d_k}: query matrix (current positions ask "what do I need?")
  • K∈RT×dkK \in \mathbb{R}^{T \times d_k}: key matrix (past positions broadcast "what I contain")
  • V∈RT×dvV \in \mathbb{R}^{T \times d_v}: value matrix (actual information to aggregate)
  • dkd_k: key/query dimension; dividing by dk\sqrt{d_k} prevents dot products from growing too large
  • MM: causal mask matrix where Mij=−∞M_{ij} = -\infty for j>ij > i and 00 otherwise, enforcing autoregressive order

Multi-Head Attention

GPT uses HH parallel attention heads to capture different relationship types simultaneously:

4
MultiHead(X)=Concat(head1,…,headH) WO,headh=Attention(XWhQ, XWhK, XWhV)\quad \text{MultiHead}(X) = \text{Concat}(\text{head}_1, \ldots, \text{head}_H)\,W^O, \quad \text{head}_h = \text{Attention}(XW^Q_h,\, XW^K_h,\, XW^V_h)

Explanation: Different heads learn different notions of "relevance"—one head might track syntactic agreement while another tracks coreference—and their outputs are concatenated then linearly projected.

Symbols:

  • WhQ,WhK∈Rdmodel×dkW^Q_h, W^K_h \in \mathbb{R}^{d_\text{model} \times d_k}: per-head projection matrices for queries and keys
  • WhV∈Rdmodel×dvW^V_h \in \mathbb{R}^{d_\text{model} \times d_v}: per-head value projection
  • WO∈RHdv×dmodelW^O \in \mathbb{R}^{H d_v \times d_\text{model}}: output projection that merges all heads back to model dimension
  • HH: number of heads; typically dk=dv=dmodel/Hd_k = d_v = d_\text{model}/H

GPT Block and Output

Each of the NN transformer blocks applies: LayerNorm → Causal Self-Attention → residual → LayerNorm → FFN → residual. After NN blocks, a linear head projects to vocabulary logits:

5
Pθ(xt∣x<t)=softmax(ht(N)WE⊤)\quad P_\theta(x_t \mid x_{<t}) = \text{softmax}(h_t^{(N)} W_E^\top)

Explanation: The final hidden state at position tt is projected back into vocabulary space via the transposed embedding matrix (weight tying), giving a probability distribution over the next token.

Symbols:

  • ht(N)∈Rdmodelh_t^{(N)} \in \mathbb{R}^{d_\text{model}}: the hidden state at position tt after all NN layers
  • WE∈R∣V∣×dmodelW_E \in \mathbb{R}^{|\mathcal{V}| \times d_\text{model}}: token embedding matrix (shared with the output projection for parameter efficiency)
  • ∣V∣|\mathcal{V}|: vocabulary size (e.g., 50,257 for GPT-2; ~100K for GPT-4)

PyTorch Implementation Sketch

```python import torch import torch.nn as nn import torch.nn.functional as F class CausalSelfAttention(nn.Module): def __init__(self, d_model: int, n_heads: int, max_seq_len: int): super().__init__() assert d_model % n_heads == 0 self.n_heads = n_heads self.d_k = d_model // n_heads

# Fused QKV projection for efficiency self.qkv = nn.Linear(d_model, 3 * d_model, bias=False) self.out_proj = nn.Linear(d_model, d_model, bias=False)

# Causal mask: upper-triangular = -inf mask = torch.triu(torch.ones(max_seq_len, max_seq_len), diagonal=1) self.register_buffer("mask", mask.masked_fill(mask.bool(), float("-inf"))) def forward(self, x: torch.Tensor) -> torch.Tensor: B, T, C = x.shape

# Project and split into Q, K, V qkv = self.qkv(x).split(C, dim=-1) # each: (B, T, C)

# Reshape to (B, n_heads, T, d_k) Q, K, V = [t.view(B, T, self.n_heads, self.d_k).transpose(1, 2) for t in qkv]

# Scaled dot-product with causal mask scores = (Q @ K.transpose(-2, -1)) / (self.d_k ** 0.5) scores = scores + self.mask[:T, :T] # broadcast over B, n_heads attn = F.softmax(scores, dim=-1) out = attn @ V # (B, n_heads, T, d_k) out = out.transpose(1, 2).contiguous().view(B, T, C) return self.out_proj(out) class GPTBlock(nn.Module): def __init__(self, d_model: int, n_heads: int, ffn_mult: int = 4, max_seq_len: int = 1024): super().__init__() self.ln1 = nn.LayerNorm(d_model) self.attn = CausalSelfAttention(d_model, n_heads, max_seq_len) self.ln2 = nn.LayerNorm(d_model) self.ffn = nn.Sequential( nn.Linear(d_model, ffn_mult d_model), nn.GELU(), nn.Linear(ffn_mult d_model, d_model), ) def forward(self, x: torch.Tensor) -> torch.Tensor: x = x + self.attn(self.ln1(x)) # residual + attention x = x + self.ffn(self.ln2(x)) # residual + FFN return x ```

researcher · Alec Radford | b. 1990 | GPT-1 and the Pre-train/Fine-tune Paradigm

Radford led the OpenAI team that published the original GPT paper in 2018, establishing the now-ubiquitous pattern of unsupervised pre-training on large corpora followed by task-specific fine-tuning with minimal architectural changes. His follow-up work on GPT-2 demonstrated that scaling the same architecture dramatically improved zero-shot task transfer, effectively launching the era of large language models. Surprisingly, the GPT-2 paper was initially withheld from full public release by OpenAI due to concerns about misuse—an unprecedented move in ML research that sparked widespread debate about responsible disclosure.

researcher · Ashish Vaswani | b. 1983 | Transformer Architecture (Attention Is All You Need)

Vaswani was the lead author on the 2017 "Attention Is All You Need" paper at Google Brain, which introduced the transformer architecture that GPT is built upon, replacing recurrent and convolutional operations entirely with self-attention. The transformer's parallelizability over sequence positions (unlike RNNs) was the key enabler for training at the scale GPT required. Notably, Vaswani and several co-authors left Google to co-found Adept AI and Inceptive, illustrating how foundational transformer research directly spawned a generation of AI startups.

Figure
GPT Forward Pass: Token Embeddings Through Causal Transformer Stack
GPT Autoregressive Forward Pass Input tokens: "The" "cat" "sat" "on" ← predict next Token Embedding + Positional Embedding → h⁰ Transformer Block 1 LayerNorm → Causal Attn → Residual → LayerNorm → FFN → Residual × N layers Transformer Block N → hᴺ LM Head (Linear) d_model → |V| logits Softmax P(next token) "the" 0.41 Causal Attention Mask t=1 t=2 t=3 t=4 k=1 k=2 k=3 k=4 ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✗ ✗ ✗ ✗ ✗ ✗ attend (past) masked (future) current query row (t=4)
Figure
Scaling Laws: GPT Model Family Parameter Count vs. Capability

GPT Model Family — Scale vs. Architecture Model Generation (log scale parameters) Emergent Capability 1 GPT-1 117M 2 GPT-2 1.5B 3 GPT-3 175B 3.5 GPT-3.5 +RLHF 4