KatInterview

Build a Causal Transformer Language Model Block by Block

Machine LearningModel answer
HardModel answerMachine Learningtransformerpytorchself-attention

Last updated

Write a decoder-only transformer from memory in PyTorch: embeddings, hand-written causal multi-head attention, feed-forward layers, residual wiring, and a logits head.

You are asked to write a small autoregressive transformer language model in Python, using PyTorch or NumPy, with no template to start from. Explain the tensor shape at each step as you write.

Task

Build a model that takes a batch of integer token IDs and returns, for every position, a score for each vocabulary entry as the next token.

The model must include:

  • token embeddings combined with positional information;
  • multi-head self-attention that you implement yourself, with a causal mask so that each position can only look at itself and earlier positions;
  • a position-wise feed-forward network;
  • residual connections and layer normalization around each sub-layer;
  • a stack of identical blocks, followed by a final projection to vocabulary logits.

Interface

  • Input: an integer tensor of shape (batch, seq_len), where seq_len is at most a maximum context length given to the constructor.
  • Output: a float tensor of shape (batch, seq_len, vocab_size).
  • Causality: the logits at position t may depend only on input tokens 0..t.
  • Constructor arguments: vocabulary size, maximum context length, model width, number of heads, number of layers, and feed-forward hidden width.

Rules

  • Primitive layers (linear, embedding, layer norm, softmax, dropout) are allowed.
  • Prebuilt attention or transformer modules are not allowed.

What to discuss

Before coding, state your assumptions: decoder-only versus encoder-decoder, whether padding must be handled, and your choice of pre-norm or post-norm and of positional encoding. After coding, show how you would verify that the model runs and that future tokens cannot influence earlier outputs, and comment on compute and memory cost.

Hints

Hint 1

Split the model width into `n_heads` chunks of size `head_dim = d_model / n_heads`. Project once to Q, K and V, reshape to `(B, H, T, head_dim)`, and merge back with a transpose and reshape at the end.

Hint 2

Scale the score matrix `Q @ K^T` by `1/sqrt(head_dim)`, then set entries above the diagonal to negative infinity BEFORE the softmax, so that masked positions get exactly zero weight.

Hint 3

To test for leakage, run the model on a sequence, change only the last token, and check that the logits at all earlier positions are unchanged.