Foundations to Frontier
Tests
F. NLP and Large Language Models › F4 Transformer Language Models

Architecture Refinements: RMSNorm, SwiGLU, RoPE and GQA

Modern LLMs (LLaMA, Mistral, Qwen and others) keep the GPT blueprint but swap in several refinements. RMSNorm normalises by the root-mean-square only, dropping LayerNorm's mean and bias: cheaper and just as stable. SwiGLU replaces the MLP's single activation with a gated product of two projections, improving quality at equal parameters. Rotary position embeddings (RoPE) rotate queries and keys by position-dependent angles, so attention scores depend only on relative offsets and no position table is needed. Grouped-query attention (GQA) shares each key/value head among several query heads, shrinking the KV cache 4–8× with little quality loss. This page explains each change, its maths and its cost. In the exercises you implement RMSNorm, SwiGLU, RoPE and GQA head grouping, then test position schemes on sequences longer than any seen in training. Trained on 16-token sequences, learned absolute positions and RoPE both solved the copy task within that length (loss 0.60 and 0.63, floor 0.50), and no positions failed (2.18). Beyond 16 tokens both failed (2.31 and 2.13): RoPE alone does not extrapolate.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Small upgrades that add up

Today’s language models are built like the original GPT, with a few parts swapped for better versions. A simpler normalisation step (RMSNorm). A gated activation in the feed-forward part (SwiGLU). A neat way of encoding positions by rotating vectors, so the model sees how far apart two words are rather than their absolute places (RoPE). And sharing some attention memory between heads (GQA), so long conversations need less memory. The demo shows that with RoPE only the distance between positions matters.

LLM lab
Score for query at 5, key at 2: -0.7200; at positions 5 and 2: -0.7200. RoPE rotates query and key by angles proportional to position, so their dot product depends only on the offset (3).
Why engineers care

These refinements decide whether a model fits in an embedded GPU’s memory and how fast it answers: GQA alone can cut the per-conversation memory of a 7B model from 4 GiB to 1 GiB at 8k tokens.

📝 Quick check (Level 0)
0/3 answered
  1. 1. RMSNorm differs from LayerNorm by…
  2. 2. RoPE makes attention scores depend on…
  3. 3. GQA shares key/value heads to save…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • RMSNorm: y = x / √(mean(x²) + ε) ⊙ g. No mean subtraction and no bias: d parameters instead of 2d, and slightly faster.
  • SwiGLU: MLP(x) = (SiLU(xW) ⊙ xV) W₂. Three matrices, so the hidden width is about (2/3)·4d to keep the parameter count (LLaMA: 11,008 for d = 4096).
  • RoPE: rotate each pair of query and key dimensions (2i, 2i + 1) by angle m·θ_i with θ_i = 10000^(−2i/d). Then q_m·k_n depends only on m − n. Wavelengths range from 2π to tens of thousands of positions. No learned position table.
  • GQA: n_q query heads share n_kv < n_q key/value heads (multi-query attention: n_kv = 1). The KV cache shrinks by n_q/n_kv: 32 → 8 heads cuts 4 GiB to 1 GiB per 8k-token sequence for a 7B model.
  • Others in the same family: pre-norm placement, no biases in linear layers, tied or untied embeddings, and QK-norm for stability (F5-4).
📝 Quick check (Level 1)
0/3 answered
  1. 1. KV-cache reduction from 32 to 8 KV heads:
  2. 2. SwiGLU hidden width for d = 4096 (before rounding):
  3. 3. RMSNorm parameters for d = 4096:

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Refinements in code

Exercise 1.

  • Implement RMSNorm and SwiGLU.
  • Implement RoPE and check that scores depend only on the offset and that rotation preserves norms.
  • Map query heads to shared KV heads (GQA).

Practice.

  • Hugging Face LLaMA-style configs expose rms_norm_eps, intermediate_size, rope_theta and num_key_value_heads.
  • RoPE is applied to Q and K after projection, inside every attention layer, and works with the KV cache (F8).
  • To convert a multi-head checkpoint to GQA, mean-pool the K and V heads within each group, then fine-tune briefly (uptraining).
  • Keep rope_theta and the position handling identical between training and inference; changing them is how context is extended (F4-6).
from transformers import LlamaConfig
cfg = LlamaConfig(hidden_size=4096, intermediate_size=11008, num_attention_heads=32,
                  num_key_value_heads=8, rms_norm_eps=1e-5, rope_theta=10000.0, max_position_embeddings=8192)
print(cfg.num_attention_heads // cfg.num_key_value_heads, "query heads share each KV head")
🐍 Exercise 1: RMSNorm, SwiGLU, RoPE and GQA
Implement RMSNorm, a SwiGLU MLP, rotary embeddings and the GQA head mapping.
📝 Quick check (Level 2)
0/3 answered
  1. 1. The config field for GQA in LLaMA models:
  2. 2. RoPE is applied to…
  3. 3. Converting MHA to GQA uses…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why RoPE is relative. A rotation R_m by angle mθ satisfies (R_m q)·(R_n k) = q·R_(n−m) k, because rotations are orthogonal and compose by adding angles. So attention depends only on n − m, for every pair of dimensions.

Why it still does not extrapolate. Relative scores do not imply generalisation to unseen offsets. A model trained on 16 tokens has never seen offsets above 15. At longer lengths, high-frequency dimensions produce essentially random scores for those offsets, and some distant keys outscore the right one. In exercise 2 RoPE failed beyond the training length just like learned positions. Context extension needs interpolation, rescaling or windowing (F4-6).

Why GQA costs little quality. Key/value heads in multi-head models are highly redundant. Ainslie and colleagues (2023) showed GQA with 8 groups matches multi-head quality closely while running at nearly multi-query speed, because generation is limited by memory bandwidth for the KV cache, not by compute.

📝 Quick check (Level 3)
0/3 answered
  1. 1. (R_m q)·(R_n k) equals…
  2. 2. RoPE fails beyond training length because…
  3. 3. Generation speed is usually limited by…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Do rotary embeddings let a model handle sequences longer than it was trained on?

History.

  • B. Zhang and R. Sennrich, “Root mean square layer normalization” (NeurIPS 2019).
  • N. Shazeer, “GLU variants improve Transformer” (2020).
  • J. Su et al., “RoFormer: enhanced transformer with rotary position embedding” (2021).
  • J. Ainslie et al., “GQA: training generalized multi-query transformer models from multi-head checkpoints” (EMNLP 2023).
  • O. Press, N. Smith and M. Lewis, “Train short, test long: attention with linear biases” (ICLR 2022), ALiBi.

Exercise 2.

  • Task: copy-8-back (vocabulary 10, entropy floor 0.50 nats).
  • Model: the one-layer GPT with causal attention and hand-written backpropagation, trained on 16-token sequences, with three position schemes:
    • none;
    • learned absolute embeddings (rows for positions above 16 stay at their random initial values);
    • RoPE on queries and keys.
  • Test: 48-token sequences, with loss measured separately on positions within the training length and beyond it.
positions loss within 16 tokens loss beyond 16 tokens
none 2.180 2.175
learned absolute 0.600 2.314
RoPE 0.626 2.130
  • Both position schemes solve the task in-distribution; RoPE does it with no position parameters at all.
  • Neither extrapolates: beyond 16 tokens both are near the uniform loss of 2.30. Learned positions there are untrained random vectors. For RoPE, the attention at long range also sees offsets above 15, never seen in training, which act as distractors.
  • The lesson for long context: relative encodings are necessary but not sufficient. Sliding windows or position interpolation are needed (F4-6 tests this).
  • Seed 1: within-length losses 0.591 (learned) and 0.618 (RoPE); beyond, 2.352 and 2.139.
🐍 Exercise 2 (research): do rotary embeddings let a model handle sequences longer than it was trained on?
Train the same GPT with no positions, learned absolute positions and RoPE on short sequences; test within and beyond the training length.

Refinements in AI, robotics and aerospace

  • Edge deployment: GQA and RMSNorm reduce memory and latency for onboard assistants.
  • Long logs and telemetry: understanding why position encodings fail beyond training length is essential before feeding long sequences.
  • Design lesson: test position handling explicitly at the lengths you will use in deployment.

References

  1. B. Zhang and R. Sennrich (2019). “Root mean square layer normalization.” NeurIPS.
  2. N. Shazeer (2020). “GLU variants improve Transformer.” arXiv:2002.05202.
  3. J. Su, Y. Lu, S. Pan, A. Murtadha, B. Wen and Y. Liu (2021). “RoFormer: enhanced transformer with rotary position embedding.” arXiv:2104.09864.
  4. J. Ainslie et al. (2023). “GQA: training generalized multi-query transformer models from multi-head checkpoints.” Proc. EMNLP.