页面简介
正文摘录
The sentences “dog bites man” and “man bites dog” contain the same three words. Passed through the unmasked self-attention layer of Section 10.3, they produce the exact same output vectors in permuted order, because attention weights depend solely on token content. To distinguish word order, positional information must be injected into the representation or the scoring rule. Positional schemes fall into three main families: adding a position vector \(\mathbf{p}_i\) to each token embedding, rotating queries and keys by position-dependent angles (rotary position embeddings, RoPE), or subtracting a distance penalty from the attention scores (ALiBi). While all three distinguish positions within the training context length, they behave very differently when asked to extrapolate to longer sequences. We first formalize the permutation symmetry of self-attention, then construct and compare five positional schemes on a two-layer attention-only byte language model (TinyCharLM) trained at length \(128\) and evaluated up to length \(512\). 10.4.1 Permutation Equivariance Let \(\mathbf{X} \in \mathbb{R}^{n \times d}\) hold \(n\) token vectors and let \(f(\mathbf{X}) = \mathrm{softmax}(\mathbf{S})\,\mathbf{X}\mathbf{W}_v\) with \(\mathbf{S} = \mathbf{X}\mathbf{W}_q(\mathbf{X}\mathbf{W}_k)^\top/\sqrt{d_h}\) denote unmasked self-attention (Section 10.3) with dropout disabled. Reordering the \(n\) tokens corresponds to multiplying \(\mathbf{X}\) from the left by an \(n \times n\) permutation matrix \(\boldsymbol{\Pi}\). Proposition (Permutation Equivariance). For every permutation matrix \(\boldsymbol{\Pi}\), \(f(\boldsymbol{\Pi} \mathbf{X}) = \boldsymbol{\Pi} f(\mathbf{X})\). Proof. Because linear projections act row-wise, \((\boldsymbol{\Pi}\mathbf{X})\mathbf{W} = \boldsymbol{\Pi}(\mathbf{X}\mathbf{W})\) for \(\mathbf{W}_q, \mathbf{W}_k, \mathbf{W}_v\). The score matrix becomes \(\boldsymbol{\Pi} \mathbf{S} \boldsymbol{\Pi}^\top\). Because row-wise softmax commutes with row and column permutations, \(\mathrm{softmax}(\boldsymbol{\Pi} \mathbf{S} \boldsymbol{\Pi}^\top) = \boldsymbol{\Pi}\, \mathrm{softmax}(\mathbf{S})\, \boldsymbol{\Pi}^\top\). Multiplying by the permuted values \(\boldsymbol{\Pi}\mathbf{X}\mathbf{W}_v\) and using \(\boldsymbol{\Pi}^\top \boldsymbol{\Pi} = \mathbf{I}\) yields \(\boldsymbol{\Pi} f(\mathbf{X})\). Concatenating heads and applying \(\mathbf{W}_o\) row-wise preserves equivariance. \(\blacksquare\) We verify permutation equivariance numerically on a four-head MultiHeadAttention layer: PyTorchJAX attention = d2l.MultiHeadAttention(num_hiddens=64, num_heads=4) X = torch.randn(1, 8, 64) perm = torch.randperm(8) Y = attention(X, X, X) Y_perm = attention(X[:, perm], X[:, perm], X[:, perm]) print(f'max |Y[perm] - Y_perm|: {(Y[:, perm] - Y_perm).abs().max():.2e}') max |Y[perm] - Y_perm|: 1.08e-07 attention = d2l.MultiHeadAttention(num_hiddens=64, num_heads=4, rngs=nnx.Rngs(d2l.get_key())) key_X, key_perm = jax.random.split(d2l.get_key()) X = jax.random.normal(key_X, (1, 8, 64)) perm = jax.random.permutation(key_perm, 8) Y = attention(X, X, X) Y_perm = attention(X[:, perm], X[:, perm], X[:, perm]) print(f'max |Y[perm] - Y_perm|: {jnp.abs(Y[:, perm] - Y_perm).max():.2e}') max |Y[perm] - Y_perm|: 0.00e+00 Stacking equivariant layers or token-wise MLPs preserves equivariance. Note, however, that a causal mask breaks permutation symmetry because position \(i\) attends over \(i+1\) predecessors—an asymmetry exploited by NoPE below. 10.4.2 Absolute Position Embeddings The original Transformer (Vaswani et al. 2017) breaks permutation symmetry at the input by adding a position vector \(\mathbf{p}_i \in \mathbb{R}^d\) (row \(i\) of \(\mathbf{P}\)) to each token embedding \(\mathbf{x}_i\): shuffling tokens maps \(\mathbf{X} + \mathbf{P}\) to \(\boldsymbol{\Pi}\mathbf{X} + \mathbf{P} \neq \boldsymbol{\Pi}(\mathbf{X} + \mathbf{P})\). 10.4.2.1 Learned Positions Models such as BERT (Devlin et al. 2018) and GPT-2 (Radford et al. 2019) treat \(\mathbf{P} \in \mathbb{R}^{L_{\max} \times d}\) as a trainable embedding table with one parameter row per position up to a fixed maximum length \(L_{\max}\). Because rows beyond the training context length never receive gradients, a learned table cannot extrapolate to unseen positions. 10.4.2.2 Sinusoidal Encodings To define position vectors for arbitrary lengths without learned parameters, Vaswani et al. (2017) populate row \(i\) of \(\mathbf{P}\) with sines and cosines at \(d/2\) geometrically spaced frequencies \(\omega_m = 10000^{-2m/d}\): \[ p_{i, 2m} = \sin\left(\frac{i}{10000^{2m/d}}\right), \qquad p_{i, 2m+1} = \cos\left(\frac{i}{10000^{2m/d}}\right). \tag{10.4.1}\] As \(\omega_m\) decreases from \(1\) radian per token (\(m = 0\)) toward \(10^{-4}\) (\(m = d/2 - 1\)), the column pairs act as a continuous analog of a binary counter: low-index columns oscillate rapidly to separate neighboring positions, while high-index columns vary slowly across broad regions. PyTorchJAX def sinusoidal_encoding(max_len, num_hiddens): """The (max_len, num_hiddens) table of sinusoidal position codes.""" theta = torch.arange(max_len)[:, None] / 10000 ** ( torch.arange(0, num_hiddens, 2) / num_hiddens) return torch.stack([torch.sin(theta), torch.cos(theta)], -1).reshape(max_len, num_hiddens) P = sinusoidal_encoding(60, 32) d2l.plot(torch.arange(60), P[:, 6:10].T, xlabel='position', figsize=(6, 2.5), legend=[f'column {d}' for d in range(6, 10)]) def sinusoidal_encoding(max_len, num_hiddens): """The (max_len, num_hiddens) table of sinusoidal position codes.""" theta = jnp.arange(max_len)[:, None] / 10000 ** ( jnp.arange(0, num_hiddens, 2) / num_hiddens) return jnp.stack([jnp.sin(theta), jnp.cos(theta)], -1).reshape(max_len, num_hiddens) P = sinusoidal_encoding(60, 32) d2l.plot(jnp.arange(60), P[:, 6:10].T, xlabel='position', figsize=(6, 2.5), legend=[f'column {d}' for d in range(6, 10)]) Displaying the full \(60 \times 32\) encoding matrix P as a heatmap shows how rapidly oscillating high-frequency pairs on the left transition to slowly varying low-frequency pairs on the right, much like the binary digits of an integer counter: PyTorchJAX d2l.show_heatmaps(P[None, None], xlabel='column (encoding dimension)', ylabel='row (position)', figsize=(3.5, 4), cmap='Blues') d2l.show_heatmaps(P[None, None], xlabel='column (encoding dimension)', ylabel='row (position)', figsize=(3.5, 4), cmap='Blues') 10.4.2.3 Sinusoidal Encodings as Rotations By the trigonometric angle-addition identities, shifting position \(i\) by an offset \(\delta\) applies a \(2 \times 2\) rotation depending only on \(\delta\) to each frequency pair \((2m, 2m+1)\): \[ \begin{bmatrix} \cos(\delta \omega_m) & \sin(\delta \omega_m) \\ -\sin(\delta \omega_m) & \cos(\delta \omega_m) \end{bmatrix} \begin{bmatrix} p_{i, 2m} \\ p_{i, 2m+1} \end{bmatrix} = \begin{bmatrix} \sin\left((i+\delta) \omega_m\right) \\ \cos\left((i+\delta) \omega_m\right) \end{bmatrix} = \begin{bmatrix} p_{i+\delta, 2m} \\ p_{i+\delta, 2m+1} \end{bmatrix}. \tag{10.4.2}\] However, because \(\mathbf{p}_i\) is added to \(\mathbf{x}_i\), the bilinear attention score with \(\mathbf{A} = \mathbf{W}_q \mathbf{W}_k^\top / \sqrt{d_h}\) expands into four terms: \[ \begin{aligned} (\mathbf{x}_i + \mathbf{p}_i)^\top \mathbf{A}\, (\mathbf{x}_j + \mathbf{p}_j) &= \underbrace{\mathbf{x}_i^\top \mathbf{A}\, \mathbf{x}_j}_{\textrm{content--content}} + \underbrace{\mathbf{x}_i^\top \mathbf{A}\, \mathbf{p}_j}_{\textrm{content--position}} \\ &\quad + \underbrace{\mathbf{p}_i^\top \mathbf{A}\, \mathbf{x}_j}_{\textrm{position--content}} + \underbrace{\mathbf{p}_i^\top \mathbf{A}\, \mathbf{p}_j}_{\textrm{position--position}}. \end{aligned} \tag{10.4.3}\] The two cross terms couple content with absolute position (varying when \(i\) and \(j\) shift together), and even \(\mathbf{p}_i^\top \mathbf{A}\, \mathbf{p}_j\) depends purely on \(j - i\) only if \(\mathbf{A}\) is block-diagonal with \(2 \times 2\) scaled-rotation blocks (Exercise 2). 10.4.3 Rotary Position Embeddings Rotary position embeddings (RoPE) (Su et al. 2024) apply position transformations multiplicatively to queries and keys so that every score depends only on the relative offset \(j - i\): \[ (\mathbf{R}_i \mathbf{q})^\top (\mathbf{R}_j \mathbf{k}) = \mathbf{q}^\top \mathbf{R}_i^\top \mathbf{R}_j \mathbf{k} = \mathbf{q}^\top \mathbf{R}_{j-i} \mathbf{k} \quad \textrm{for all } i, j. \tag{10.4.4}\] Requiring \(\mathbf{R}_i^\top \mathbf{R}_j = \mathbf{R}_{j-i}\) with full-rank \(\mathbf{R}_0\) implies: (1) \(\mathbf{R}_0 = \mathbf{I}\) (from \(\mathbf{R}_0^\top \mathbf{R}_0 = \mathbf{R}_0\)); (2) \(\mathbf{R}_i^\top \mathbf{R}_i = \mathbf{I}\), so every \(\mathbf{R}_i\) is orthogonal and norm-preserving; and (3) \(\mathbf{R}_{i+j} = \mathbf{R}_i \mathbf{R}_j\), so \(\mathbf{R}_i = \mathbf{R}_1^i\). In an appropriate orthonormal basis (absorbable into \(\mathbf{W}_q, \mathbf{W}_k\)), any orthogonal matrix \(\mathbf{R}_1\) decomposes into \(2 \times 2\) planar rotations. RoPE partitions the \(d_h\) coordinates of each query and key into \(d_h/2\) pairs and rotates pair \(m\) at position \(i\) by \(i\omega_m\) with \(\omega_m = 10000^{-2m/d_h}\) (Figure 10.4.1): \[ \begin{aligned} \mathbf{R}_i &= \begin{bmatrix} R(i\omega_0) & & \\ & \ddots & \\ & & R(i\omega_{d_h/2-1}) \end{bmatrix}, \\ R(\alpha) &= \begin{bmatrix} \cos\alpha & -\sin\alpha \\ \sin\alpha & \cos\alpha \end{bmatrix}. \end{aligned} \tag{10.4.5}\] Values are not rotated, ensuring that the layer’s output remains invariant to global position shifts. RoPE is the standard positional encoding in modern open-weights language models. Figure 10.4.1: Rotary embeddings rotate each two-dimensional feature pair of the query and the key by an angle proportional to position. Shifting both positions by the same amount, here by 3, rotates both vectors together and leaves the angle between them (\(2\theta + \varphi\) in both panels), and hence the attention score, unchanged. Here \(\theta =