Unit 5 of 11 · about 5 hours · derive, implement

RoPE offsets, extrapolation failure, and position interpolation, NTK-aware scaling and YaRN

Long context fails in a specific way: some rotation angles at long range were never seen in training. Knowing which dimension pairs carry that risk lets you choose a scaling method for a stated length and know what fine-tuning it still needs.

You'll be able to

  • Derive the relative-position property of RoPE with explicit position offsets, and explain why neither it nor the long-term decay bound guarantees behavior beyond the trained length.
  • Implement position interpolation, NTK-aware base scaling, NTK-by-parts and the YaRN attention temperature as maps on positions and frequencies, and predict which dimension pairs each one changes.
  • Measure loss against evaluation length on a small trained model for direct extrapolation and each scaling method, and state what the measurement does not show.

Covers

RoPE, position offsets and extrapolation failurePosition interpolation, NTK-aware scaling and YaRN vocabulary
1

Read

In this order, only the parts listed

0 of 5 done

  1. RoFormer: Enhanced Transformer with Rotary Position Embedding (arXiv:2104.09864v5)RoFormer: Enhanced Transformer with Rotary Position Embedding (Su et al., 2021)

    Section 3.1 (Equation 11, the relative-position requirement), Sections 3.2.1 and 3.2.2 (2D case and general form), Section 3.3 (properties) and Section 3.4.3 with Figure 2 (long-term decay)

    Skip Sections 4 and 5, the Chinese and BERT-style experiments.

  2. Extending Context Window of Large Language Models via Position Interpolation (arXiv:2306.15595v2)Extending Context Window of Large Language Models via Positional Interpolation (Chen et al., 2023) and YaRN (Peng et al., 2023)

    Section 2.2 (direct extrapolation and Figure 2), Section 2.3 (the method and Theorem 2.1), Section 3.2 (Table 1), Section 3.3 (passkey retrieval, Table 4)

  3. YaRN: Efficient Context Window Extension of Large Language Models (arXiv:2309.00071v3)Extending Context Window of Large Language Models via Positional Interpolation (Chen et al., 2023) and YaRN (Peng et al., 2023)

    Sections 2.2 and 3.1 to 3.4 (Equations 10 to 15), Appendix A.1 to A.3 (Equations 16 to 23)

    Stop before Section 4. Use Appendix A.1 (Equation 16) for the direction of position interpolation; see the traps.

  4. CS336 Spring 2026, Lecture 3 slidesCS336 2026 - Architectures and Attention Alternatives

    Slides 30 to 35 (position embeddings, RoPE, the actual RoPE math, implementation)

  5. Modern LLM Notebook: Long Context ExtrapolationModern LLM Notebook - Architecture Frontiers

    Sections 4 to 9 (RoPE, why extrapolation fails, position interpolation, NTK-aware) and Section 12 (how to validate long context)

    Do not use Section 10 or the yarn branch of ExtrapolatableRoPE as a description of YaRN (see the traps).

2

Focus on

  • RoPE rotates each pair of a query or key by the angle with , so depends on only. With explicit position IDs this also holds for any common offset, which is what a KV cache and a packed batch rely on.
  • Relative encoding does not make extrapolation safe. The PI paper shows a fitted attention-score function that stays within on the trained range and reaches values above 8000 outside it (Figure 2), and calls the RoFormer decay bound too loose to rule that out. YaRN's account: pairs whose wavelength exceeds the trained length never complete a rotation in training, so long-range angles are new to the model.
  • The four maps, with . PI divides positions by . NTK-aware sets the base to , which leaves the first pair unchanged and divides the last pair's frequency by exactly . NTK-by-parts leaves pairs with alone, divides pairs with by and ramps between (, for Llama). YaRN adds one scalar on the attention logits, , applied by scaling both queries and keys by .
  • Fine-tuning needs differ. PI needs a short fine-tune and is worse than the other maps without one in the small run of the reproduce step. NTK-aware works better than PI without fine-tuning, but the YaRN paper reports that fine-tuning with it gives inferior results to PI. With dynamic scaling the scale follows the current length, so cache keys before applying RoPE.
Common mistakes · 3
  • Applying position interpolation in the wrong direction. YaRN v3 Equation 9 writes with , which would stretch positions; its own Appendix A.1 Equation 16 and the PI paper use . Divide by .
  • Taking the Modern LLM Notebook's Section 10 as YaRN. It describes NTK base change plus a per-dimension temperature, while YaRN's temperature is one scalar on all logits and the per-dimension step is the frequency ramp of NTK-by-parts. The notebook's ExtrapolatableRoPE implements the yarn strategy as NTK-aware only and marks it as simplified.
  • Calling a method 'extended' from one perplexity number or one passkey test. In the small run in the reproduce step, YaRN's temperature did not help (its loss was slightly above NTK-by-parts at every length), and a 16-pair model is not a Llama. Compare methods at several lengths and seeds, and report whether any fine-tuning happened.
3

Try it yourself

Closed-book, before checking anything

Closed-book, derive pair by pair, then compute for head size 128, , , , the number of pairs with , with and in the ramp (18, 21 and 25 of the 64 pairs). Compute the NTK-aware base for (82,684.6) and check that the last pair's frequency ratio is 0.125 exactly. Implement RoPE with explicit position IDs and check in float64 that for random the score at positions (2, 5) equals the score at (12, 15), and that with PI at the score at (40, 100) equals the unscaled score at (10, 25), so distance 60 looks like distance 15. Then measure: labeled example, not a target, from a 4-layer pre-norm decoder (width 128, 4 heads, head size 32, base 10000, byte-level text, 2500 steps at length 128, cosine schedule, one seed, PyTorch 2.14.1 on CPU, no fine-tuning at the longer lengths). Mean held-out next-byte loss in nats at length 128 was 1.119. At lengths 256, 512, 1024 and 2048 () direct extrapolation gave 2.008, 2.979, 3.657 and 4.241, PI 2.985, 3.802, 4.152 and 4.619, NTK-aware 1.437, 2.058, 2.789 and 3.580, NTK-by-parts 1.807, 2.568, 3.041 and 3.606, and YaRN 1.825, 2.613, 3.083 and 3.644. Your numbers will differ, and with another seed, model or corpus the ordering can too; compare methods across seeds rather than against this run.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Show that the RoPE score depends only on .Answer

    Per pair, , because rotations are orthogonal and compose by adding angles. So is a function of , and for every pair, hence of the position difference only.

  2. 2.For head size 128 and base 10000, what base does NTK-aware scaling use for , and what happens to the first and last pairs' frequencies?Answer

    . The first pair has either way and is unchanged. The last pair's frequency is multiplied by exactly , as in position interpolation.

  3. 3.With PI at , what does the model see for two tokens that are 60 positions apart, and what is the cost?Answer

    They look 15 positions apart, because positions are divided by 4. The model never sees angles beyond the trained range, but all neighboring tokens are 4 times closer in angle, so local resolution drops. That is the reason a short fine-tune is needed.

  4. 4.For , what multiplier does YaRN apply to the attention logits, and how is it implemented without changing the attention code?Answer

    (so ). Scale both the queries and the keys by , for example by scaling the cached rotary cosine and sine tables.

  5. 5.A model passes a passkey test at 4 times its trained length with a scaled RoPE and no fine-tuning. What else do you need before you say it handles that length?Answer

    Loss or perplexity against length on held-out long documents, tasks that need information spread across the context, the same tests at the trained length (scaling can hurt there), and more than one seed or document set. A single retrieval test shows that one capability exists at that length.

5

Practice

  • TensorTonic: Rotary Query and Key Embeddings

    Free problem cs336-l03-rotary-query-key-embeddings, function rotary_embed(q, k, positions, inv_freq)

    The three public cases check zero and one positions, a fractional angle from position 50 with inv_freq=[0.01], and batch-specific position offsets of shape (B, S). The caller supplies the frequencies, so this is the place to plug in the PI, NTK-aware and NTK-by-parts maps. They do not test gradients or dtype. Add your own relative-offset and float16 tests.

  • Loss against length for four scaling methods on your own decoder

    YaRN Section 3 and Appendix A.2; write one function per map that returns inverse frequencies and a logit multiplier, test it against the exact numbers in the reproduce step, then repeat the measurement above

    Use your own small decoder trained at a short length. Evaluate at 2, 4, 8 and 16 times that length without fine-tuning, with three seeds if your budget allows, and report which methods needed fine-tuning in the papers.

You're done when

Your RoPE passes the offset and PI-equivalence tests in float64, your four maps reproduce 18, 21, 25 and 82,684.6, and you have a loss-against-length table for your own model with the fine-tuning status stated.

Only when you can do this without notes.

Leads to

Notes

Resources · 4 for this unit, 14 more in the section
  • CS336 2026 - Architectures and Attention AlternativesStanford University · primary

    Study the Lecture 3 slides (lecture_03.pdf, architectures and hyperparameters) and Lecture 4 slides (lecture_04.pdf, attention alternatives and mixture of experts) in stanford-cs336/lectures, then implement the Assignment 1 Section 3.3 to 3.5 pieces (RMSNorm, SwiGLU, RoPE, causal attention, the pre-norm block) against its tests. Reconstruct every parameter and state equation before you change one mechanism. Keep GPUs, kernels and parallelism (Lectures 5 to 8) for their own tracks.

  • RoFormer: Enhanced Transformer with Rotary Position Embedding (Su et al., 2021)Zhuiyi Technology · required

    Read Section 3: the rotation-matrix form of RoPE, why the attention score depends only on relative position, and the long-distance decay property. Base 10000 is the original choice; later models raise it.

  • Extending Context Window of Large Language Models via Positional Interpolation (Chen et al., 2023) and YaRN (Peng et al., 2023)Meta AI; Nous Research · support

    Read Position Interpolation Sections 2 and 3 (scale positions by the length ratio instead of extrapolating), then YaRN Section 3 (frequency-dependent interpolation and the attention temperature). Both still fine-tune. YaRN is at https://arxiv.org/abs/2309.00071.

  • Modern LLM Notebook - Architecture FrontiersWalking Labs · support

    Use notebooks-en/part2-training/08-gpt2-to-modern-models.ipynb, 11-mla-kv-cache.ipynb and 13-moe.ipynb, and notebooks-en/part4-frontiers/27-long-context.ipynb and 30-efficient-attention.ipynb. Implement only the one variant selected for the checkpoint.

Also in this section

  • OLMo 2 Open Model and Training RecipeAllen Institute for AI · required

    Read Section 2.1 (architecture), Section 3.2 (initialization) and Sections 3.3.1 to 3.3.3 (non-parametric norm to RMSNorm, reordered norm with QK-norm, z-loss) and Table 1, then find the same settings in a released configuration. The changes were adopted as a package, so the report cannot attribute stability to any single one.

  • Build a Large Language Model (From Scratch), Chapters 3 and 4Sebastian Raschka / Manning · support

    Use Chapter 3 (causal multi-head attention, pp. 50-91) and Chapter 4 (the GPT model, pp. 92-127) as the smallest runnable decoder, then the companion bonus folders ch04/04_gqa and ch04/07_moe for one bounded variant. The printed chapters use GPT-2 parts (LayerNorm, GELU, absolute positions); the modern pieces live only in the bonus folders.

  • On Layer Normalization in the Transformer Architecture (Xiong et al., 2020)Microsoft Research Asia · support

    Read Figure 1 and Sections 3 and 4: why Post-LN gradients near the output are large at initialization and need warmup, and why Pre-LN does not. The analysis holds at initialization only and assumes uniform attention weights and Gaussian inputs there.

  • GLU Variants Improve Transformer (Shazeer, 2020)Google · support

    Read Section 2 (the GLU family and SwiGLU) and Section 3.1 (hidden width cut from 3072 to 2048 so parameters match), then Table 1, where GEGLU edges out SwiGLU on the longest run. Check the matching arithmetic yourself.

  • GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (Ainslie et al., 2023) with Fast Transformer Decoding: One Write-Head is All You Need (Shazeer, 2019)Google Research · support

    Read MQA Sections 2 and 3 (one shared key and value head to cut decoding memory traffic), then GQA Section 2 (grouped heads as the interpolation, mean-pooled uptraining with 5% of pretraining compute) and Table 1. Both report encoder-decoder results. MQA is at https://arxiv.org/abs/1911.02150.

  • Small-Scale Proxies for Large-Scale Transformer Training Instabilities (Wortsman et al., 2023)Google DeepMind · support

    Read Section 3.1: attention-logit growth and output-logit divergence reproduced in small models at high learning rates, and the QK-layernorm and z-loss fixes (Figures 1 to 4). It explains two of the OLMo 2 choices; transfer to a specific large run is argued, not proven.

  • TensorTonic - Architecture and Attention AlternativesTensorTonic · support

    Solve RMSNorm Forward Pass (cs336-l03-rmsnorm-forward), Parameter-Matched SwiGLU Block (cs336-l03-parameter-matched-swiglu), Rotary Query and Key Embeddings (cs336-l03-rotary-query-key-embeddings), Causal Grouped-Query Attention (cs336-l03-causal-grouped-query-attention), Top-k MoE Router with Load Statistics (cs336-l04-topk-moe-router) and one of cs336-l04-linear-attention-duality or cs336-l04-mamba2-gated-state-scan. Add capacity and token-drop cases the router tests lack. Public test cases check the listed edge cases, not gradients or the hidden grader, so keep your own tests beside each solution.

  • Decoder-Only Transformer StackRoadmap-Final · support

    Extend the already-tested decoder with the chosen mechanism. Preserve its slow oracle, causal and position tests, generation behavior and model arithmetic.

  • Switch TransformersGoogle Research · depth

    Use Equations 4 to 6 (the load-balancing loss), Figure 3 (capacity factors), Table 3 (smaller initialization for stability) and the Appendix F pseudocode as the deeper MoE reference. Reproduce only a tiny router experiment; full sparse pretraining belongs to later systems work.

  • ST-MoE: Designing Stable and Transferable Sparse Expert Models (Zoph et al., 2022)Google · depth

    Read Section 3 and Appendix B: the router z-loss in Equation 5, its coefficient 0.001 and the load-balance weight in Equation 6, and why update clipping stabilizes runs at a quality cost. Its setting is encoder-decoder T5.

  • DeepSeek-V2, Section 2.1 (Multi-head Latent Attention)DeepSeek-AI · optional

    Read Sections 2.1.1 to 2.1.4: low-rank joint key-value compression, decoupled RoPE and the cache comparison. The 93.3% cache reduction is against their own 67B model, not a portable ratio.

  • Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality (Dao and Gu, 2024)Princeton and CMU · optional

    Read Section 1 and Sections 5 and 6, including Listing 1 (the segsum reference), for a state-space alternative. Skip the full duality theory; compare against a linear-attention baseline in your own harness.

  • Modern LLM Notebook, Appendix B: From Parameters to MemoryWalking Labs · support

    Appendix B Section 1 (parameters per block and per model, GQA and SwiGLU) and Section 2 (activation memory). Recount the activation tables with autograd hooks; the notebook lists produced tensors, not saved ones. Pin commit 979eecf.

  • Deep Learning Tuning PlaybookGoogle Research · support

    Read 'Identifying scientific, nuisance, and fixed hyperparameters' and 'Determining whether to adopt a training pipeline change or hyperparameter configuration' as the protocol for comparing architecture variants (per-arm learning rate, trial variance). Skip the batch-norm material. Last commit 2024; pin commit 7554a51.