Implement decoder-only GPT-style transformer
AmazonApplied Scientist · OnsiteLast updated
This question evaluates implementation-level mastery of transformer architectures, including multi-head masked self-attention, position-wise feed-forward networks, residual connections, and precise tensor-shape reasoning for a decoder-only language model, within the Coding & Algorithms domain of deep learning and neural network engineering.
Goal
Implement a simplified decoder-only Transformer language model (similar in spirit to GPT) for next-token prediction. The implementation should be modular, using four main classes:
MultiHeadAttentionFeedForwardDecoderLayerGPT(the full model)
You may assume a deep learning framework (e.g., PyTorch or TensorFlow), but you should clearly specify tensor shapes and operations.
Model details and requirements
Assume:
- Batch size:
B - Sequence length:
T - Embedding dimension:
d_model - Number of attention heads:
num_heads(assumed_modelis divisible bynum_heads) - Vocabulary size:
V
1. Multi-head self-attention (MultiHeadAttention)
Implement a class MultiHeadAttention that performs masked self-attention:
- Inputs:
x: Tensor of shape(B, T, d_model)(token embeddings or layer outputs).- Internally learnable parameters:
- Linear projections to compute queries
Q, keysK, and valuesVfor all heads. - Operations:
- Project
xintoQ,K, andVwith shapes(B, T, d_model). - Split them into
num_headsheads, each of dimensiond_head = d_model / num_heads. - Compute scaled dot-product attention for each head:
[
\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^\top}{\sqrt{d_{head}}} + M\right)V,
]
where
Mis a causal mask that prevents a position from attending to future positions (positions> t). - Concatenate the outputs of all heads back to shape
(B, T, d_model). - Apply a final linear projection to return to
(B, T, d_model).
- Output:
- Tensor of shape
(B, T, d_model).
Ensure you correctly implement the causal (autoregressive) mask so that position t can only attend to positions 0..t.
2. Position-wise feed-forward network (FeedForward)
Implement a class FeedForward for the position-wise MLP:
- Inputs:
x: Tensor of shape(B, T, d_model).- Internal structure (typical choice):
- Linear layer from
d_modeltod_ff(e.g.,4 * d_model). - Non-linear activation (e.g., GELU or ReLU).
- Linear layer from
d_ffback tod_model. - All operations are applied independently to each position in the sequence.
- Output:
- Tensor of shape
(B, T, d_model).
3. Decoder layer (DecoderLayer)
Implement a single Transformer decoder block that combines attention, feed-forward, residual connections, and layer normalization:
- Inputs:
x: Tensor of shape(B, T, d_model).- Components:
- LayerNorm
ln1before self-attention. MultiHeadAttentionblock (masked self-attention).- Residual connection:
x = x + attention_output. - LayerNorm
ln2before feed-forward. FeedForwardblock.- Residual connection:
x = x + ff_output.
- Output:
- Tensor of shape
(B, T, d_model).
Your DecoderLayer should be reusable so that multiple layers can be stacked.
4. GPT model (GPT)
Implement a GPT class representing the full decoder-only Transformer:
- Inputs:
input_ids: Integer tensor of shape(B, T)representing token indices.- Components:
- Token embedding layer mapping token IDs to vectors of size
d_model. - Positional encodings (learned or fixed) of shape
(T, d_model)added to the token embeddings. - A stack of
NidenticalDecoderLayerblocks. - A final linear layer mapping from
d_modelto vocabulary sizeV.
- Forward pass:
- Embed tokens, add positional encodings to obtain
(B, T, d_model). - Pass through the
Ndecoder layers sequentially. - Apply the final linear layer to obtain logits of shape
(B, T, V).
- Output:
- Logits for next-token prediction:
(B, T, V).
Additional notes
- You should define the
forwardmethod for each class with correct tensor transformations. - Be careful about tensor shapes when splitting/combining heads.
- Ensure the causal mask is correctly broadcast and applied in attention.
- You do not need to implement training loops or optimization; focus on correct and clean model implementation.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.