Implement a decoder-only GPT model
I was asked this
No reports yet. Sign in to say where you were asked it.
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)— projectxto queries, keys and values, split into heads, computesoftmax(QKᵀ / sqrt(d_head) + M) Vwith a causal maskMso positiontsees only positions0..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 tod_ff(often4 * 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)), thenx = 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,Ndecoder 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_modeldivisible bynum_heads;Tat 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
viewandtransposein 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
-infbefore 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
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
