4.1.6 · D3Transformer Architecture

Worked examples — Positional encodings (sinusoidal)

2,780 words13 min readBack to topic

This page is the "hit every case" companion to Positional encodings (sinusoidal). The parent note built the formula and did three clean examples. Here we deliberately hunt down the awkward cases: position zero, huge positions, the highest frequency dimension vs. the lowest, the rotation-by-offset trick, and an exam twist. Every number below is machine-checked at the bottom.

Before anything, the facts we will reuse constantly. For a token at position and a dimension-pair index , define the base — the single constant that sets the whole frequency ladder — and the angular frequency

The index runs over — that is, there are exactly distinct frequencies, one per pair, and together the and channels fill all dimensions. (For our tiny this means : two frequencies, four channels.)

Read as "how fast the angle spins as position advances by one." The denominators are powers of the base ; a bigger means a bigger power, hence a smaller (slower spin). Then the even/odd pair is

Figure — Positional encodings (sinusoidal)

The scenario matrix

Every question this topic can pose falls into one of these cells. The examples afterward are tagged with the cell(s) they cover.

Cell Case class What makes it tricky Example(s)
A Position zero (degenerate) — a fixed pattern, not "no encoding" Ex 1
B Highest-frequency dim (, ) Angle in radians = position; wraps fast Ex 2
C Lowest-frequency dim (large ) Angle barely moves; near-linear Ex 3
D Two positions look identical? (aliasing) One dim can repeat; full vector cannot Ex 4
E Relative shift = rotation (the claim) Offset maps to a rotation angle; sign of Ex 5
F Large position / extrapolation () Values stay bounded; no explosion Ex 6
G Real-world word problem Choosing base/wavelength for a task Ex 7
H Exam twist (dot product of two encodings) Depends only on the offset (incl. negative) Ex 8

Throughout we use a tiny model, , so : and .


Forecast: guess the four numbers before reading on. Many people say "all zeros." Are they right?

  1. Even dims use sine of . Why this step? Every frequency times zero is zero, so both sine arguments are , and . , .
  2. Odd dims use cosine of . Why this step? , independent of frequency, because a zero angle points along the positive -axis on the circle. , .
  3. Assemble: . Why this step? The full encoding vector is built by laying the channels out in index order , so we interleave dim 0 (sine), dim 1 (cosine), dim 2 (sine), dim 3 (cosine) into one -length vector — that ordered concatenation is .

Verify: Not all zeros — the cosine channels are pinned to . So "position 0" is a very specific, non-null fingerprint. On the circle it is the point : the rightmost point, for every frequency simultaneously.


Forecast: the angle here equals the position measured in radians. Since one full loop is , guess which two consecutive positions sit almost on top of each other.

  1. Angle = position. Why this step? With , the argument is exactly radians. So position advances the circle-angle one radian per token.
  2. Evaluate:
  3. Find the wrap. Why this step? A full period is . Positions and would coincide; vs ( rad) are close but not equal ().

Look at Figure s02 below: the smooth blue curve is ; the orange dots are the integer positions with their values labelled. The red dashed line marks one full period at — notice how the dots have not returned to their starting height by , which is the point of this example.

Figure — Positional encodings (sinusoidal)

Verify: The fastest channel completes its circle in about positions — it is the "seconds hand." Distinct positions get distinct sine values within one period, but this single channel alone would repeat after tokens. That is exactly why we need slower channels (Ex 3).


Forecast: the wavelength is positions. Over just 100 tokens we traverse a small arc, so the curve should look nearly straight. Guess vs the naive "."

  1. Small-angle regime. Why this step? For , angle rad; for , angle rad. These are modest arcs on the circle, so the sine is close to (but below) the angle itself.
  2. Evaluate: .
  3. Compare to linear. Why this step? A linear counter would give ; the sine gives — close early, then bending. The slow channel encodes coarse global position without exploding.

Verify: Over this channel moved only (never leaving ), while the fast channel (Ex 2) looped times. Fast = fine local order, slow = coarse global position. Exactly the "zoom levels" the parent described.


Forecast: the fast channel () has period exactly , so it repeats between these two. Does that mean the whole vector repeats? Guess yes/no.

  1. Fast channel repeats. Why this step? and . So dims are identical at these two positions.
  2. Check the slow channel. Why this step? Its frequency is , so at its angle is rad, not . Then .
  3. Conclusion. Why this step? Because at least one channel differs, the full vectors differ. Aliasing on a single channel does not cause a full-vector collision — the multi-frequency design is what guarantees uniqueness over any realistic range.

Verify: dim 2 ; dim 2 . Distinct. The channels only all realign after the least common period, astronomically far away — far beyond any sequence length.


Forecast: the parent claimed where rotates by . So predict: take the sub-vector at , rotate by rad, and land exactly on the sub-vector at .

Axis-ordering reminder: as flagged in the warning callout, for matrix algebra we stack the sub-vector as sine on top.

  1. Compute the source sub-vector at , angle . Why this step? We need the "before" point in matrix ordering. (top), (bottom).
  2. Compute the target directly at , angle . Why this step? This is the "after" point we must reproduce: (top), (bottom).
  3. Why this exact matrix form? Why this step? We are not guessing the matrix — it is forced by the sine and cosine addition identities. Writing with : Read the top identity: the new sine is — so the top row of the matrix must be acting on . Read the bottom: the new cosine is — so the bottom row is . That is precisely why the sign sits on the lower-left:
  4. Negative offset . Why this step? Every case must be covered, including going backward. Then . Since and , the matrix becomes — the inverse rotation (opposite spin direction). It sends back to , confirming shifts are invertible rotations for any sign of .

Look at Figure s03 below: the blue arrow is the sub-vector at , the orange arrow at , and the red arc is the -rad rotation carrying blue onto orange. (For the arc would sweep the other way.)

Figure — Positional encodings (sinusoidal)

Verify: top row . ✓ The angle depends only on (and its sign), never on the absolute position . That is why relative distances — forward and backward — are learnable by a single fixed linear layer.


Forecast: a raw counter would give a value of here, swamping the embeddings. Sinusoids can't. Guess the range of each component.

  1. Fast channel. Why this step? , so angle rad. That is full loops. , .
  2. Slow channel. Why this step? , angle rad loops. , .
  3. Assemble: . Why this step? Same interleaving rule as Ex 1 — dims are laid out in index order (sine, cosine, sine, cosine), so we place the fast pair in slots and the slow pair in slots to form the single position-1000 vector.

Verify: every entry lies in despite . No explosion — this is exactly the extrapolation property: the formula is defined and bounded for positions far beyond any training length, unlike a lookup table capped at max length (Learned Positional Embeddings).


Forecast: guess whether the slowest channel finishes less than one loop over tokens.

  1. Derive the longest wavelength. Why this step? A channel of frequency has period (wavelength) , because repeats when advances by . The longest wavelength comes from the smallest frequency , which is the largest- channel. With , the smallest frequency uses the largest exponent , so This is where the expression comes from — it is just "period " with the base substituted.
  2. Base , : the exponent is , so , giving positions. Why this step? Compare to : , so the slowest channel completes far less than one loop across the whole document — no wrap, global order preserved. Base suffices.
  3. Base : , so positions. Why this step? , so the slowest channel wraps times — distant positions alias and global order is lost. Base fails for this task.

Verify: base gives ✓; base gives ✗. Recommendation: keep the standard base (or larger for ultra-long context) — it is precisely the parent's "too small a base fails on long sequences," now quantified. For context lengths well beyond k tokens you would raise the base further or switch to Rotary Position Embeddings (RoPE).


Forecast: gap is , so predict the dot product , regardless of the specific and .

Axis-ordering note: the dot product is order-independent, so it does not matter whether we stack or — we sum sine·sine plus cosine·cosine either way. We keep the sine-first ordering for consistency with Ex 5.

  1. Write both sub-vectors (sine top, cosine bottom). Why this step? We need the two circle points. At : . At : .
  2. Dot product. Why this step? Multiply matching channels and add:
  3. Compare to the identity. Why this step? The cosine difference identity says , and here , so this should equal .
  4. Negative gap (). Why this step? Swap to : then and the identity gives . Since cosine is even, — the same value. So the dot product is symmetric: forward and backward gaps of equal size score identically, exactly what you want for distance-based attention.

Verify: ✓. Because depends only on , attention scores built from these encodings naturally reflect relative distance — the seed idea behind Relative Positional Encodings and Self-Attention Mechanism's position sensitivity.


Recall Quick self-test

for is ::: — cosine channels pinned to 1, not all zeros. Why doesn't a single-channel repeat cause a full-vector collision? ::: Other channels use different frequencies, so at least one differs until an astronomically large common period. In matrix form, which entry of the 2D sub-vector goes on top? ::: The sine (); cosine goes below — that ordering makes the rotation matrix work. A position offset of acts on each 2D sub-vector as a ::: rotation by angle ; negative is the inverse (opposite-direction) rotation. Why does the dot product depend only on ? ::: It equals and cosine is even, so sign of the gap doesn't matter. Base vs for 8192-token docs? ::: Base 100 wraps (); base 10000 does not ().

Related: Token Embeddings (what PE is added to), Multi-Head Attention, Fourier Transform (the multi-frequency view), and the Hinglish note.