LeetKernels
ProblemsStart solving
Problems

74. GPT-2 Transformer Block hard

Implement a single GPT-2 transformer decoder block. Given an input tensor x 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.

x (seq_len, 768) residual LayerNorm 1 QKV Projection Multi-Head Attention Output Projection + residual LayerNorm 2 Linear (768 → 3072) GELU Linear (3072 → 768) + output (seq_len, 768)

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:

x′output​=x+MultiHeadAttn(LN1​(x))=x′+FeedForward(LN2​(x′))​

where the sub-layers are defined as:

LN(z)[Q∣K∣V]headi​MultiHeadAttn(z)FeedForward(z)​=σ2+ϵ​z−μ​⊙γ+β,μ=d1​i∑​zi​,σ2=d1​i∑​(zi​−μ)2=LN1​(x)⋅Wqkv​+bqkv​=softmax(dk​​Qi​Ki⊤​​)Vi​,dk​=64=Concat(head1​,…,head12​)⋅Wattn​+battn​=GELU(z⋅Wfc​+bfc​)⋅Wproj​+bproj​​

Expanding into individual steps:

  1. Layer Norm 1: xnorm​=LN1​(x) with parameters γ1​,β1​
  2. QKV Projection: QKV=xnorm​⋅Wqkv​+bqkv​, split into Q,K,V each of shape (seq_len, 768)
  3. Multi-Head Attention: Reshape Q,K,V into 12 heads of dimension 64, compute per-head scaled dot-product attention (no causal mask), then concatenate heads into A
  4. Output Projection: P=A⋅Wattn​+battn​
  5. Residual 1: x′=x+P
  6. Layer Norm 2: hnorm​=LN2​(x′) with parameters γ2​,β2​
  7. Feed-Forward: F=GELU(hnorm​⋅Wfc​+bfc​)⋅Wproj​+bproj​
  8. Residual 2: output=x′+F

Implementation Requirements

  • Use only native features (external libraries are not permitted)
  • The solve function signature must remain unchanged
  • The final result must be stored in the output tensor
  • LayerNorm uses ϵ=10−5
  • Use the GELU tanh approximation: GELU(x)=0.5x(1+tanh(π2​​(x+0.044715x3)))

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. Wqkv​[i][j] is at weights[1536 + i * 2304 + j]). All 2D matrices are stored in row-major order.

Parameter Shape Size Offset
γ1​ (LN1 weight) (768,) 768 0
β1​ (LN1 bias) (768,) 768 768
Wqkv​ (768, 2304) 1,769,472 1,536
bqkv​ (2304,) 2,304 1,771,008
Wattn​ (768, 768) 589,824 1,773,312
battn​ (768,) 768 2,363,136
γ2​ (LN2 weight) (768,) 768 2,363,904
β2​ (LN2 bias) (768,) 768 2,364,672
Wfc​ (768, 3072) 2,359,296 2,365,440
bfc​ (3072,) 3,072 4,724,736
Wproj​ (3072, 768) 2,359,296 4,727,808
bproj​ (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) {}

Solve it on your GPU

Previous: All-Pairs Shortest PathsNext: Sparse Matrix-Dense Matrix Multiplication

From LeetGPU, CC BY-NC-ND 4.0.