Skip to content
Skip to lesson
Back to Topics
LearnTransformer & Multimodal ArchitecturesPositional Encoding: RoPE & ALiBi
HardTransformer Architecture15 min read

Positional Encoding: RoPE & ALiBi

Unmasked attention follows tokens when they move. Sinusoids, RoPE, and ALiBi put order back in different places, and a longer formula still needs a retrieval test.

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 cannot tell those two sentences apart: shuffle the input rows by any permutation PP, and the output rows simply shuffle by the exact same PP.

Transformers put order back at three completely different points in the block: additive at the input, rotating projected queries and keys, or adding a linear distance penalty directly to attention . 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 Attention(X)=softmax(QKT/dk)V\text{Attention}(X) = \text{softmax}(Q K^T / \sqrt{d_k}) V and left-multiply the input rows by a permutation matrix PP (X′=PXX' = P X).[1] Because linear projections act on columns, Q′=PQQ' = P Q, K′=PKK' = P K, and V′=PVV' = P V. Substituting (PK)T=KTPT(P K)^T = K^T P^T and using orthogonality PTP=IP^T P = I:

A′=softmax ⁣(PQKTdkPT)=PAPT,Y′=A′V′=(PAPT)(PV)=P(AV)=PYA' = \text{softmax}\!\left(P \frac{Q K^T}{\sqrt{d_k}} P^T\right) = P A P^T, \qquad Y' = A' V' = (P A P^T)(P V) = P(A V) = P Y

That property, Attention(PX)=P Attention(X)\text{Attention}(P X) = P\,\text{Attention}(X), is permutation equivariance. A fixed breaks that symmetry by letting token ii count visible predecessors j≤ij \le i (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].
Without a position signal or fixed mask, shuffling input rows `[model, loaded, ckpt]` simply shuffles the attention weights and output rows by the exact same permutation.
A unified Transformer attention block schematic traces input x through linear projections W_Q, W_K, W_V, scaled dot product QK^T / sqrt(d_k), softmax, and multiplication by V to output Y, pinpointing three color-coded positional injection sites: (1) blue additive sinusoidal or learned embeddings added at input x + p before projections (entering Q, K, and V), (2) green RoPE rotating projected Q and K via R(m) and R(n) while leaving V untouched, and (3) warm ALiBi adding -m_h|i-j| bias directly to pre-softmax logits.
Three positional injection sites inside one attention block: additive embeddings at input x+px + p (entering Q,K,VQ, K, V), RoPE rotating projected Q,KQ, K (leaving VV untouched), or ALiBi biasing pre-softmax logits.

Absolute position: give every slot a multi-speed fingerprint

The original Transformer adds geometric sine/cosine pairs to each token embedding:[1]

PE(pos,2i)=sin⁡ ⁣(pos100002i/dmodel),PE(pos,2i+1)=cos⁡ ⁣(pos100002i/dmodel)PE_{(\text{pos}, 2i)} = \sin\!\left(\frac{\text{pos}}{10000^{2i/d_{\text{model}}}}\right), \qquad PE_{(\text{pos}, 2i+1)} = \cos\!\left(\frac{\text{pos}}{10000^{2i/d_{\text{model}}}}\right)

Every pair acts like a dial turning at a different wavelength λ2i=2π⋅100002i/dmodel\lambda_{2i} = 2\pi \cdot 10000^{2i/d_{\text{model}}}: at dmodel=512d_{\text{model}} = 512, 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 kk is a linear 2×22\times 2 rotation depending only on kk:

[sin⁡((p+k)ω)cos⁡((p+k)ω)]=[cos⁡(kω)sin⁡(kω)−sin⁡(kω)cos⁡(kω)][sin⁡(pω)cos⁡(pω)]\begin{bmatrix} \sin((p+k)\omega) \\ \cos((p+k)\omega) \end{bmatrix} = \begin{bmatrix} \cos(k\omega) & \sin(k\omega) \\ -\sin(k\omega) & \cos(k\omega) \end{bmatrix} \begin{bmatrix} \sin(p\omega) \\ \cos(p\omega) \end{bmatrix}

Why add instead of concatenate? Concatenation doubles hidden width from dd to 2d2d, quadrupling the size of every WQ,WK,WVW_Q, W_K, W_V matrix (4×4\times entries). Adding keeps width dd, at the cost of mixing content and position into four cross terms when computing (xm+pm)WQWKT(xn+pn)T(x_m + p_m) W_Q W_K^T (x_n + p_n)^T. And although the sinusoidal formula is defined past training length, Press et al. showed sinusoidal models still suffer sharp perplexity spikes past LtrainL_{\text{train}}.[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.
Multi-speed sinusoidal dials for dmodel=512d_{\text{model}} = 512: pair (0,1) oscillates rapidly while pair (510,511) barely moves across 32 tokens.

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 (q2i,q2i+1)(q_{2i}, q_{2i+1}) with frequency θi=b−2i/drotary\theta_i = b^{-2i/d_{\text{rotary}}}, RoPE rotates the pair by angle mθim\theta_i:

(q2i(m)q2i+1(m))=(cos⁡(mθi)−sin⁡(mθi)sin⁡(mθi)cos⁡(mθi))(q2iq2i+1)\begin{pmatrix} q_{2i}^{(m)} \\ q_{2i+1}^{(m)} \end{pmatrix} = \begin{pmatrix} \cos(m\theta_i) & -\sin(m\theta_i) \\ \sin(m\theta_i) & \cos(m\theta_i) \end{pmatrix} \begin{pmatrix} q_{2i} \\ q_{2i+1} \end{pmatrix}

Equivalently, viewing each pair as a complex number z=x+iyz = x + i y, rotation is simply multiplication by eimθie^{i m \theta_i}. Now take the dot product between a query at position mm and a key at position nn. Because Rθ,mTRθ,n=Rθ,n−mR_{\theta, m}^T R_{\theta, n} = R_{\theta, n - m}, both absolute positions cancel completely, leaving only the relative offset n−mn - m:

(RΘ,mq)T(RΘ,nk)=qTRΘ,n−mk(R_{\Theta, m} q)^T (R_{\Theta, n} k) = q^T R_{\Theta, n - m} k

Shift both tokens forward by +100 (from (2, 1) to (102, 101)), and their dot product stays identical (0.878). RoPE preserves vector norms ∥RΘ,mq∥2=∥q∥2\|R_{\Theta, m} q\|_2 = \|q\|_2, adds zero parameters, and leaves values VV unrotated so position governs routing without scrambling the content payload.

Shifting both mm and nn by +100 rotates q′q' and k′k' around the circle while keeping their angular gap (−0.5-0.5 rad) and dot product (0.8780.878) identical.
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.
An 8-dim RoPE head at offset −2-2: the fast pair turns negative (−0.416-0.416) while slower pairs remain near +1+1, summing to 2.5642.564 (scaled logit 0.9060.906).

Three RoPE implementation traps you will meet in real code

  1. 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).
  2. bfloat16 position rounding: Never cast integer position IDs to bfloat16 before computing angles! In bfloat16, positions 4096 and 4097 both round to 4096.0, giving identical cosines and collapsing adjacent tokens onto the exact same coordinate! Always compute pos * freq in float32, then cast sin/cos to the activation dtype.[9]
  3. 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]
rope-mechanics-and-traps.py
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()])
Output
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: cos⁡(0.5Δ)\cos(0.5\Delta) dips to -0.990 at Δ=6\Delta = 6 and climbs back up to -0.654 at Δ=8\Delta = 8. Men et al. showed that too small a RoPE base breaks long-range passkey retrieval even while aggregate perplexity still looks clean.[12]

A coordinate plot compares a single RoPE pair score S(Delta) = cos(0.5 Delta) against the ALiBi linear penalty B(Delta) = -0.1 Delta over relative offsets Delta from 0 to 12. Highlighted between Delta = 6 and Delta = 8, the RoPE pair rebounds upward from -0.990 to -0.654 as its cosine phase turns, while ALiBi drops monotonically from -0.600 to -0.800 and reaches -1.200 at Delta = 12.
A single RoPE pair oscillates (cos⁡(0.5Δ)\cos(0.5\Delta) rebounds from −0.990-0.990 to −0.654-0.654), whereas ALiBi's linear penalty drops monotonically with distance.

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 j≤ij \le i (while the causal mask still sets j>ij > i to −∞-\infty):[7][13]

Attention(Q,K,V)=softmax ⁣(QKTdk+B(h))V,Bij(h)=−mh(i−j) for j≤i\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^T}{\sqrt{d_k}} + B^{(h)}\right) V, \qquad B^{(h)}_{ij} = -m_h (i - j) \text{ for } j \le i

For HH heads (power of two), slopes follow the geometric ladder mh=2−8h/Hm_h = 2^{-8h/H} (for H=8H = 8: 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].
ALiBi spans steep local heads (−8.0-8.0 at lag 16) to gentle long-range heads (−0.06-0.06), biasing past weights toward recency while causal masking zeroes future keys.

Extending RoPE to long contexts

Extending a 4K-trained RoPE checkpoint to 16K or 128K (s=Ltarget/Ltrains = L_{\text{target}} / L_{\text{train}}) requires rescaling frequencies cleanly and validating both short-context quality and long-range retrieval:

Top: frequency multiplier theta-prime over theta across 64 rotary pairs for 4K-to-16K (s=4) context extension. PI scales uniformly to 0.25x, NTK-aware (base 40,890) decays smoothly from 1.00x to 0.25x, and YaRN preserves fast pairs at 1.00x before ramping to 0.25x on slow pairs. Bottom-left: YaRN multipliers for d=8 pairs are 1.000, 1.000, 0.384, and 0.250. Bottom-right: YaRN attention scaling factors for s=4 are Base 1.000, Q/K amplitude a=1.139, logit scale a^2=1.296, and temperature t=0.771.
Comparing 4K→16K (s=4s=4) RoPE extensions: uniform PI (0.25x everywhere), NTK-aware smooth geometric decay, and YaRN band preservation plus attention amplitude scaling (a=1.139a = 1.139).
yarn-and-cache-consistency.py
orig = [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:]))
Output
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: False

Long-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:

serialized_input_tokens+reserved_output_tokens≤context_limit\text{serialized\_input\_tokens} + \text{reserved\_output\_tokens} \le \text{context\_limit}

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 n(n+1)/2n(n+1)/2 token pairs per layer (O(n2)O(n^2)): growing a prompt 32×32\times from 4K to 128K tokens multiplies pairwise attention scores by 322=1,024×32^2 = 1{,}024\times. Sliding-window attention (SWA) bounds each local layer to the last ww tokens, reducing cost to O(nw)O(n w).[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:

logical KV bytes=∑ℓnℓ(HK,ℓdK,ℓbK,ℓ+HV,ℓdV,ℓbV,ℓ)\text{logical KV bytes} = \sum_\ell n_\ell \big(H_{K,\ell} d_{K,\ell} b_{K,\ell} + H_{V,\ell} d_{V,\ell} b_{V,\ell}\big)

At 128K tokens in BF16, a uniform 80-layer Llama 3 70B profile (8 GQA KV heads, dh=128d_h = 128) 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, dh=256d_h = 256) and 8 global 128K layers (1 KV head, dh=512d_h = 512) uses only 0.3125 + 2.0000 = 2.3125 GiB, whereas assuming the local shape everywhere overestimates memory by more than 20×20\times (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 DCP×block_size\text{DCP} \times \text{block\_size} 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:

  1. 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.
  2. 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-kk similarity retrieval clusters in high-scoring files and reverses true counts).
  3. 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's 90% mean while silently failing an 85% 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.

Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 10 answered
1.An unmasked, position-free attention block with dropout disabled gives output rows A=[2,1], B=[4,3], C=[6,5] and D=[8,7]. Its input order changes from A/B/C/D to C/A/D/B, with each token vector unchanged. Which output row order should the recomputed block produce?
2.A sine-first absolute position pair uses 0.25 radians per slot at position 3. A separate design concatenates content and position vectors, each of width 96, and widens its square attention projections from 96 to the combined width. What values does the position pair store, and by what factor does the number of entries in each projection matrix grow?
3.One RoPE pair has fixed unrotated q=[2,0], k=[1,0] and frequency 0.25. Compare positions (m=7,n=4) with (m=37,n=34). The standard attention setup leaves V unrotated. Which score pair follows?
4.A six-coordinate head stores adjacent rotary pairs in its first four coordinates: [1,2,3,4,5,6]. The last two coordinates are outside the rotary region. Which coordinate order converts it to a matching split-half convention without changing the represented pairs?
5.One RoPE pair encodes height and another encodes width. On each axis, the unrotated query and key both equal [1, 0], and the rotation is 0.25 radians per position. The query patch is at (3, 2) and the key patch is at (1, 1), in (height, width) order. What is the dot product of the rotated vectors before and after both patches shift by (7, 9)?
6.An ALiBi query at 12 compares a visible key at 5. Its already-scaled content logit is 5.0. Two head slopes are 1/4 and 1/32. Which pair of logits enters softmax?
7.Apply the stated NTK-aware base transform to rotary width 6 and extension scale 9. For pair indices 0,1,2, which frequency ratios new/original follow?
8.An attention head uses softmax at temperature 1. For each permitted key, the logit equals the rotated query–key dot product divided by the square root of the head width. The head now multiplies both rotated vectors by 1.2. By what factor does it scale the logits, and what temperature on the original logits gives the same weights for every input?
9.A cached chunk has query logical positions 51 and 54. Its cached keys are physically stored in the order [54,49,52], and their rotary coordinates are correct. If true means allowed, which permission rows preserve causal visibility in that physical storage order?
10.A deployment specification requires at most 8192 total prompt-plus-generation tokens, short-task accuracy at least 0.85, long-task accuracy at least 0.80, and cache computation matching the evaluated frequency schedule. Candidate A uses 6200 prompt+1800 generation tokens, scores 0.88/0.83 and recomputes the entire prefix under the evaluated schedule. Candidate B uses 6000+1500 tokens and scores 0.90/0.86, but changes only new-query frequencies while retaining old-schedule cached keys. Which decision follows?

10 questions remaining.

References

Attention Is All You Need.

Vaswani, A., et al. · 2017

https://arxiv.org/abs/1706.03762

Transformer Language Models without Positional Encodings Still Learn Positional Information.

Haviv, A., Ram, O., Press, O., Izsak, P., & Levy, O. · 2022 · Findings of EMNLP 2022

https://arxiv.org/abs/2203.16634

BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding.

Devlin, J., et al. · 2019 · NAACL 2019

https://arxiv.org/abs/1810.04805

GPT-2 Source Implementation.

OpenAI · 2019

https://github.com/openai/gpt-2/blob/master/src/model.py

RoFormer: Enhanced Transformer with Rotary Position Embedding.

Su, J., et al. · 2021

https://arxiv.org/abs/2104.09864

The Llama 3 Herd of Models.

Dubey, A., et al. · 2024 · arXiv preprint

https://arxiv.org/abs/2407.21783

Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation.

Press, O., Smith, N. A., & Lewis, M. · 2022 · ICLR 2022

https://arxiv.org/abs/2108.12409

Llama 3.1 reference rotary embedding and frequency scaling

Meta · 2026

https://github.com/meta-llama/llama-models/blob/f45cdfd624b98b6655540f7101d8d9cb432e631c/models/llama3_1/reference_impl/model.py

Llama rotary embedding implementation

Hugging Face · 2026

https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py

Qwen2.5-VL Technical Report

Qwen Team, Alibaba Group · 2025

https://arxiv.org/abs/2502.13923

Utilities for Rotary Embedding

Hugging Face · 2026

https://huggingface.co/docs/transformers/main/internal/rope_utils

Base of RoPE Bounds Context Length.

Men, X., et al. · 2024 · NeurIPS 2024

https://arxiv.org/abs/2405.14591

ALiBi reference transformer implementation

Ofir Press et al. · 2026

https://github.com/ofirpress/attention_with_linear_biases/blob/master/fairseq/models/transformer.py

Extending Context Window of Large Language Models via Positional Interpolation.

Chen, S., et al. · 2023

https://arxiv.org/abs/2306.15595

YaRN: Efficient Context Window Extension of Large Language Models.

Peng, B., et al. · 2023

https://arxiv.org/abs/2309.00071

Code Llama: Open Foundation Models for Code

Rozière, M., et al. · 2023

https://arxiv.org/abs/2308.12950

Transformers 5.17.0 YaRN rotary parameter implementation

Hugging Face Contributors · 2026

https://github.com/huggingface/transformers/blob/v5.17.0/src/transformers/modeling_rope_utils.py

Gemma 3 Technical Report

Gemma Team et al. · 2025

https://arxiv.org/abs/2503.19786

LongRoPE2: Near-Lossless LLM Context Window Scaling

Shang, N., Zhang, L. L., Wang, S., et al. · 2025

https://arxiv.org/abs/2502.20082

Mistral 7B.

Jiang, A. Q., et al. · 2023

https://arxiv.org/abs/2310.06825

Efficient Streaming Language Models with Attention Sinks

Xiao, G., Tian, Y., Chen, B., Han, S., Lewis, M. · 2023 · ICLR 2024

https://arxiv.org/abs/2309.17453

Ring Attention with Blockwise Transformers for Near-Infinite Context.

Liu, H., et al. · 2023 · arXiv preprint

https://arxiv.org/abs/2310.01889

Lost in the Middle: How Language Models Use Long Contexts

Liu, N.F., et al. · 2024 · TACL 2024

https://aclanthology.org/2024.tacl-1.9/

Needle In A Haystack: Pressure Testing LLMs

Kamradt, G. · 2023

https://github.com/gkamradt/needle-in-a-haystack

RULER: What's the Real Context Size of Your Long-Context Language Models?

Hsieh, C.-P., et al. · 2024

https://arxiv.org/abs/2404.06654

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.