Positional Encoding and RoPE
📍 What is positional encoding? Attention compares every token with every other token but has no idea of order: shuffle the input and the outputs shuffle the same way. A positional encoding adds that missing information, either by adding a position vector to each token's embedding or, in rotary embeddings (RoPE), by rotating each query and key by an angle that grows with its position.
Mercor's machine learning engineer onsite asked about position embeddings among the Transformer fundamentals that followed a train-a-small-LLM project (the question).
The Prompt
Positional encodings are short to code, so the interviewer grades whether you know why they are needed, what each kind can and cannot do, and whether your RoPE is exactly right, since an off-by-one in its layout fails silently.
"Attention has no notion of order. Show that, then add positions: first a sinusoidal encoding, then rotary embeddings applied to the queries and keys."
Clarifying Questions
You: What shapes? I'll assume token embeddings (B, T, D) and, for RoPE, per-head queries and keys
(B, H, T, d_head) with d_head even.
Interviewer: Yes.
You: For RoPE, which dimensions form a rotating pair? The original paper pairs (0, 1), (2, 3), ...; many
open models pair dimension i with i + d/2.
Interviewer: Use the half-split layout, i with i + d/2. Base 10,000.
You: During generation the new token sits at position T, not 0. Should the function take a position offset?
Interviewer: Yes, it should work for one token at a time.
You: Do you want a learned embedding as well?
Interviewer: Briefly. Tell me what goes wrong with it.
What You'll Build
sinusoidal(T, D) -> (T, D): fixed encodings added to token embeddings.LearnedPositions(max_len, D): annn.Modulereturning(T, D)for a lengthT.rope_cache(T, d_head) -> (cos, sin): two(T, d_head)tables, computed once.apply_rope(x, cos, sin, offset=0) -> (B, H, T, d_head): rotated queries or keys.