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 , and without any HuggingFace
transformers utilities. The inputs are query and key tensors of shape with an even head dimension
. You also get an explicit
position_ids tensor of shape , 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 memory with no per-head copies.
Fill in the 4 core tensor operations in the skeleton and trace the broadcasting shapes from and
to
. Then explain why building
cos and sin in BF16 corrupts long-context positions, and write a test confirming that depends only on the offset
.
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
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.
1Inspection Checklist (Where to Look)
(1) Frequency Band: Build inverse frequencies with even exponents
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 so memory does not scale with
.
(4) FP32 Rotation Boundary: Pair consistently, rotate in FP32, and cast back to the input dtype only at the end.
2Visual Review Map (Figure 2)

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:
0, 2, ..., D - 2 explicitly with dtype=torch.float32 so instantiating the module under a BF16 default dtype never quantizes base ** (-2i / D).
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).
i pairs with channel i + D // 2; rotating (x1, x2) by +90° yields (-x2, x1) concatenated along the last axis.
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.
Leave a Reply