KatInterview

Implement a Decoder-Only Autoregressive Transformer

Machine LearningModel answer
MediumModel answerMachine Learningtransformersdeep-learningpytorch

Last 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:

  1. MultiHeadAttention:

    • Accepts input tensor x of shape (B, T, d_model).
    • Computes query, key, and value representations using linear projections.
    • Splits representations across num_heads heads (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).
  2. FeedForward:

    • Implements a position-wise feed-forward network (MLP).
    • Maps (B, T, d_model) to an inner dimension d_ff (e.g., $4 \times d_{\text{model}}$), applies GELU activation, and projects back to (B, T, d_model).
  3. 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))$.
  4. 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 DecoderLayer instances.
    • Includes a final LayerNorm and projects to output logits of shape (B, T, V) across vocabulary size $V$.

Expected Dimensions & Notation

  • B: Batch size
  • T: Sequence length
  • d_model: Embedding dimension
  • num_heads: Number of parallel attention heads
  • d_ff: Feed-forward hidden dimension
  • V: 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.