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 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 :
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:
- : joint probability of the full token sequence
- : the token at position (an integer index into the vocabulary)
- : total sequence length
The training objective is to maximize the log-likelihood across a corpus :
Explanation: We sum log-probabilities over every token position and every document in the corpus—every token is simultaneously a supervised training signal.
Symbols:
- : all learnable parameters of the transformer
- : log-likelihood objective (maximized, or equivalently, negative cross-entropy is minimized)
- : the model's predicted distribution parameterized by
Scaled Dot-Product Attention (Causal)
Each transformer layer applies causal self-attention. For queries , keys , values derived from the same input, with a causal mask :
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:
- : query matrix (current positions ask "what do I need?")
- : key matrix (past positions broadcast "what I contain")
- : value matrix (actual information to aggregate)
- : key/query dimension; dividing by prevents dot products from growing too large
- : causal mask matrix where for and otherwise, enforcing autoregressive order
Multi-Head Attention
GPT uses parallel attention heads to capture different relationship types simultaneously:
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:
- : per-head projection matrices for queries and keys
- : per-head value projection
- : output projection that merges all heads back to model dimension
- : number of heads; typically
GPT Block and Output
Each of the transformer blocks applies: LayerNorm → Causal Self-Attention → residual → LayerNorm → FFN → residual. After blocks, a linear head projects to vocabulary logits:
Explanation: The final hidden state at position is projected back into vocabulary space via the transposed embedding matrix (weight tying), giving a probability distribution over the next token.
Symbols:
- : the hidden state at position after all layers
- : token embedding matrix (shared with the output projection for parameter efficiency)
- : 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 ```
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.
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.