Unit 7.4 · about 3 h
217 / 324Positional information and position offsets
Self-attention sees sets, not sequences. Positional information is the only place order enters, so every offset bug becomes a meaning bug.
- derive
- implement
You can now
- Prove permutation equivariance of unpositioned self-attention and explain why order needs extra input.
- Implement sinusoidal absolute encodings and predict any entry from the closed form.
- Derive the relative-offset rotation and use it to explain shift generalization.
Covers
- Positional information and position offsets
Study, in this order
3 steps
- Positional encodingUnderstanding Deep Learning - Transformers
Section 12.3.1 (pp. 213 to 214): permutation equivariance, absolute encoding matrix, and relative per-offset parameters, with Figure 12.5
- Positional encoding implementation and theoryD2L - attention and transformer implementation route
Positional Encoding: the sine-cosine formula, the
PositionalEncodingclass withmax_len1000 and dropout after the add, theencoding_dim32 withnum_steps60 run plotting columns6:10, the binary-frequency intuition, and the relative-offset rotation derivation - Order-free self-attentionD2L - attention and transformer implementation route
The paragraphs before Positional Encoding on parallel computation discarding sequential order
Focus on
- Without positions the block is permutation-equivariant: \(\operatorname{Sa}[XP]\) equals \(\operatorname{Sa}[X]P\). UDL Problem 12.3 asks for this proof; it is the reason order must be injected as input.
- Absolute encodings add a unique column per position. The D2L
TransformerEncoderscales embeddings by \(\sqrt{\text{width}}\) before the add because the encodings stay in \([-1, 1]\). - Sinusoid pairs rotate with offset: position \(i\) plus \(\delta\) is a fixed \(2 \times 2\) rotation of position \(i\), depending on \(\delta\) and frequency only. Shifting text shifts encodings linearly.
- Relative schemes index by the offset between key and query positions, not by absolute index. They survive absolute shifts that absolute tables must relearn.
Reproduce closed-book
Traps
- Not stating where positions enter. UDL lists three placements: once at the input, at every layer, or only in the query and key computation. The last leaves values free of position, which changes what later layers can read; write down which one your block uses.
- Exceeding D2L
max_len1000. The stored table is fixed width, so longer inputs fail on the add; rebuild the table instead of truncating silently. - Comparing encodings or outputs in train mode. D2L applies dropout to the sum of embeddings and encodings, so train-mode runs drop entries at random; compare in eval mode or with dropout
0, as the D2L plot does.
Practice
TrenTorch: Sinusoidal positional encoding
Implement sinusoidal_positional_encoding(seq_len, d_model) with sin on even columns and cos on odd columns
Row 0 must read [0, 1, 0, 1, ...]. After the tests pass, assert the \(2 \times 2\) rotation identity numerically for one \((i, \delta, j)\) triple in your own repository.
UDL Problem 12.3: permutation equivariance
Problems (p. 239): show \(\operatorname{Sa}[XP]\) equals \(\operatorname{Sa}[X]P\) for equation 12.8
Pen-and-paper proof through the value, query and key maps and the column-wise softmax.
Self-test
-
State permutation equivariance for self-attention and explain why it forces positional input.
\(\operatorname{Sa}[XP]\) equals \(\operatorname{Sa}[X]P\) for any permutation matrix \(P\): reordering inputs reorders outputs identically. The block therefore carries no order information, so positions must enter as extra input. -
Write the D2L sinusoidal encoding entries.
\(p(i, 2j)\) equals \(\sin(i / 10000^{2j/d})\) and \(p(i, 2j+1)\) equals \(\cos(i / 10000^{2j/d})\), with \(i\) the position and \(d\) the width. -
What does the \(2 \times 2\) rotation from position \(i\) to position \(i\) plus \(\delta\) depend on?
Only the offset \(\delta\) and the pair frequency \(\omega_j\). It never depends on the absolute position \(i\), which is why a fixed shift is a fixed linear map. -
A 1500-token input meets D2L default
PositionalEncoding. What happens?The stored table is 1000 wide, so the slice caps at 1000 and the add fails on shape mismatch. Rebuild the encoding with a largermax_len.
Completion criterion
Stop when
Your encoding table matches the closed form entry by entry, the rotation check passes, and you can say which tensors carry position into the first attention call.
Mark passed, then open 7.5 Only mark this when you can do it without notes.Leads to
- 7.5 Transformer blocks: residual stream, normalization and feed-forward Add positions before the first residual block.
- 7.2 Causal masks, padding masks and fully masked rows Recheck valid indices after any position shift.
Comes after
- 5.5 Patch embeddings and positional informationCompare learned patch positions with sequence position schemes.
Resources for this unit
- Understanding Deep Learning - Transformers Use Chapter 12.1-12.11 and the matching notebooks for dot-product self-attention, extension to transformers, transformer layers and vision transformers.
- D2L - attention and transformer implementation route Use queries-keys-values, attention-scoring-functions, multihead-attention, self-attention-and-positional-encoding, transformer and vision-transformer. Implement masked single-head attention, multi-head attention and one pre-normalized block before comparing with PyTorch.
Also in this section
- PyTorch - scaled dot product attention Use the official function documentation as a differential oracle for shapes, masks, dropout and backend behavior after the manual version passes intervention tests.
- Deep-ML candidate - attention problems Use 490 Scaled Dot-Product Attention as the fifth platform admission sample. If the judge catches a seeded masking error, use at most one of 490, 491, 53, 904 or 905 as a changed-prompt drill.
- TrenTorch - attention and block questions Solve the multi-head split, sinusoidal positional encoding, causal mask and pre-norm versus post-norm questions the units name, then carry the same checks into your own block.