Implement a Decoder-Only Autoregressive Transformer
Machine LearningModel answerLast updated
Write PyTorch components for a decoder-only GPT model, specifying tensor shapes and handling causal masking, multi-head attention, and block architecture.
Construct a modular, decoder-only Transformer language model suitable for autoregressive next-token prediction using PyTorch (or pseudo-code with explicit tensor operations).
Your solution should implement four distinct classes:
-
MultiHeadAttention:- Accepts input tensor
xof shape(B, T, d_model). - Computes query, key, and value representations using linear projections.
- Splits representations across
num_headsheads (where $d_{\text{head}} = d_{\text{model}} / \text{num_heads}$). - Applies scaled dot-product attention with a causal mask to enforce autoregressive visibility (a position $t$ can only attend to positions $\le t$).
- Concatenates head outputs and projects back to
(B, T, d_model).
- Accepts input tensor
-
FeedForward:- Implements a position-wise feed-forward network (MLP).
- Maps
(B, T, d_model)to an inner dimensiond_ff(e.g., $4 \times d_{\text{model}}$), applies GELU activation, and projects back to(B, T, d_model).
-
DecoderLayer:- Implements a single Transformer decoder block using Pre-LayerNormalization (Pre-LN).
- Structured as: $x \leftarrow x + \text{Attn}(\text{LN}_1(x))$ followed by $x \leftarrow x + \text{FFN}(\text{LN}_2(x))$.
-
GPT:- Represents the complete architecture.
- Converts token IDs of shape
(B, T)into embeddings and adds positional embeddings. - Passes the combined embeddings through a sequence of $N$ stacked
DecoderLayerinstances. - Includes a final LayerNorm and projects to output logits of shape
(B, T, V)across vocabulary size $V$.
Expected Dimensions & Notation
B: Batch sizeT: Sequence lengthd_model: Embedding dimensionnum_heads: Number of parallel attention headsd_ff: Feed-forward hidden dimensionV: Vocabulary size
Be ready to explain key tensor transformations, memory complexity, and common pitfalls during head splitting/merging and matrix masking.
Hints
Hint 1
Pay close attention to how you reshape and transpose tensors when converting between (B, T, d_model) and multi-head representation (B, h, T, d_head). Using view without proper transpose permutes elements incorrectly.
Hint 2
Construct the upper-triangular causal mask such that positions > t contain -inf (or True for PyTorch masked_fill), ensuring softmax outputs 0 for future tokens.
Hint 3
In PyTorch, register non-trainable tensors like the static upper-triangular mask using register_buffer so that they move with model device state without updating gradients.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Architecture & Implementation Strategy
A decoder-only autoregressive Transformer generates tokens sequentially by masking future positions during training and inference.
Tensor Transformations Through the Model
| Stage | Input Shape | Output Shape | Notes |
|---|---|---|---|
| Token + Pos Embedding | (B, T) | (B, T, d_model) | Sum of token and position lookup tables |
| Q, K, V Projection | (B, T, d_model) | (B, T, d_model) | Linear maps prior to head separation |
| Head Separation | (B, T, d_model) | (B, h, T, d_head) | Reshape to (B, T, h, d_head) then transpose (1, 2) |
| Attention Matrix ($Q K^T$) | (B, h, T, d_head) | (B, h, T, T) | Dot-product scaled by $1 / \sqrt{d_{\text{head}}}$ |
| Masked Softmax $\cdot V$ | (B, h, T, T) | (B, h, T, d_head) | Future scores mapped to $-\infty$ |
| Merge Heads | (B, h, T, d_head) | (B, T, d_model) | Transpose (1, 2), make .contiguous(), then .view() |
| Unembedding (LM Head) | (B, T, d_model) | (B, T, V) | Map to vocabulary logits |
Complete PyTorch Implementation
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class MultiHeadAttention(nn.Module):
"""
Causal Multi-Head Self-Attention using Pre-LN style setup.
"""
def __init__(self, d_model: int, num_heads: int, max_seq_len: int, dropout: float = 0.0):
super().__init__()
assert d_model % num_heads == 0, "d_model must be evenly divisible by num_heads"
self.d_model = d_model
self.num_heads = num_heads
self.d_head = d_model // num_heads
self.q_proj = nn.Linear(d_model, d_model)
self.k_proj = nn.Linear(d_model, d_model)
self.v_proj = nn.Linear(d_model, d_model)
self.out_proj = nn.Linear(d_model, d_model)
self.attn_dropout = nn.Dropout(dropout)
self.resid_dropout = nn.Dropout(dropout)
# Causal mask: upper-triangular matrix filled with True above main diagonal
mask = torch.triu(torch.ones(max_seq_len, max_seq_len, dtype=torch.bool), diagonal=1)
self.register_buffer("causal_mask", mask, persistent=False)
def _split_heads(self, x: torch.Tensor) -> torch.Tensor:
B, T, _ = x.shape
# (B, T, d_model) -> (B, T, h, d_head) -> (B, h, T, d_head)
return x.view(B, T, self.num_heads, self.d_head).transpose(1, 2)
def forward(self, x: torch.Tensor) -> torch.Tensor:
B, T, C = x.shape
q = self._split_heads(self.q_proj(x)) # (B, h, T, d_head)
k = self._split_heads(self.k_proj(x)) # (B, h, T, d_head)
v = self._split_heads(self.v_proj(x)) # (B, h, T, d_head)
# Scaled dot-product attention
scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.d_head) # (B, h, T, T)
# Apply causal mask (future positions -> -inf)
mask = self.causal_mask[:T, :T].view(1, 1, T, T)
scores = scores.masked_fill(mask, float("-inf"))
weights = F.softmax(scores, dim=-1)
weights = self.attn_dropout(weights)
out = weights @ v # (B, h, T, d_head)
# Re-assemble heads: (B, h, T, d_head) -> (B, T, h, d_head) -> (B, T, d_model)
out = out.transpose(1, 2).contiguous().view(B, T, C)
return self.resid_dropout(self.out_proj(out))
class FeedForward(nn.Module):
"""
Position-wise Feed-Forward Network (MLP).
"""
def __init__(self, d_model: int, d_ff: int, dropout: float = 0.0):
super().__init__()
self.net = nn.Sequential(
nn.Linear(d_model, d_ff),
nn.GELU(),
nn.Linear(d_ff, d_model),
nn.Dropout(dropout)
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.net(x)
class DecoderLayer(nn.Module):
"""
Single Decoder Block with Pre-Layer Normalization and Residual Connections.
"""
def __init__(self, d_model: int, num_heads: int, d_ff: int, max_seq_len: int, dropout: float = 0.0):
super().__init__()
self.ln1 = nn.LayerNorm(d_model)
self.attn = MultiHeadAttention(d_model, num_heads, max_seq_len, dropout)
self.ln2 = nn.LayerNorm(d_model)
self.ffn = FeedForward(d_model, d_ff, dropout)
def forward(self, x: torch.Tensor) -> torch.Tensor:
# Pre-LN residual connections
x = x + self.attn(self.ln1(x))
x = x + self.ffn(self.ln2(x))
return x
class GPT(nn.Module):
"""
Complete Decoder-Only Autoregressive Model.
"""
def __init__(
self,
vocab_size: int,
d_model: int,
num_layers: int,
num_heads: int,
d_ff: int,
max_seq_len: int,
dropout: float = 0.0
):
super().__init__()
self.max_seq_len = max_seq_len
self.tok_emb = nn.Embedding(vocab_size, d_model)
self.pos_emb = nn.Embedding(max_seq_len, d_model)
self.drop = nn.Dropout(dropout)
self.layers = nn.ModuleList([
DecoderLayer(d_model, num_heads, d_ff, max_seq_len, dropout)
for _ in range(num_layers)
])
self.ln_final = nn.LayerNorm(d_model)
self.lm_head = nn.Linear(d_model, vocab_size, bias=False)
def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
B, T = input_ids.shape
assert T <= self.max_seq_len, f"Sequence length {T} exceeds max supported length {self.max_seq_len}"
positions = torch.arange(0, T, device=input_ids.device).unsqueeze(0) # (1, T)
x = self.tok_emb(input_ids) + self.pos_emb(positions) # (B, T, d_model)
x = self.drop(x)
for layer in self.layers:
x = layer(x)
x = self.ln_final(x)
logits = self.lm_head(x) # (B, T, V)
return logits
Detailed Design Considerations & Pitfalls
1. Splitting and Merging Heads correctly
A standard mistake is doing x.view(B, num_heads, T, d_head) directly without transposing.
- Incorrect:
x.view(B, num_heads, T, d_head)pairs contiguous channels of $d_{\text{model}}$ together, interspersing time steps with head indices. - Correct: First reshape to
(B, T, num_heads, d_head), preserving the temporal sequence along dimension 1, thentranspose(1, 2)to swap heads and sequence indices. When merging, calling.contiguous()is mandatory before.view()because.transpose()changes the memory layout stride without relocating memory in place.
2. Scaled Dot-Product Variance
The attention scores are scaled by $\frac{1}{\sqrt{d_{\text{head}}}}$. If queries and keys have zero mean and unit variance, their inner product $q \cdot k = \sum_{i=1}^{d_{\text{head}}} q_i k_i$ has mean $0$ and variance $d_{\text{head}}$. Dividing by $\sqrt{d_{\text{head}}}$ scales the variance back down to $1$, preventing softmax inputs from growing extremely large where gradients vanish.
3. Pre-LN vs. Post-LN
- Post-LN (Original Vaswani et al., 2017): $x_{l+1} = \text{LN}(x_l + \text{SubLayer}(x_l))$. Requires careful learning rate warm-up because gradients can explode or vanish in deep stacks.
- Pre-LN (GPT-2, Megatron-LM): $x_{l+1} = x_l + \text{SubLayer}(\text{LN}(x_l))$. Preserves an unobstructed identity residual path throughout the network, allowing stable training of very deep models without warm-up heuristics.
Computational and Memory Complexity
Let $L$ be the layer depth, $T$ the sequence length, $d$ the model dimension, and $V$ the vocabulary size:
- Attention Computations per Layer:
- $Q, K, V$ linear projections: $\mathcal{O}(B \cdot T \cdot d^2)$
- Matrix product $Q K^T$: $\mathcal{O}(B \cdot h \cdot T^2 \cdot d_{\text{head}}) = \mathcal{O}(B \cdot T^2 \cdot d)$
- Output projection: $\mathcal{O}(B \cdot T \cdot d^2)$
- Feed-Forward Computations per Layer:
- Linear projections with inner dimension $d_{\text{ff}} = 4d$: $\mathcal{O}(B \cdot T \cdot d \cdot 4d) = \mathcal{O}(B \cdot T \cdot d^2)$
- LM Head Projection:
- Final projection: $\mathcal{O}(B \cdot T \cdot d \cdot V)$
Key Bottleneck: The $\mathcal{O}(T^2)$ memory footprint for storage of attention score matrices during training scales quadratically with respect to context length $T$.