93. Llama Transformer Block hard
Implement a single Llama-style transformer decoder block. Given an input tensor of shape
(seq_len, 512), a packed weight buffer, and precomputed RoPE tables, compute the
output using pre-norm architecture with Grouped Query Attention (GQA), Rotary Position Embeddings
(RoPE), and a SwiGLU feed-forward network.
The block follows Llama's pre-norm architecture. Unlike GPT-2, it uses RMSNorm (no mean subtraction, no additive bias), Grouped Query Attention with 8 query heads and 2 key/value heads, Rotary Position Embeddings applied to Q and K, and a SwiGLU feed-forward network. None of the linear projections have bias terms.
The sub-operations in detail:
where is the upper-triangular causal mask ( above the diagonal) and .
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 - RMSNorm uses , no additive bias
- Apply causal masking: position attends only to positions
- Repeat K and V heads (GQA groups) before computing attention
cosandsinhave shape(seq_len, 32)— apply them to both Q and K heads independently
Weight Layout
All parameters are packed into a single contiguous weights buffer
(2,819,072 floats) in the order below. All 2-D matrices are stored row-major
with shape (out_dim, in_dim). There are no bias terms.
| Parameter | Shape | Size | Offset |
|---|---|---|---|
| (RMSNorm 1 scale) | (512,) | 512 | 0 |
| (512, 512) | 262,144 | 512 | |
| (128, 512) | 65,536 | 262,656 | |
| (128, 512) | 65,536 | 328,192 | |
| (512, 512) | 262,144 | 393,728 | |
| (RMSNorm 2 scale) | (512,) | 512 | 655,872 |
| (1408, 512) | 720,896 | 656,384 | |
| (1408, 512) | 720,896 | 1,377,280 | |
| (512, 1408) | 720,896 | 2,098,176 |
Example
With seq_len = 4, x drawn uniformly from [−1, 1], and randomly
initialized weights:
Input: x.shape = (4, 512) # 4 token hidden states
weights.shape = (2,819,072,) # packed weight buffer
cos.shape = (4, 32) # precomputed RoPE cosines
sin.shape = (4, 32) # precomputed RoPE sines
seq_len = 4
Output: output.shape = (4, 512) # transformed token hidden states
Constraints
d_model= 512,n_q_heads= 8,n_kv_heads= 2,head_dim= 64,ffn_hidden= 1,408- 1 ≤
seq_len≤ 4,096 - All tensors use 32-bit floating point
- Performance is measured with
seq_len= 2,048
Starter code (CUDA)
#include <cuda_runtime.h>
// x, output, weights, cos, sin are device pointers
extern "C" void solve(const float* x, float* output, const float* weights, const float* cos,
const float* sin, int seq_len) {}
From LeetGPU, CC BY-NC-ND 4.0.