Explain transformer positional encoding using sine and cosine functions. Show that for any fixed offset, the encoding can be represented as a linear function via rotation matrix property.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Positional encoding uses sine/cosine pairs at different frequencies so that shifting position by Δ corresponds to applying a block diagonal rotation matrix to the encoding vector, making PE(p+Δ) a linear transformation of PE(p).
One of the design goals in the original Transformer was to give the model some notion of the order of the tokens without having to learn an explicit positional embedding table. Vaswani et al. achieve this by adding to each token embedding a fixed, deterministic vector
[
\mathrm{PE}(p) \in \mathbb{R}^{d_{\text{model}}}
]
whose components are sinusoidal functions of the position index (p) at a range of frequencies:
Here each pair ((\mathrm{PE}{2i}, \mathrm{PE}{2i+1})) encodes the position on a unit circle at an angular frequency (\omega_i = 1/10000^{2i/d_{\text{model}}}). Different (i) use different wavelengths spanning several orders of magnitude.
A useful property of this choice is that shifting the position by a fixed offset (\Delta) acts as a rotation in each of these two‑dimensional subspaces. Using the sum identities for sine and cosine,
[
\sin!\left(\frac{p+\Delta}{\lambda}\right) = \sin!\left(\frac{p}{\lambda}\right)\cos!\left(\frac{\Delta}{\lambda}\right) + \cos!\left(\frac{p}{\lambda}\right)\sin!\left(\frac{\Delta}{\lambda}\right),
]
[
\cos!\left(\frac{p+\Delta}{\lambda}\right) = \cos!\left(\frac{p}{\lambda}\right)\cos!\left(\frac{\Delta}{\lambda}\right) - \sin!\left(\frac{p}{\lambda}\right)\sin!\left(\frac{\Delta}{\lambda}\right),
]
one finds for each frequency (\lambda_i = 10000^{2i/d_{\text{model}}}) that
[
\begin{pmatrix}
\mathrm{PE}{2i}(p+\Delta)\[0.3em]
\mathrm{PE}{2i+1}(p+\Delta)
\end{pmatrix}
The (2\times 2) matrix on the right is a planar rotation matrix. Stacking these blocks along the diagonal gives a block–diagonal matrix (R(\Delta)\in\mathbb{R}^{d_{\text{model}}\times d_{\text{model}}}) such that for all positions (p)
[
\mathrm{PE}(p+\Delta) = R(\Delta),\mathrm{PE}(p).
]
This shows that for any fixed offset (\Delta) the positional encoding at (p+\Delta) can be obtained by applying a fixed linear transformation to the encoding at (p). This linear “shift–as–rotation” property is one of the reasons sinusoidal encodings are convenient: relative positions can be recovered from dot products and the model can, in principle, learn to extrapolate to unseen sequence lengths.