On this page
"The model loaded the checkpoint" and "The checkpoint loaded the model" contain the exact same five words, yet reverse who acted on whom. Without a position signal, unmasked self-attention cannot tell those two sentences apart: shuffle the input rows by any permutation , and the output rows simply shuffle by the exact same .
Transformers put order back at three completely different points in the block: additive position embeddings at the input, RoPE rotating projected queries and keys, or ALiBi adding a linear distance penalty directly to attention logits. Understanding where order enters explains both how checkpoints scale to 128K+ context and why subtle bugs (like bfloat16 position rounding or adjacent vs. split-half rotary layouts) silently break attention.
First, watch attention lose the order
Take unmasked self-attention and left-multiply the input rows by a permutation matrix ().[1] Because linear projections act on columns, , , and . Substituting and using orthogonality :
That property, , is permutation equivariance. A fixed causal mask breaks that symmetry by letting token count visible predecessors (enough for Haviv et al.'s NoPos causal decoders to recover approximate positions, while unmasked bidirectional encoders collapse without position signals).[2]
![Content-only attention processes the word vectors for model [1,0], loaded [0,1], and checkpoint [1,1]. Permutation P=[2,0,1] reorders the tokens, both axes of the attention matrix, and outputs together: Attn(PX)=P Attn(X). The first output coordinate moves from [0.802,0.599,0.752] to [0.752,0.802,0.599].](https://assets.leetllm.com/v1/07a36d136a1d/fundamentals/positional-encoding-rope-alibi/illustrations/_generated/position_blind_attention_dark.png)
| Approach | Where position enters | Extra parameters | Examples |
|---|---|---|---|
| Absolute (sinusoidal / learned) | Added to token embeddings | / | Original Transformer, BERT, GPT-2[1][3][4] |
| Rotary (RoPE) | Rotates projected and ( untouched) | RoFormer, Llama family[5][6] | |
| Linear bias (ALiBi) | Added to pre-softmax attention logits | ALiBi[7] |

Absolute position: give every slot a multi-speed fingerprint
The original Transformer adds geometric sine/cosine pairs to each token embedding:[1]
Every pair acts like a dial turning at a different wavelength : at , pair (0, 1) cycles every ~6 tokens to distinguish neighbors, pair (64, 65) cycles every ~20 tokens, and pair (510, 511) takes ~60,611 tokens. By trigonometric addition formulas, stepping forward by is a linear rotation depending only on :
Why add instead of concatenate? Concatenation doubles hidden width from to , quadrupling the size of every matrix ( entries). Adding keeps width , at the cost of mixing content and position into four cross terms when computing . And although the sinusoidal formula is defined past training length, Press et al. showed sinusoidal models still suffer sharp perplexity spikes past .[7]
![Top: smooth sinusoidal waves sin(p * omega_k) across token positions 0 to 32 for d_model=512, contrasting fast pair (0,1), mid-speed pair (64,65), and nearly flat slow pair (510,511), with position p=12 marked. Bottom-left: [sin, cos] coordinates and phase dials at p=12: (-0.537, 0.844) for (0,1), (-0.608, -0.794) for (64,65), and (0.001, 1.000) for (510,511). Bottom-right: cumulative phase angles at p=12 of 12.00, 3.79, and 0.001 radians.](https://assets.leetllm.com/v1/a6b00dc22f86/fundamentals/positional-encoding-rope-alibi/illustrations/_generated/sinusoidal_waves_dark.png)
RoPE: make a shared offset visible inside QK
Rotary Position Embedding (RoPE) moves position out of the embedding table and straight into query-key geometry.[5] For each 2D coordinate pair with frequency , RoPE rotates the pair by angle :
Equivalently, viewing each pair as a complex number , rotation is simply multiplication by . Now take the dot product between a query at position and a key at position . Because , both absolute positions cancel completely, leaving only the relative offset :
Shift both tokens forward by +100 (from (2, 1) to (102, 101)), and their dot product stays identical (0.878). RoPE preserves vector norms , adds zero parameters, and leaves values unrotated so position governs routing without scrambling the content payload.
![For q=k=[1,0] in four RoPE pairs, query position m=4 and key position n=2 give offset −2. Contributions cos((n−m)θ_i) are −0.416, 0.980, 1.000, and 1.000 for θ_i=1, 0.1, 0.01, and 0.001. They sum to 2.564; scaling by √8 gives attention logit 0.906. RoPE rotates Q and K; V is unchanged.](https://assets.leetllm.com/v1/6588c62d7851/fundamentals/positional-encoding-rope-alibi/illustrations/_generated/rope_pair_mechanics_dark.png)
Three RoPE implementation traps you will meet in real code
- Adjacent vs. split-half pairing: Meta's Llama reference pairs adjacent coordinates
[x0, y0, x1, y1], while Hugging Face Transformers pairs split halves[x0, x1, y0, y1](rotate_half).[8][9] Both preserve norms, so a norm check never catches a mismatch; converting checkpoints requires permuting the Q/K projection rows ([0, 2, 1, 3]for width 4). bfloat16position rounding: Never cast integer position IDs tobfloat16before computing angles! Inbfloat16, positions4096and4097both round to4096.0, giving identical cosines and collapsing adjacent tokens onto the exact same coordinate! Always computepos * freqinfloat32, then castsin/costo the activation dtype.[9]- 2D/3D multimodal coordinates (MRoPE): Vision-language models like Qwen2.5-VL split rotary pairs across
(time, height, width)axes so vertical image neighbors keep a constant offset regardless of image width.[10][11]
import torch
def apply_rope(vec, pos, freqs, split_half=False):
out = vec.clone()
half = len(vec) // 2
for i, f in enumerate(freqs):
a, b = (i, i + half) if split_half else (2 * i, 2 * i + 1)
c, s = torch.cos(pos * f), torch.sin(pos * f)
out[a], out[b] = vec[a] * c - vec[b] * s, vec[a] * s + vec[b] * c
return out
# 1. Relative offset invariance & adjacent vs split-half conversion
q = torch.tensor([1., 2., 3., 4.], dtype=torch.float64)
k = torch.tensor([4., 3., 2., 1.], dtype=torch.float64)
freqs = torch.tensor([1.0, 0.01], dtype=torch.float64)
s1 = torch.dot(apply_rope(q, torch.tensor(5.), freqs), apply_rope(k, torch.tensor(2.), freqs))
s2 = torch.dot(apply_rope(q, torch.tensor(105.), freqs), apply_rope(k, torch.tensor(102.), freqs))
perm = [0, 2, 1, 3]
s_conv = torch.dot(apply_rope(q[perm], torch.tensor(5.), freqs, True), apply_rope(k[perm], torch.tensor(2.), freqs, True))
s_wrong = torch.dot(apply_rope(q, torch.tensor(5.), freqs, True), apply_rope(k, torch.tensor(2.), freqs, True))
print(f"offset (5,2)={s1:.6f}, shifted (105,102)={s2:.6f}, converted split-half={s_conv:.6f}, wrong layout={s_wrong:.6f}")
# 2. bfloat16 position rounding collapses 4096 and 4097!
pos = torch.tensor([4096, 4097], dtype=torch.int64)
print("bf16 cosines (collapsed!):", [round(x, 6) for x in pos.to(torch.bfloat16).float().cos().tolist()])
print("fp32 cosines (distinct): ", [round(x, 6) for x in pos.float().cos().tolist()])offset (5,2)=-0.760002, shifted (105,102)=-0.760002, converted split-half=-0.760002, wrong layout=-1.615580
bf16 cosines (collapsed!): [0.803991, 0.803991]
fp32 cosines (distinct): [0.803991, 0.934772]Note also that a single RoPE frequency pair does not decay monotonically with distance: dips to -0.990 at and climbs back up to -0.654 at . Men et al. showed that too small a RoPE base breaks long-range passkey retrieval even while aggregate perplexity still looks clean.[12]

ALiBi: make recency a score bias
ALiBi (Attention with Linear Biases) skips embeddings and rotations completely, subtracting a fixed head-specific distance penalty directly from scaled pre-softmax logits for visible keys (while the causal mask still sets to ):[7][13]
For heads (power of two), slopes follow the geometric ladder (for : 1/2, 1/4, ..., 1/256). Steep heads stay local (Head 1 subtracts -8.0 at distance 16); gentle heads reach far back (Head 8 subtracts only -0.0625 at distance 16). Crucially, ALiBi is a soft recency preference, not a hard mask: even at distance 16,384 where Head 8 subtracts -64, a far key with a +65 content-score advantage still beats the self-key (softmax([65 - 64, 0]) = 0.731).
![Four aligned views show ALiBi mechanics. At upper left, downward negative recency penalties across 8 heads at lag 16 span -8.0 in h1 to -0.06 in h8. At upper right, a 4x4 Head 1 causal bias matrix (m=1/2) shows past penalties 0 to -1.5 with a hatched -infinity mask for future keys j > i. At lower left, query i=2 logit arithmetic adds QK/sqrt(d) [2.0, 2.0, 2.0, 100] and Head 1 bias [-1.0, -0.5, 0.0, -infinity] to yield [1.0, 1.5, 2.0, -infinity]. At lower right, softmax weights equal [0.186, 0.307, 0.506, 0.000].](https://assets.leetllm.com/v1/ca06a4ead20d/fundamentals/positional-encoding-rope-alibi/illustrations/_generated/alibi_bias_dark.png)
Extending RoPE to long contexts
Extending a 4K-trained RoPE checkpoint to 16K or 128K () requires rescaling frequencies cleanly and validating both short-context quality and long-range retrieval:
- Position Interpolation (PI): Divides every frequency uniformly by (), mapping
[0, 16383]back into[0, 4095.75]at the cost of compressing fast local bands.[14] - NTK-aware scaling: Raises the RoPE base to so , keeping the fastest band intact while stretching the slowest band by .[15][16]
- YaRN (Yet another RoPE extensioN): Splits frequencies by how many full rotations they complete inside the training window: bands above turns stay untouched, bands below turn scale by , middle bands ramp linearly, and an empirical attention scale scales and (multiplying logits by , equivalent to temperature ).[15][17]
- Modern checkpoint recipes: Llama 3.1 starts at base
500,000with a piecewise wavelength ramp;[8][6] Gemma 3 mixes 5 local layers (base = 10,000) per global layer (base = 1,000,000);[18] and LongRoPE2 searches per-dimension ratios directly against needle retrieval loss.[19]

import math
import torch
import torch.nn.functional as F
# 1. YaRN band ratios (d=8, L_train=4096, s=4) & attention temperatureorig = [10000.0 ** (-2 * i / 8) for i in range(4)]
yarn = []
for f in orig:
turns = 4096 * f / (2 * math.pi)
keep = min(1.0, max(0.0, (turns - 1.0) / 31.0))
yarn.append(f * (keep + (1.0 - keep) / 4.0))
amp = 1.0 + 0.1 * math.log(4.0)
print("YaRN freq ratios:", [round(n / o, 3) for n, o in zip(yarn, orig)], f"| a={amp:.3f}, a^2={amp**2:.3f}")
# 2. Cached chunk RoPE consistency vs schedule mismatch
def rot(rows, pos, freqs):
p = rows.reshape(rows.shape[0], -1, 2)
ang = pos[:, None] * freqs[None, :]
c, s = ang.cos(), ang.sin()
return torch.stack((p[..., 0] * c - p[..., 1] * s, p[..., 0] * s + p[..., 1] * c), -1).flatten(1)
q = torch.tensor([[1., 0., 1., 0.], [0., 1., 1., 1.], [1., 1., 0., 1.]], dtype=torch.float64)
k = torch.tensor([[1., 1., 1., 0.], [1., 0., 0., 1.], [0., 1., 1., 1.]], dtype=torch.float64)
v = torch.eye(3, dtype=torch.float64)
pos = torch.arange(800, 803, dtype=torch.float64)
f_old, f_new = torch.tensor([1., 0.01], dtype=torch.float64), torch.tensor([1., 0.005], dtype=torch.float64)
sdpa = lambda qq, kk, vv, c=False, m=None: F.scaled_dot_product_attention(qq[None, None], kk[None, None], vv[None, None], is_causal=c, attn_mask=m)[0, 0]
rq, rk = rot(q, pos, f_old), rot(k, pos, f_old)
full = sdpa(rq, rk, v, c=True)
chunk_mask = pos[None, :] <= pos[1:, None]
chunk_ok = sdpa(rq[1:], rk, v, m=chunk_mask)
mixed_bad = sdpa(rot(q[-1:], pos[-1:], f_new), rk, v)
all_new = sdpa(rot(q, pos, f_new), rot(k, pos, f_new), v, c=True)
print("chunk matches full:", torch.allclose(chunk_ok, full[1:]), "| mixed schedule matches new pass:", torch.allclose(mixed_bad, all_new[-1:]))YaRN freq ratios: [1.0, 1.0, 0.384, 0.25] | a=1.139, a^2=1.296
chunk matches full: True | mixed schedule matches new pass: FalseLong-context budgets, Ring Attention, and depth retrieval
A longer positional formula only defines valid angles; serving long prompts reliably also requires fitting the shared window budget, managing quadratic prefill and KV memory, and verifying retrieval across every depth.
Shared context budgets, sliding windows, and hybrid KV accounting
Every prompt shares one hard limit with its reply:
When multi-turn history outgrows the input budget, reserve system instructions and output tokens first, then drop or compact complete user/assistant or tool-call/result turns from the oldest end while pinning exact file paths, constants, and identifiers outside any lossy summary.
Hardware costs then split across two phases. Full causal prefill compares token pairs per layer (): growing a prompt from 4K to 128K tokens multiplies pairwise attention scores by . Sliding-window attention (SWA) bounds each local layer to the last tokens, reducing cost to .[20] Because evicting the very first tokens of a stream can destabilize softmax mass, StreamingLLM preserves a few initial attention-sink KV slots alongside the rolling window.[21]
On hybrid checkpoints that mix short local layers with periodic global layers, never multiply one layer's shape uniformly across all layers; sum layer by layer instead:
At 128K tokens in BF16, a uniform 80-layer Llama 3 70B profile (8 GQA KV heads, ) consumes 40 GiB per sequence (160 GiB for four concurrent requests, exceeding the ~130 GiB weights). By contrast, a hybrid 48-layer profile with 40 local 1K layers (8 KV heads, ) and 8 global 128K layers (1 KV head, ) uses only 0.3125 + 2.0000 = 2.3125 GiB, whereas assuming the local shape everywhere overestimates memory by more than (48.0 GiB).
Ring Attention and decode context parallelism
When a single ultra-long prompt outgrows one GPU's HBM, Ring Attention shards sequence blocks across GPUs arranged in a ring: each rank pins its local query block, circulates KV blocks clockwise around the ring overlapped with local FlashAttention, and merges partial outputs via online softmax.[22] During decode, Decode Context Parallelism (DCP) distributes KV positions across ranks so each logical block covers tokens (e.g., 64 positions per logical block at DCP = 4, physical block size 16), letting a 1M-token sequence run without duplicating KV state per device. See Model Parallelism for LLM Inference for the full mass-aware merge mechanics.
Lost in the middle and per-slice NIAH/RULER verification
Recall accuracy drops sharply for facts buried near the middle of a 128K prompt. Liu et al. demonstrated this U-shaped accuracy curve ("Lost in the Middle"), where recall stays sharp near the start and end of a prompt while dipping sharply in the center, and distractor tokens progressively induce context rot.[23] Three habits guard retrieval quality:
- Edge-priority packing: Place the two highest-relevance excerpts at the head (after instructions) and tail (right before the question), pushing lower-priority background into the middle.
- Match strategy to query structure: Use full context for self-contained packets, RAG for targeted lookups over large corpora, and exact code/SQL filters for counting or aggregation questions (top- similarity retrieval clusters in high-scoring files and reverses true counts).
- Evaluate every
(length, depth)slice: Run Needle-in-a-Haystack (NIAH)[24] and RULER (multi-needle lookup, variable tracking, aggregation)[25] and gate on the worst slice, never a pooled average: a candidate scoring(100%, 70%, 100%)across(head, middle, tail)matches a(90%, 90%, 90%)baseline's90%mean while silently failing an85%middle-depth floor.
Choose by mechanism, then earn the window
Pick the insertion point that matches your architecture (additive embeddings, RoPE on Q/K, or ALiBi on logits), inspect the checkpoint's exact config (base, rotary width, pairing layout, local/global layer mix), and verify both short-context stability and long-range passkey/multi-needle retrieval at your target window before shipping.