Attention & Transformers

Positional Encoding

How transformers represent order: sinusoidal encodings, learned embeddings, and relative-position methods like RoPE.

status: publishedimportance: importantdifficulty 2/5math: undergraduateread: 12mlive demo

Concept Structure

Positional Encoding

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

1prerequisites
2next concepts
2related links

Learning map

Positional Encoding
BeforeScaled Dot-Product Attention & Transformer LayersNow4/4 sections readyTryManipulate one control and predict the visible change.NextRotary Position Embeddings (RoPE)

Object flow

4/4 sections readyAsk about thisResearch room
ConceptPositional EncodingAttention & Transformers
1 source attachedLocal snapshot ready
concept:attention-transformers/positional-encoding

Conceptual Bridge

What should feel connected as you move through this page.

Carry inScaled Dot-Product Attention & Transformer Layers

Bring the mental model from Scaled Dot-Product Attention & Transformer Layers; this page will reuse it instead of restarting from zero.

Work herePositional Encoding

How transformers represent order: sinusoidal encodings, learned embeddings, and relative-position methods like RoPE.

Carry outRotary Position Embeddings (RoPE)

The next edge should feel earned: use the demo prediction here before following Rotary Position Embeddings (RoPE).

Test the linkManipulate one control and predict the visible change.Then continue to Rotary Position Embeddings (RoPE)
01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

Section prompt

Self-attention compares tokens by content (queries vs keys). But content alone does not tell you where a token is in the sequence.

If you shuffle the tokens in a sequence and keep their embeddings the same, plain unmasked self-attention has no built-in way to notice the shuffle. In other words, attention is permutation-equivariant unless we inject order information through positions or through an asymmetric mask such as a causal mask.

Positional encodings are the mechanism that turns "a bag of token vectors" into "an ordered sequence". There are many variants:

  • Absolute position (sinusoidal or learned): add a position vector to each token.
  • Relative position (RoPE, ALiBi, etc.): make attention scores depend on relative offsets.

RoPE is one modern relative-position method, but it is easier to appreciate once you understand the basic goal: the model needs a stable coordinate system for time/position.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

Section prompt

The classic sinusoidal encoding (Vaswani et al.) defines, for model dimension dd and position pp:

PE(p,2i)=sin(pωi),PE(p,2i+1)=cos(pωi),\mathrm{PE}(p,2i) = \sin\left(p\,\omega_i\right),\qquad \mathrm{PE}(p,2i+1) = \cos\left(p\,\omega_i\right),

with frequencies

ωi=base2i/d,i{0,,d21}.\omega_i = \mathrm{base}^{-2i/d},\qquad i\in\{0,\dots,\tfrac d2-1\}.

Two useful facts:

  1. Shift structure: the dot product between two pure position vectors depends only on their offset:
PE(p)PE(q)=icos(ωi(pq)).\mathrm{PE}(p)\cdot \mathrm{PE}(q) = \sum_i \cos\left(\omega_i\,(p-q)\right).
  1. Additive absolute encoding: the simplest way to use PE is to add it to token embeddings:
hp=ep+PE(p).h_p = e_p + \mathrm{PE}(p).

Relative-position methods (like RoPE) instead modify the attention computation so that qpkqq_p^\top k_q depends on (pq)(p-q) directly.

The caveat is important: once position vectors are added to token embeddings, the full attention score contains content-content, content-position, and position-position terms. The identity above explains the position-only signal, not every term in the final attention logit.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

Section prompt
import numpy as np

def sinusoidal_pe(T, d, base=10000.0):
    assert d % 2 == 0
    pos = np.arange(T)[:, None]
    i = np.arange(d // 2)[None, :]
    w = base ** (-2 * i / d)
    angles = pos * w
    pe = np.zeros((T, d))
    pe[:, 0::2] = np.sin(angles)
    pe[:, 1::2] = np.cos(angles)
    return pe

pe = sinusoidal_pe(T=32, d=16)
dot = lambda p, q: float(pe[p] @ pe[q])

for delta in [0, 1, 5, 10]:
    a = dot(0, delta)
    b = dot(7, 7 + delta)  # same relative offset
    print("delta =", delta, "dot =", round(a, 3), "dot (shifted) =", round(b, 3))
04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

Section prompt

Use the demo to predict the shift invariant before seeing the answer. Choose two positions pp and qq, shift both by the same amount, and ask what should happen to the pure sinusoidal position dot product.

The point is deliberately narrow: for a sine/cosine dimension pair, the position-only dot product follows the relative gap pqp-q. The reveal then bridges to RoPE, where the same phase-gap intuition appears inside query-key attention rather than as an added vector.

Live Concept Demo

Explore Positional Encoding

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 2/5undergraduatecode-aligned
Demo Prediction Checkpoint

Manipulate one control and predict the visible change.

Commit to what Positional Encoding should make visible before reading the result.

After The First Pass

Turn the concept into an inspected object.

Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.

Mechanism Storyboard

See the idea move before the page explains it

How transformers represent order: sinusoidal encodings, learned embeddings, and relative-position methods like RoPE.

Prediction open01 / Intuition
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Positional Encoding should make visible.

Visual Inquiry

Make the image answer a mathematical question

How transformers represent order: sinusoidal encodings, learned embeddings, and relative-position methods like RoPE.

4/4 stages readyLive demo connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Positional Encoding easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

paper · 2017Attention Is All You NeedVaswani et al.

Defines the sinusoidal positional encoding used in the original Transformer and motivates it through relative-offset structure.

Open source

Claim Review

How transformers represent order: sinusoidal encodings, learned embeddings, and relative-position methods like RoPE.

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources1 reference

vaswani-2017-attention

Witnesses4 local objects

Use equation, code, and demo objects to check whether the source support is operational.

Substantively reviewedSinusoidal positional encodings inject order by assigning each position a deterministic sine/cosine vector; because each dimension pair uses the same frequency at every position, the position-only dot product PE(p) dot PE(q) depends on the relative offset p - q through sums of cosines.Claim metadata: source checked

Vaswani et al. define the sine/cosine PE formula, add PEs to token embeddings, and motivate sinusoidal PEs through fixed-offset linear structure. The dot-product identity is local math from that formula.

Sources: Attention Is All You NeedFull attention logits after adding token embeddings include content-position cross terms, not only p-q. Causal/asymmetric masks can also inject order-dependent structure.A bounded review summary is present; still check caveats and exact source scope.

Checked Vaswani et al. section 3.5: it defines sine/cosine formulas at alternating dimensions, says each dimension is a sinusoid, gives geometrically spaced wavelengths, and motivates fixed-offset structure because PE(pos+k) can be represented linearly from PE(pos). The dot-product offset identity follows by sin a sin b + cos a cos b = cos(a-b) on each pair. Caveat preserves that full logits include token, cross, and mask terms.

Reviewer: codex; reviewed 2026-06-26

Practice Loop

Try the idea before it explains itself

How transformers represent order: sinusoidal encodings, learned embeddings, and relative-position methods like RoPE.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in Positional Encoding.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Object research drawerClose
ConceptPositional EncodingAttention & Transformers
Code witness comparisonPositional Encoding code witness 1assert d % 2 == 0Prediction before revealPositional Encoding interactive demoManipulate one control and predict the visible change.
Grounded room questionWhat is the smallest example that makes Positional Encoding click without losing the math?Local snapshot ready

Research Room

Attach the question to an exact object

Pick the concept, equation, source, code witness, claim, misconception, or demo state before asking for help. The handoff stays grounded to that object.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptAttention & Transformers

Positional Encoding

Anchored question

What is the smallest example that makes Positional Encoding click without losing the math?

Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays locally in this browser for concept:attention-transformers/positional-encoding.

No local draft saved.
Evidence to inspect
  • Source ids to inspect: vaswani-2017-attention
  • Definition, prerequisite, and contrast concept links
  • The equation or code witness that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Grounded AI handoff

I am working in Continuous Function's research reading room. Object: concept - Positional Encoding Object key: concept:attention-transformers/positional-encoding Context: Attention & Transformers Anchor id: concept/concept-notebook/attention-transformers/positional-encoding Open question: What is the smallest example that makes Positional Encoding click without losing the math? Evidence to inspect: - Source ids to inspect: vaswani-2017-attention - Definition, prerequisite, and contrast concept links - The equation or code witness that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.

Open source object
concept/concept-notebook/attention-transformers/positional-encoding concept:attention-transformers/positional-encoding