Skip to content
mlmentorship

Positional encoding: where does position enter attention?

Compare embeddings, rotary geometry, and score biases; compute ALiBi probabilities and test slope, visibility, and common-shift changes.

Published · 7 min read ·Core ·Intermediate
Reading depth

Summary

Position can change embeddings, query/key geometry, or scores before softmax. Those are different computations, not interchangeable ways to relabel a checkpoint. Unmasked position-free self-attention is permutation-equivariant: permuting input rows permutes output rows. A fixed causal mask already restricts positions asymmetrically.

Task: query position may read keys . Hold scaled content scores at zero and use causal ALiBi slope . Compute the attention probabilities, then change the slope and permitted directions.

The lineup

The pipeline is embeddings, Q/K projections, dot product, bias/mask, then softmax. Locate each method at its actual stage.

Sinusoidal (original Transformer, 2017)

Add fixed absolute-position vectors before the projections:

PE(pos, 2i)   = sin(pos / 10000^(2i/d))
PE(pos, 2i+1) = cos(pos / 10000^(2i/d))

Defined values at unseen positions do not guarantee useful extrapolation.

Learned absolute positional embeddings

Add a learned table row for each supported position, as in BERT or GPT-2. Unseen indices need an explicit adaptation, not an undefined table lookup.

Relative positional encoding

T5-style relative bucket biases enter scores; bucket definitions are part of the model. Shaw and Transformer-XL use other relative constructions, not the same lookup formula.

RoPE (Rotary Position Embeddings)

Rotate query/key coordinate pairs before their dot product, rather than adding an embedding vector.

For positions m and n, use their specified block-diagonal rotations:

Q' = R_m * Q   (Q rotated by query position)
K' = R_n * K   (K rotated by key position)

The rotation derivation proves the common-shift relationship for fixed content vectors. The figure retains positions and ; their relative offsets agree.

ALiBi (Attention with Linear Biases)

Add a distance bias after the scaled content score:

score_h(i, j) = Q_i K_j^T / sqrt(d) - s_h * (i - j)

Here is head width, is a fixed head-specific slope, and allowed causal keys satisfy . Forbidden scores still require a separate mask.

Learning objective

RoPE rotates vectors; ALiBi subtracts distance from attention scores

Rotating features and shifting scores are different operationsRoPE rotates query/key coordinates before their dot product. ALiBi instead subtracts a head-specific distance penalty from the attention score.Position enters different stages ofthe calculationRoPE: rotate coordinates before thedot productqrotatekrotateALiBi: subtract distance cost fromthe scored=00d=1-0.5d=2-1
Derivation
RoPE changes query and key angles while ALiBi subtracts distance from attention scores The upper panel uses identical unit content vectors and one rotary frequency. At positions one and three, query and key are rotated to angles theta and three theta, leaving a two-theta gap. Shifting both to positions four and six rotates both vectors together and preserves the same two-theta gap and dot product cosine of two theta. The lower panel keeps content vectors unchanged. For a causal query at position six, keys at positions two, four, and six have distances four, two, and zero, so ALiBi adds score biases negative four s sub h, negative two s sub h, and zero before softmax. RoPE · rotate Q and K before the dot product positions (m, n) = (1, 3) R₁qR₃k2θ shift both: (m, n) = (4, 6) R₄qR₆k2θ same offset → same angle gap → same positional effect (Rₘq)ᵀ(Rₙk) = qᵀRₙ₋ₘk for q = k = unit vector: score = cos((n − m)θ) = cos(2θ) ALiBi · keep Q and K unchanged; bias their score causal query i = 6query 6 key j = 2distance 4 → bias −4sₕ key j = 4distance 2 → −2sₕ key j = 6distance 0 → 0 content score − sₕ(i − j) → softmax each head h has its own fixed positive slope sₕ
shifting both upper positions by three preserves their angle gap for fixed content vectors. ALiBi instead subtracts distance penalties from content scores before softmax. At slope 0.25, the lower symbolic biases become −1, −0.5, and 0. These are different operations, despite their common relative-offset dependence. Sources: RoFormer and ALiBi.
Check: What is unchanged when both positions shift together in the RoPE example? What operation instead adds ALiBi's distance effect?
Read it this way: RoPE rotates query/key coordinates before their dot product. ALiBi instead subtracts a head-specific distance penalty from the attention score.
Does an ALiBi penalty rotate the stored query and key vectors?

Compute and change the row

SlopeDistancesScore biasesSoftmax probabilities

For the first row, exponentials are , summing to . The newest key is times as likely as the oldest because their content scores match. Shifting query to and keys to preserves distances and probabilities for unchanged content.

New task: strengthen recency preference. Double the slope and recompute softmax, as the second row shows. Use when: deliberately adapting head distance preferences; changing deployed slopes changes the model.

New task: allow an encoder query at to read key . Use a bidirectional mask and the specified absolute-distance bias. Check: slope gives , not from misusing signed causal distance. Use when: available source positions lie on both sides.

Position-free / implicit position

A causal mask or recurrence can impose order without adding a positional vector. Mixture-of-experts routing alone does not supply sequence position.

What an interviewer expects you to say

Separate position representation, visibility, and context capacity. Failure: a fixed slope is not a causal mask; unmasked future keys can receive an unintended positive signed-distance bias.

Reconstruct: can RoPE replace ALiBi unchanged because both use relative positions?

Answer

No. Rotation changes content dot products; ALiBi adds score biases. The same trained weights need not preserve scores, probabilities, or useful behavior after substitution.

Common confusions

Relative scores do not guarantee long-context generalization. Context capacity also depends on memory, compute, implementation limits, and training. An unbounded position formula is not an empirical quality result.

Long-context extension techniques

  • Position interpolation rescales positions toward the trained range, with its specified continued training.
  • NTK-aware variants change the frequency schedule; inspect the actual formula rather than assuming one universal implementation.
  • YaRN changes interpolation and attention scaling under its chosen recipe.
  • Continued long-context training changes the learning exposure and compute budget, not merely a position index limit.

Evaluate short-context retention, retrieval, reasoning, location sensitivity, latency, and memory separately. One successful retrieval needle does not qualify every long-document task.

Why interviewers ask

The useful test is whether you can locate the operation, reproduce the score change, and specify evidence for adaptation.


Related: Transformer architecture, FlashAttention, KV cache.