正弦波位置エンコーディング
定義
定数$C > 0$とデータ列$\mathbf{X} = \begin{bmatrix} \mathbf{x}_{1} & \cdots & \mathbf{x}_{n} \end{bmatrix}$ $(\mathbf{x}_{\text{pos}} \in \mathbb{R}^{d}$、$d$は偶数$)$に対して、以下のように定義される関数$\operatorname{pe} : \mathbb{N} \to \mathbb{R}^{d}$あるいは写像$\mathbf{x}_{\text{pos}} \mapsto \mathbf{x}_{\text{pos}} + \operatorname{pe}(\text{pos})$を正弦波位置エンコーディングsinusoidal positional encodingという。成分のインデックスは$1$から数え、$i$は$1 \le i \le d/2$の範囲を動く。
$$ \begin{align*} \left[ \operatorname{pe}(\text{pos}) \right]_{2i-1} &:= \sin \left( \text{pos} / C^{2(i-1)/d} \right) \\ \left[ \operatorname{pe}(\text{pos}) \right]_{2i} &:= \cos \left( \text{pos} / C^{2(i-1)/d} \right) \end{align*} $$
説明
トランスフォーマーの位置エンコーディングとして使われて有名になった。トランスフォーマーを提案した論文『🔒(26/08/27)Attention Is All You Need』1では$C = 10000$、$d = d_{\text{model}} = 512$とおいた。$\operatorname{pe}(\text{pos})$をベクトルとして書き下すと次のようになる。
$$ \operatorname{pe}(\text{pos}) = \begin{bmatrix} \sin \left( \text{pos} \right) \\ \cos \left( \text{pos} \right) \\ \sin \left( \text{pos} / C^{2/d} \right) \\ \cos \left( \text{pos} / C^{2/d} \right) \\ \vdots \\ \sin \left( \text{pos} / C^{(d-2)/d} \right) \\ \cos \left( \text{pos} / C^{(d-2)/d} \right) \end{bmatrix} $$
奇数番目の成分は正弦、偶数番目の成分は余弦であり、成分の対$(2i-1, 2i)$ごとに波長が$2\pi C^{2(i-1)/d}$である正弦波が一つずつ対応する。波長は$2\pi$から$2\pi C^{(d-2)/d} \approx 2\pi C$まで等比数列をなすので、前方の成分ほど速く振動し、後方の成分ほどゆっくり振動する。下の図は$C = 10000$、$d = 512$のときの奇数番目の成分$\left[ \operatorname{pe}(\text{pos}) \right]_{2i-1} = \sin \left( \text{pos} / 10000^{2(i-1)/512} \right)$を、$i = 1, 10, 50, 100$についてそれぞれ位置$\text{pos}$の関数として描いたものである。$i$が大きくなるほど波長が長くなることがわかる。

次は$C = 10000$、$d = 128$のときの$\operatorname{pe}(1), \dots, \operatorname{pe}(100)$を列として並べ、ヒートマップで表したものである。インデックスが小さい下側は位置が変わるたびに速く振動し、上側はゆっくりと変化する。

トランスフォーマーでは、それぞれの単語が文の中でどこに位置するかについての情報を含ませるために使用した。$\mathbf{x}_{\text{pos}}$が単語の意味を込めたベクトルであるとすれば、$\operatorname{pe}(\text{pos})$はその単語が何番目に登場するかという情報を持つ摂動やノイズなどとして理解でき、同じ単語であっても登場する位置によって互いに異なるベクトルとして区別できるようにしてくれる。
正弦波位置エンコーディングの役割は上のようなものだけではない。例えば自然数$k$に対して次の写像をニューラルネットワークの一番前に置けば、自然に周期関数を実装できる。すべての成分が周期$2\pi$を持つ関数であるため、この写像の後にどんなニューラルネットワーク$f : \mathbb{R}^{2k} \to \mathbb{R}$を合成しても、全体は自ずと周期が$2\pi$の関数になる。3次元のシーンをニューラルネットワークで表現するNeRFがこれを使用した代表的な事例である2。
$$ x \mapsto \begin{bmatrix} \sin x \\ \cos x \\ \sin 2x \\ \cos 2x \\ \vdots \\ \sin kx \\ \cos kx \end{bmatrix} $$
