Phase 01/Inside the transformer block/Positional encoding
PHASE 01 · Inside the transformer block

Positional encoding

0%
5 h5 subtopics2 lessons · 1 required
In plain English

Attention compares every word with every other word, but on its own it has no idea which word came first. "Dog bites man" and "man bites dog" would look identical. Positional encoding fixes this by stamping each word with information about where it sits in the sentence. Think of a stack of photographs from a trip: the photos alone do not tell you the order, so you write a date on the back of each one. Older models wrote a fixed or learned number pattern on each word; modern models like Llama instead rotate the word's numbers by an angle that depends on its position, which makes the comparison between two words depend only on how far apart they are.

Why it matters

The positional scheme decides a model's maximum context length and how it degrades beyond it, which is a daily serving concern. RoPE is applied inside the attention kernel to Q and K at every decode step, so it affects kernel design and what exactly gets stored in the KV cache.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, Crusoe, Databricks, Hugging Face, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Implement sinusoidal and rotary position encodings in PyTorch.
  • Verify numerically that RoPE makes q.k depend only on relative position.
  • Inspect GPT-2's learned position embedding matrix and interpret its structure.
  • Explain why a learned table caps context length while RoPE does not hard-cap it.
  • Locate where RoPE is applied inside a Hugging Face Llama attention module.

Key concepts

Sinusoidal encoding
Fixed sin/cos waves of geometrically spaced frequencies added to token embeddings, from the original transformer paper.
Learned absolute positions
A trainable (max_positions, d_model) table, as in GPT-2's wpe; cannot represent positions beyond its size.
Rotary position embedding (RoPE)
Rotating pairs of Q and K dimensions by an angle proportional to position, so dot products encode relative distance.
Relative position
The offset m-n between two tokens; RoPE and ALiBi make attention depend on this rather than on absolute indices.
RoPE base (theta)
The constant (10000 in Llama 2, 500000 in Llama 3) that sets rotation frequencies; raising it stretches usable context.
Context extension
Tricks such as position interpolation or NTK-aware scaling that let a RoPE model run past its training length.

Subtopics

  1. 1. Why attention is permutation-invariant

    Show that shuffling input tokens shuffles attention outputs identically without positional information.

  2. 2. Sinusoidal and learned absolute encodings

    The original sin/cos formula and GPT-2's learned wpe table; both are added to the input embeddings once.

  3. 3. Rotary position embedding

    Rotating (q_2i, q_2i+1) pairs by position*theta_i; the relative-position identity and the rotate_half implementation.

  4. 4. Context length and extrapolation

    Learned tables hard-fail past max_positions; RoPE degrades gradually and can be stretched by changing theta or interpolating.

  5. 5. Where RoPE lives in a kernel

    Applied to Q and K after projection and before QK^T; cached K is stored already rotated in most engines.

Resources

Hands-on lessons

L1

Implement RoPE and prove the relative-position property

CPU · your Macnotebook90 minrequired

Goal · Write sinusoidal and rotary encodings from scratch and numerically demonstrate that RoPE dot products depend only on relative offset.

  1. 1Implement sinusoidal_pe(T, d) from the formula and plot it as a (T, d) heatmap for T=128, d=64.
  2. 2Implement rope(x, positions, theta=10000) using the rotate_half trick on tensors of shape (T, d).
  3. 3Generate a random q and k of dimension 64; compute dot(rope(q, m), rope(k, n)) for (m, n) in [(0, 5), (10, 15), (100, 105)] and show the three values are equal within 1e-5.
  4. 4Repeat with sinusoidal added encodings and show the dot products are not equal.
  5. 5Load TinyLlama and compare your rope output on a random tensor with the model's apply_rotary_pos_emb using its rotary_emb cos/sin.
  6. 6Change theta to 500000 and plot how the rotation angle of dimension pair 0 and pair 31 changes with position.
Deliverable
A notebook with the equality assertion, the TinyLlama match and the two heatmaps.
Check
The three RoPE dot products agree within 1e-5 and your rope matches apply_rotary_pos_emb at atol 1e-5.
L2

Inspect GPT-2's learned position table and break its limit

CPU · your Macexperiment45 minoptional

Goal · Visualise structure in GPT-2's wpe matrix and observe what happens past 1024 tokens for GPT-2 versus TinyLlama.

  1. 1Load gpt2; take model.transformer.wpe.weight of shape (1024, 768).
  2. 2Compute the (1024, 1024) cosine-similarity matrix between position vectors and plot it; describe the band structure.
  3. 3Build a 1100-token input and run gpt2; record the exception.
  4. 4Run TinyLlama (max_position_embeddings 2048) on a 2300-token input and record that it runs, then compare next-token loss on the last 100 tokens against a 1500-token input of the same text.
Deliverable
The heatmap, the GPT-2 error text and the two loss numbers.
Check
GPT-2 raises an index error past 1024 while TinyLlama runs but shows higher loss at 2300 than at 1500.

Build your own

Build your own RoPE

PythonCPU · your Mac~5 h

Sinusoidal and rotary position encodings written from scratch, verified for the relative-position property against Llama's implementation, then stretched past their training length to watch them break.

The real thing: github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py ↗

How you know a stage passes

Write tests/test_rope.py first. Stages assert on tensor equalities (torch.allclose at atol 1e-5) against closed-form expressions and against the Hugging Face Llama rotary functions, and on measured loss numbers written to a results JSON by a small eval script on TinyLlama. Run `pytest -q`; a stage is done when its test passes and all earlier tests still pass.

Stages, in order. Each one leaves you with something that runs.0/5
  1. 01sinusoidal table
    `sinusoidal(T, d)` returns the Vaswani table with sin on even and cos on odd dimensions.
    test · Shape is [T, d]; every row has norm sqrt(d/2) within 1e-4; the table equals the formula from the paper at 10 random (pos, i) entries.
  2. 02rotate pairs
    `rope(x, positions, theta)` rotates each adjacent (or half-split) pair of dimensions by pos * theta_i, with theta_i = 10000^(-2i/d).
    test · Rotating by position 0 is the identity; the norm of each vector is unchanged within 1e-6; rotating by p then -p returns the input within 1e-5.
  3. 03prove the relative-position property
    Dot products of rotated queries and keys depend only on the position difference.
    test · For random q, k and 100 random (m, n) pairs, dot(rope(q, m), rope(k, n)) equals dot(rope(q, m + s), rope(k, n + s)) for shift s within 1e-4, while the unrotated sinusoidal-added version does not.
  4. 04match Llama
    Your RoPE uses the half-split layout and cos/sin cache so it behaves identically to the Hugging Face Llama rotary functions.
    test · Output equals apply_rotary_pos_emb from modeling_llama.py at atol 1e-5 on random [B, H, T, d] inputs with T=512; swapping your function into TinyLlama changes logits by less than 1e-4.
  5. 05break it and stretch it
    An eval script measures TinyLlama next-token loss at 1500 and 3000 tokens with vanilla RoPE, then with position interpolation (scale 2) and an NTK-aware theta change.
    test · The JSON records loss at 3000 tokens higher than at 1500 for vanilla RoPE, and lower at 3000 for at least one of the two stretched variants; the README table lists all six numbers.

Knowledge check

QWhy can GPT-2 not accept a 2000-token prompt?

Its position embeddings are a learned table with exactly 1024 rows; there is no row for position 1024 or beyond.

QWhat property makes RoPE attractive for inference engines?

The score between q at position m and k at position n depends only on m-n, so cached keys can be stored already rotated and new queries just rotate by their own position.

QDoes RoPE add parameters to the model?

No. The rotation angles are fixed functions of position, dimension index and theta.

QWhat happens when you raise the RoPE base theta?

Rotation frequencies drop, so angles grow more slowly with position and the model can distinguish positions over a longer range, which is how Llama 3 extended context.

Completion

  • All 5 subtopics marked done
  • All 1 required lessons done
  • All subtopics marked completed.
  • Lesson l1 check passes.
  • Can state the RoPE relative-position identity and explain rotate_half in words.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →