CD0004 Rotary Position Embedding Implementation

Mode B · Build & Trace 30 Min PyTorch 2.x · FP32/BF16 4 Tensor Blanks

Meta's GenAI org develops the Llama model family, whose rotary position encoding every Llama inference kernel depends on. In a foundation-model coding interview for that stack, you are asked to implement Rotary Positional Embedding (RoPE) from scratch in PyTorch, exactly as Llama 3 uses it with base b = 500000, and without any HuggingFace transformers utilities. The inputs are query and key tensors of shape (B, H, T, D) with an even head dimension D. You also get an explicit position_ids tensor of shape (B, T), so the same code serves KV-cached decoding and left-padded batches.

You must precompute the inverse frequency band inv_freq, build the cosine and sine tables for arbitrary position_ids, and apply the 2D pairwise rotation to q and k in real-valued FP32 arithmetic before casting back to the input dtype. Forbidden: transformers helpers such as apply_rotary_pos_emb, and complex-number shortcuts (torch.view_as_complex, torch.polar) inside the implementation. Output shapes and dtypes must equal the inputs, and the table must cost O(BTD) memory with no per-head copies.

Fill in the 4 core tensor operations in the skeleton and trace the broadcasting shapes from (D/2,) and (B, T) to (B, 1, T, D). Then explain why building cos and sin in BF16 corrupts long-context positions, and write a test confirming that \langle \mathrm{RoPE}(q, m), \mathrm{RoPE}(k, n) \rangle depends only on the offset m - n.

RoPE Skeleton (Fill Blanks 1–4):

01  import torch
02  # Real-valued FP32 rotation only: no transformers helpers, no view_as_complex.
03
04
05  class RotaryEmbedding(torch.nn.Module):
06      def __init__(self, head_dim: int, base: float = 500000.0):
07          super().__init__()
08          assert head_dim % 2 == 0, "RoPE needs an even head_dim"
09          # TODO (Blank 1): inv_freq of shape (D // 2,), computed in FP32
10          inv_freq = ...
11          self.register_buffer("inv_freq", inv_freq, persistent=False)
12
13      @torch.no_grad()
14      def forward(self, position_ids: torch.Tensor):
15          # position_ids: (B, T) int64 -> cos, sin: (B, 1, T, D) in FP32
16          # TODO (Blank 2): per-token angles, widened to D, plus a head axis
17          emb = ...
18          return emb.cos(), emb.sin()
19
20
21  def rotate_half(x: torch.Tensor) -> torch.Tensor:
22      # x: (B, H, T, D) -> (B, H, T, D)
23      # TODO (Blank 3): rotate each channel pair by 90 degrees
24      ...
25
26
27  def apply_rope(q, k, cos, sin):
28      # q, k: (B, H, T, D) any float dtype; cos, sin: (B, 1, T, D) FP32
29      # TODO (Blank 4): rotate in FP32, then cast back to the input dtype
30      q_out = ...
31      k_out = ...
32      return q_out, k_out
Operator contract for RoPE: q and k of shape (B, H, T, D) in bf16 and position_ids of shape (B, T) feed a RoPE core marked with a question mark, which outputs rotated q and k with the same shape and dtype; a note states the goal that the attention score depends only on m minus n

Figure 1: two activation tensors and a position map go in, and rotated tensors with the same shape and dtype come out. The tensor plumbing in the middle is yours to write.

Interactive PyTorch Workspace: Switch to the split-screen workspace to implement RoPE Blanks 1-4 and run relative-offset and 100k-context BF16 checks.

Open in Colab ↗
Progressive Hints (Free · Zero Spoilers)
1Inspection Checklist (Where to Look)

(1) Frequency Band: Build D/2 inverse frequencies with even exponents 2i/D in FP32.
(2) Explicit Positions: Compute per-token angles directly from position_ids rather than arange(T) so cached decode and left-padding work.
(3) Broadcast Over Heads: Keep the cos/sin tables at shape (B, 1, T, D) so memory does not scale with H.
(4) FP32 Rotation Boundary: Pair (i, i + D/2) consistently, rotate in FP32, and cast back to the input dtype only at the end.

2Visual Review Map (Figure 2)
Shape trace diagram: Blank 1 produces inv_freq of shape (D/2,) in FP32, position_ids of shape (B, T) enters as (B, T, 1), Blank 2 produces angles (B, T, D/2) then emb (B, T, D), the cos and sin tables are (B, 1, T, D) in FP32 and broadcast over heads into Blanks 3-4, which combine them with q and k of shape (B, H, T, D)

Figure 2: The shape contract for the table builder. Blank 1 produces the FP32 band, and the later blanks must carry it through each intermediate shape to a table that broadcasts over heads.

3Interviewer Nudge & Line Focus

Check precision boundaries and broadcasting rank at each of the 4 blanks:

Blank 1 (Frequency Band): Generate even indices 0, 2, ..., D - 2 explicitly with dtype=torch.float32 so instantiating the module under a BF16 default dtype never quantizes base ** (-2i / D).
Blank 2 (Broadcast Table): At position 100,000, BF16 ULP spacing is 512 tokens! Cast position_ids to FP32 before the outer product, concatenate the D/2 angles twice along dim=-1, and unsqueeze a size-1 head axis to get (B, 1, T, D).
Blank 3 (Pairwise 90° Turn): Under Llama's half-split convention, channel i pairs with channel i + D // 2; rotating (x1, x2) by +90° yields (-x2, x1) concatenated along the last axis.
Blank 4 (FP32 Apply + Cast): Promote q and k to .float() before computing x * cos + rotate_half(x) * sin, then cast the result back to q.dtype so downstream attention kernels receive the original BF16/FP16 dtype.
Answer
Login to view more content

Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *