74. GPT-2 Transformer Block hard
Implement a single GPT-2 transformer decoder block. Given an input tensor
of shape (seq_len, 768) and a packed weight buffer containing
all block parameters, compute the output using pre-norm architecture with
multi-head self-attention and a feed-forward network with GELU activation.
The block uses GPT-2's pre-norm architecture: LayerNorm is applied before each sub-layer (attention and feed-forward), not after. At a high level:
where the sub-layers are defined as:
Expanding into individual steps:
- Layer Norm 1: with parameters
- QKV Projection: , split into each of shape
(seq_len, 768) - Multi-Head Attention: Reshape into 12 heads of dimension 64, compute per-head scaled dot-product attention (no causal mask), then concatenate heads into
- Output Projection:
- Residual 1:
- Layer Norm 2: with parameters
- Feed-Forward:
- Residual 2:
Implementation Requirements
- Use only native features (external libraries are not permitted)
- The
solvefunction signature must remain unchanged - The final result must be stored in the
outputtensor - LayerNorm uses
- Use the GELU tanh approximation:
Weight Layout
All block parameters are packed into a single contiguous weights buffer
(7,087,872 floats) in the following order. Index into the buffer using the offsets below
(e.g. is at weights[1536 + i * 2304 + j]).
All 2D matrices are stored in row-major order.
| Parameter | Shape | Size | Offset |
|---|---|---|---|
| (LN1 weight) | (768,) | 768 | 0 |
| (LN1 bias) | (768,) | 768 | 768 |
| (768, 2304) | 1,769,472 | 1,536 | |
| (2304,) | 2,304 | 1,771,008 | |
| (768, 768) | 589,824 | 1,773,312 | |
| (768,) | 768 | 2,363,136 | |
| (LN2 weight) | (768,) | 768 | 2,363,904 |
| (LN2 bias) | (768,) | 768 | 2,364,672 |
| (768, 3072) | 2,359,296 | 2,365,440 | |
| (3072,) | 3,072 | 4,724,736 | |
| (3072, 768) | 2,359,296 | 4,727,808 | |
| (768,) | 768 | 7,087,104 |
Example
With seq_len = 4, x uniformly drawn from [−1, 1], and weights randomly initialized
(see Weight Layout for the packing structure):
Input: x.shape = (4, 768) # 4 token embeddings
weights.shape = (7,087,872,) # packed weight buffer
seq_len = 4
Output: output.shape = (4, 768) # transformed token embeddings
Constraints
d_model= 768,n_heads= 12,ffn_dim= 3,072 (GPT-2 124M architecture)- 1 ≤
seq_len≤ 4,096 - All tensors use 32-bit floating point
- Performance is measured with
seq_len= 1,024
Starter code (CUDA)
#include <cuda_runtime.h>
// x, output, weights are device pointers
extern "C" void solve(const float* x, float* output, const float* weights, int seq_len) {}
From LeetGPU, CC BY-NC-ND 4.0.