The Decoder-Only Transformer
The decoder-only transformer is a neural network architecture that autoregressively generates sequences by attending only to previously produced tokens, forming the backbone of virtually every large language model in production today including GPT-4, Claude, Llama, and Gemini. It matters because its simplicity relative to the full encoder-decoder transformer — dropping cross-attention entirely — turns out to lose almost nothing in practice while dramatically simplifying training at scale. The counterintuitive fact: despite being called "decoder-only," the architecture learns rich bidirectional-like representations of its context window through the key-value cache, achieving encoder-quality understanding without a separate encoder.
A decoder-only transformer is just a stack of masked self-attention layers: every token can see all tokens before it, but none after it. This causal masking means the model can be trained on raw text with a single next-token prediction objective — the labels are the inputs shifted by one position, so no manual annotation is ever needed. The "aha moment" is that language modeling, the simplest possible self-supervised task, forces the network to build an internal world model rich enough to generate coherent reasoning, code, and prose — no special architecture required, just scale and causal masking.
How It Works
Input Embedding and Positional Encoding
Raw tokens (integers from a vocabulary of size ) are first mapped to dense vectors, then augmented with positional information. Modern decoder-only models use learned absolute or rotary positional encodings rather than the sinusoidal encodings from the original transformer.
Explanation: The input representation for position is the sum of a token embedding (row of the embedding matrix ) and a positional vector .
Symbols: is the token embedding matrix with rows (one per vocabulary item) and columns (model dimension); is the integer token id at position ; is the positional encoding at position .
Causal (Masked) Self-Attention
The heart of the architecture is scaled dot-product attention with a causal mask. For a sequence of length with model dimension and head dimension across heads:
Explanation: Each query vector attends to all key vectors, scaled to prevent vanishing gradients, then the additive mask sets future positions to so they contribute zero weight after softmax.
Symbols: are the query, key, and value matrices for one head; is the per-head dimension; is the causal mask with if else . The projections that produce Q, K, V are:
Explanation: Each of the three matrices is a learned linear projection that maps the full-dimensional token representations into a lower-dimensional query, key, or value space for one attention head. Multi-head attention concatenates heads and projects back:
Explanation: The outputs of all attention heads (each ) are concatenated into a matrix and projected by to produce the final attention output.
Feed-Forward Sublayer
After attention, each position is transformed independently by a two-layer MLP (the feed-forward network, FFN). In modern models this is typically a SwiGLU or GeGLU variant, but the canonical form is:
Explanation: Each token's representation is expanded to an intermediate dimension (typically ) by , passed through ReLU nonlinearity, then projected back to by , adding representational capacity that attention alone lacks.
Residual Connections and Layer Norm
Each sublayer (attention and FFN) is wrapped in a Pre-LayerNorm residual connection (the modern convention, differing from the original "post-norm" paper): ```python
# Pre-LN decoder block in PyTorch class DecoderBlock(nn.Module): def __init__(self, d_model, n_heads, d_ff, dropout=0.1): super().__init__() self.ln1 = nn.LayerNorm(d_model) self.ln2 = nn.LayerNorm(d_model) self.attn = CausalSelfAttention(d_model, n_heads) self.ffn = nn.Sequential( nn.Linear(d_model, d_ff), nn.GELU(), nn.Linear(d_ff, d_model), nn.Dropout(dropout), ) def forward(self, x, mask=None): x = x + self.attn(self.ln1(x), mask) # residual + attention x = x + self.ffn(self.ln2(x)) # residual + FFN return x ```
Causal Mask Construction
```python import torch def causal_mask(seq_len: int, device: torch.device) -> torch.Tensor: """Upper-triangular matrix of -inf, zeros on and below diagonal.""" mask = torch.full((seq_len, seq_len), float('-inf'), device=device) mask = torch.triu(mask, diagonal=1) # keep diagonal (self-attention OK) return mask # shape: (T, T) ```
Training Objective
The model is trained by maximum likelihood on next-token prediction across all positions simultaneously — the key efficiency advantage over autoregressive inference: ```python
# Cross-entropy loss for language modeling logits = model(input_ids) # (B, T, V) loss = F.cross_entropy( logits[:, :-1, :].reshape(-1, vocab_size), input_ids[:, 1:].reshape(-1), # targets: shifted by one ) ```
Vaswani led the Google Brain team that published "Attention Is All You Need" (2017), introducing the full encoder-decoder transformer, which the decoder-only architecture directly descends from. His specific contribution was demonstrating that self-attention alone — without recurrence or convolution — could match or exceed the state of the art in sequence modeling. Vaswani later co-founded Essential AI, and the original transformer paper remains one of the most cited in the history of machine learning.
Radford, as a research scientist at OpenAI, was the lead author on the GPT-1 paper (2018) which first demonstrated that a decoder-only transformer pretrained on raw text with next-token prediction could be fine-tuned to achieve state-of-the-art results across diverse NLP tasks. He followed this with GPT-2 (2019) and GPT-3 (co-authored, 2020), establishing the scaling laws that now govern LLM development. Radford also co-invented CLIP, showing that the same transformer ideas extend to vision-language alignment.
Intuition
Imagine you are an author writing a novel one word at a time, but you have a perfect photographic memory of every word you have written so far. Before choosing each new word, you can look back at all previous words — but you cannot look forward, because those words don't exist yet. That is exactly what the decoder-only transformer does: causal masking enforces the "can't see the future" constraint, while self-attention gives the model that perfect photographic memory, letting any token directly attend to any earlier token regardless of distance. The feed-forward network after attention acts like your brain's "composition instinct" — it processes the attended context through a fast lookup of pattern→continuation associations burned in during training. The residual connections are the through-line of the original input — no matter how deep the stack, there is always a highway back to the raw token signal, preventing the representational collapse that plagued deep RNNs. At inference, the KV-cache is like sticky notes: once you've read and summarized each earlier token (computed its K and V), you stick those notes to your desk and never re-read the original source — you just glance at the sticky notes and write the next word.