Unit 5 of 7 · about 4 hours · derive, implement
RoPE: positions as rotations
RoPE makes position differences enter attention through rotations of and . An implementation that silently restarts positions at zero can pass a short demo and fail incremental decoding.
You'll be able to
- Derive for paired rotations.
- Implement RoPE on and with explicit position IDs, head-local pairs and preserved output dtype.
- Detect pairing and offset errors using norm, common-offset and nonzero-position tests.
Covers
Read
In this order, only the parts listed
0 of 2 done
- Paired rotations and relative dot productsModern LLM Notebook - decoder construction path
Rotary Position Encoding (RoPE): 2D rotation mathematical intuition, From 2D to higher dimensions, and Full RoPE implementation
Stop before Experimental comparison. The rotation identity, not a plotted attention pattern, is the result to reproduce.
- Explicit position IDs and rotary attention contractStanford CS336 Assignment 1 - model contract
Section 3.4.3, Relative Positional Embeddings and problem (rope), printed pp. 22 to 23; section 3.4.5, Applying RoPE, printed p. 25
Focus on
- For zero-based pair , frequency is . Rotate by
position*frequencyusing radians, not degrees. - . The positional factor depends on the difference; content vectors and still matter.
- Apply the rotation after projection and head splitting to and , not . Require an even rotary width and agree on adjacent-pair versus split-half layout.
- Index with the supplied positions, including nonzero offsets. Compute angles and rotations in
float32when needed and cast the result back; buffers are not trainable weights.
Common mistakes · 3
- Mixing adjacent pairs with a split-half reference without permuting channels and projection weights. Both conventions can work, but their raw tensors are not interchangeable.
- Using
arange(T)instead of supplied position IDs. This discards offsets and per-sequence positions. - Inferring monotonic distance decay or reliable long-context quality from the identity. Rotations are periodic, and the identity alone guarantees neither.
Try it yourself
Closed-book, before checking anything
Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why do a common offset on query and key positions cancel?Answer
, assuming unchanged , and frequencies. The rotary positional factor is unchanged.
2.With and , what frequencies do the two adjacent pairs use?Answer
1 and 0.01 radians per position. Position gives angles and .
3.Should rotating a vector change its norm?Answer
Not in exact arithmetic. Each 2D rotation is orthogonal; numerical tests allow a dtype-appropriate tolerance.
4.For a full paired rotation, what should happen with an odd head width?Answer
Reject it unless a separate partial-rotation contract explicitly leaves a channel unrotated. The assignment's full paired construction needs an even width.
Practice
- CS336 Assignment 1:
ropeand rotarymultihead_self_attentionProblem (
rope), section 3.4.3, and Applying RoPE, section 3.4.5; implementrun_ropeandrun_multihead_self_attention_with_ropeand passtest_ropeandtest_multihead_self_attention_with_ropeAdd your own position-zero, nonzero-offset, common-offset dot-product, norm-preservation and odd-width rejection tests. Test
float32and a supported low-precision dtype. For positions beyond a precomputed table, test the documented extension or rejection policy.
You're done when
Both named public tests and your offset and pairing tests pass, and you derive the relative-position identity without looking at the notebook.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 4 more in the section
- Modern LLM Notebook - decoder construction pathWalking Labs · primary
Work through English notebooks 03-embedding, 04-position-encoding, 05-transformer-block, 06-mini-gpt and the selected normalization, RoPE, GQA and SwiGLU comparisons in 08-gpt2-to-modern-models. Re-derive shapes and rerun with changed dimensions.
- Stanford CS336 Assignment 1 - model contractStanford University · required
Use the named linear, embedding, rmsnorm, positionwise_feedforward, rope, softmax, scaled_dot_product_attention, multihead_self_attention, transformer_block, transformer_lm and transformer_accounting specifications and public tests. Keep implementation independent and respect the course AI and honor-code boundary.
Also in this section
- LLMs from Scratch companion - attention and GPT constructionSebastian Raschka · required
Use the ch03 attention notebooks and ch04 model code. Rebuild the model without a high-level Transformer module and compare one forward and backward path with an independent small reference.
- PyTorch scaled dot product attention referencePyTorch · support
Use the functional contract only after the explicit attention oracle passes. Transfer identical weights and masks, compare outputs and gradients, and explain dtype, causal and dropout behavior from the documented semantics.
- Deep-ML candidate - three transformer closing drillsDeep-ML · optional
After the platform quality sample passes, attempt at most problems 490, 53 and 904 as changed-prompt drills for attention shapes and multi-head composition. Preserve independent tests; a judge result does not replace the section checkpoint.
- nanoGPT - residual projection initializationAndrej Karpathy · support
Read
model.py:MLP,Block,GPT.__init__'s special scaled initialization ofc_proj.weight, andGPT._init_weights. Contrast the depth-dependent residual initialization with CS336's component initialization; do not adopt the training or generation code.