7 routes42 sections324 units

Unit 7.4 · about 3 h

217 / 324

Positional 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

  1. Positional encoding
    Understanding 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

  2. Positional encoding implementation and theory
    D2L - attention and transformer implementation route

    Positional Encoding: the sine-cosine formula, the PositionalEncoding class with max_len 1000 and dropout after the add, the encoding_dim 32 with num_steps 60 run plotting columns 6:10, the binary-frequency intuition, and the relative-offset rotation derivation

  3. Order-free self-attention
    D2L - 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 TransformerEncoder scales 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

Closed-book, write \(p(i, 2j)\) and \(p(i, 2j+1)\), sketch the \(\operatorname{Sa}[XP]\) equals \(\operatorname{Sa}[X]P\) proof, and verify the \(2 \times 2\) rotation numerically for one \((i, \delta, j)\) triple.

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_len 1000. 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

  1. State permutation equivariance for self-attention and explain why it forces positional input.

  2. Write the D2L sinusoidal encoding entries.

  3. What does the \(2 \times 2\) rotation from position \(i\) to position \(i\) plus \(\delta\) depend on?

  4. A 1500-token input meets D2L default PositionalEncoding. What happens?

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

Comes after

Resources for this unit

  • Understanding Deep Learning - Transformers
    Simon J. D. Princeprimarytheory
    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
    D2L authorsrequiredimplementation
    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
    PyTorchreferencereference
    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
    Deep-MLoptionalpractice
    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
    TrenTorchsupportpractice
    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.

Quick find

Search Michi

Type to search every route, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels