← Questions

Implement a decoder-only GPT model

0
AmazonCodingLast asked Nov 2025

A coding interview question asked in Amazon's coding round, last asked Nov 2025. It tests transformers, pytorch and deep learning.

Write a small decoder-only transformer language model (GPT-style) from scratch, for next-token prediction. Use PyTorch or another framework for tensors, but write the layers yourself, as four classes. State the shape of every tensor. Training is not needed: the goal is a correct, clean forward pass.

Notation: batch B, sequence length T, model width d_model, num_heads heads with d_head = d_model // num_heads, vocabulary size V.

Part 1: MultiHeadAttention

  • forward(x: (B, T, d_model)) -> (B, T, d_model) — project x to queries, keys and values, split into heads, compute softmax(QKᵀ / sqrt(d_head) + M) V with a causal mask M so position t sees only positions 0..t, concatenate the heads and apply an output projection.

Part 2: FeedForward

  • forward(x: (B, T, d_model)) -> (B, T, d_model) — a linear layer to d_ff (often 4 * d_model), a GELU or ReLU, and a linear layer back, applied to each position independently.

Part 3: DecoderLayer

  • Pre-norm block: x = x + attn(ln1(x)), then x = x + ff(ln2(x)). Layers must stack.

Part 4: GPT

  • forward(input_ids: (B, T)) -> logits (B, T, V) — token embeddings plus learned position embeddings, N decoder layers, a final layer norm and a linear projection to the vocabulary.

Example

A hand check of the attention step, with one head, d_model = 1 and every projection the identity:

x = [[[0], [1]]]          # B = 1, T = 2
position 0 sees only itself              ->  output 0
position 1: scores [0·1, 1·1] = [0, 1], softmax [0.269, 0.731],
            output 0.269·0 + 0.731·1     ->  0.731059

Constraints

  • d_model divisible by num_heads; T at most the maximum context length.

Clarifying questions

  • Pre-norm or post-norm? Learned or sinusoidal position embeddings?
  • Should the output projection share weights with the token embedding?
  • Is dropout needed?

What a strong answer covers

  • Head split and merge with view and transpose in a consistent order ((B, T, d_model) to (B, num_heads, T, d_head) and back, with .contiguous() before the merge).
  • A causal mask built once, broadcast over batch and heads, applied with -inf before the softmax.
  • Scaling by sqrt(d_head) and why it is needed.
  • Residuals and layer norms in the right places; a final layer norm before the output head.
  • Parameter count and the cost of attention, O(T² · d_model) per layer.
  • A test: changing a later token must not change the logits at earlier positions.

Follow-ups

  • Add a key-value cache for generation.
  • Write greedy and top-k sampling generation.
  • Replace learned position embeddings with rotary embeddings.

Where it's asked

  • Amazon · Coding · Last asked Nov 202555 min · Usually two rounds; one is often an object-oriented design built in steps · No AI

What it tests

transformers · pytorch · deep learning

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding