Skip to content

Order matters: positional encodings

Attention by itself ignores the order of its tokens. See that permutation equivariance in code, then the ways Transformers put order back — learned, sinusoidal and relative positions — and why a table needs none.

Applied ~12 min6 steps

What runs in CodeSplash

You will be able to

  • Show that attention without positions is permutation equivariant
  • Compare learned, sinusoidal and relative (rotary) position schemes
  • Explain why the FT-Transformer needs no positional encoding

Read first

01

Shuffle in, shuffle out

Read

Attention compares every token with every other and averages. Nothing in softmax(QKᵀ/√d)V knows which token came first. Reorder the input tokens and the outputs come out reordered the same way, with identical values: permutation equivariancePermutation equivarianceReordering the inputs reorders the outputs the same way and changes nothing else. Attention without positions behaves this way..

For a set of items that's ideal. For a sentence it's fatal: "dog bites man" and "man bites dog" would look alike. Run the program to see the equivariance hold, then break once positions are added.

Python
import numpy as np

def softmax(z):
    e = np.exp(z - z.max(axis=-1, keepdims=True)); return e / e.sum(axis=-1, keepdims=True)

def attend(X):
    return softmax(X @ X.T / np.sqrt(X.shape[1])) @ X

rng = np.random.default_rng(0)
X = rng.normal(size=(5, 4)); perm = np.array([3, 0, 4, 1, 2])
print("equivariant without positions:", np.allclose(attend(X[perm]), attend(X)[perm]))

pos = np.arange(5)[:, None]; i = np.arange(4)[None, :]
P = np.where(i % 2 == 0, np.sin(pos / 10000 ** (i / 4)), np.cos(pos / 10000 ** ((i - 1) / 4)))
print("equivariant with positions:   ", np.allclose(attend(X[perm] + P), attend(X + P)[perm]))
R
softmax_rows <- function(z) { e <- exp(z - apply(z, 1, max)); e / rowSums(e) }
attend <- function(X) softmax_rows(X %*% t(X) / sqrt(ncol(X))) %*% X

set.seed(0)
X <- matrix(rnorm(20), 5, 4); perm <- c(4, 1, 5, 2, 3)
cat("equivariant without positions:", isTRUE(all.equal(attend(X[perm, ]), attend(X)[perm, ])), "\n")

pos <- 0:4; i <- 0:3
P <- outer(pos, i, function(p, k) ifelse(k %% 2 == 0, sin(p / 10000^(k / 4)), cos(p / 10000^((k - 1) / 4))))
cat("equivariant with positions:   ", isTRUE(all.equal(attend(X[perm, ] + P), attend(X + P)[perm, ])), "\n")
02

Three ways to add order

Read

A positional encodingPositional encodingInformation about each token's position added to or mixed into attention. Without it, attention ignores the order of tokens. puts position back in.

SchemeHowNote
Learned absolutea trained vector per position, added to the tokencan't go beyond the longest training length
Sinusoidalsines and cosines of position at many frequencies, addedfixed, no weights; relative offsets are linear maps
Relative (rotary, biases)rotate queries and keys by their positions, or add a distance bias to the scoresthe score depends on the offset between tokens

Rotary embeddings rotate q and k so their dot product depends only on how far apart they are. Most recent language models use them.

Shift both positions and see which schemes keep the scores the same.

DExplorable · Positional encodings: sinusoidal, RoPE, ALiBi

How does attention learn where a word is, and what does each scheme remember about distance?

Shift the query and every key by the same amount. Do the scores change with this scheme?

How sure?

Scheme

16
32

Base

Sets the slowest wavelength: larger bases tell far positions apart.

20
7

Score both positions s places later: does anything change?

3

Each head has its own slope.

query
  • score(20, n)
  • both shifted by 7

cos(p·θᵢ) for each rotation pair: fast pairs on the left

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

03

Do columns need positions?

Predict

Predict first

The FT-Transformer turns each column of a table into a token. Does it need a positional encoding to tell the columns apart?

Yes, or it can't tell age from glucoseNo: each column already has its own tokenizer weightsYes, sinusoidal ones
Reveal

No. Each column has its own tokenizer weights, so the token already says which column it is. Columns have no natural order, so permutation equivariance is what you want: reordering the columns shouldn't change the prediction.

04

What runs here

Read
EntryIn CodeSplash
Transformer (DNN019)Runs in CodeSplash: the FT-Transformer, with per-column tokens and no positional encoding

The pretrained vision transformer in the image models adds a learned position embedding to each patch. No learner lets you choose a positional encoding; the schemes are explained here.

05

Check: positions

Checkpoint

Check yourself

You reverse the order of the tokens fed to self-attention with no positional encoding. What happens to the outputs?

Show the answer

Answer: a

That's permutation equivariance: each token's output depends on the set of tokens, not their order.

Check yourself

A model with learned absolute position embeddings was trained on sequences of up to 512 tokens. What's the problem at 1,000 tokens?

Show the answer

Answer: a

Learned tables cover only the positions seen in training. Sinusoidal and relative schemes can be evaluated at any position, though quality beyond the training length still needs checking.

Check yourself

With rotary position embeddings, what does the attention score between two tokens depend on, besides their content?

Show the answer

Answer: a

Rotating q and k by angles proportional to position makes their dot product depend on the difference in positions.

Check yourself

Why is it fine that the FT-Transformer has no positional encoding?

Show the answer

Answer: a

The token identifies its column. Being indifferent to column order is a feature for tables.

06

Recap

Recap
  • Attention without positions is permutation equivariant: good for sets, wrong for sequences.
  • Learned, sinusoidal and relative (rotary) encodings put order back; they differ in how they extend beyond training lengths.
  • The FT-Transformer identifies columns through their own tokenizer weights and needs no positions.

Concepts in this lesson