logo

トランスフォーマー 📂機械学習

トランスフォーマー

定義1 2

埋め込み次元が$d$で長さが$n$の数列を表す行列 $\mathbf{X} \in \mathbb{R}^{d \times n}$に対して、関数$\operatorname{Attention} : \mathbb{R}^{d \times n} \to \mathbb{R}^{d \times n}$を次のように定義し、アテンションattentionと呼ぶことにしよう。

$$ \operatorname{Attention}(\mathbf{X}) = \mathbf{X} + \sum_{h=1}^{H} \mathbf{W}_{h}^{O} \left( \mathbf{W}_{h}^{V}\mathbf{X} \right) \operatorname{Softmax} \left[ (\mathbf{W}_{h}^{K}\mathbf{X})^{\mathsf{T}} (\mathbf{W}_{h}^{Q}\mathbf{X}) \right] $$

このとき$H$はヘッドの個数、$m$はヘッド1つの次元であり、それぞれの$h = 1, \dots, H$に対して$\mathbf{W}_{h}^{Q}, \mathbf{W}_{h}^{K}, \mathbf{W}_{h}^{V} \in \mathbb{R}^{m \times d}$、$\mathbf{W}_{h}^{O} \in \mathbb{R}^{d \times m}$である。そして$\operatorname{Softmax}$とは、与えられた行列$\mathbf{X} = \begin{bmatrix} \mathbf{x}_{1} & \cdots & \mathbf{x}_{n}\end{bmatrix}$に対して各列ベクトルソフトマックス $\operatorname{softmax}$を取ることで、各列の和が$1$になるようにする関数のことをいう。

$$ \operatorname{Softmax}(\mathbf{X}) := \begin{bmatrix} \underset{\vert}{\overset{\vert}{\operatorname{softmax}(\mathbf{x}_{1})}} & \cdots & \underset{\vert}{\overset{\vert}{\operatorname{softmax}(\mathbf{x}_{n})}} \end{bmatrix} $$

順伝播型ニューラルネットワーク $\operatorname{FF} : \mathbb{R}^{d \times n} \to \mathbb{R}^{d \times n}$を次のように定義しよう。

$$ \begin{align*} \operatorname{FF}(\mathbf{X}) &= \mathbf{X} + \mathbf{W}_{2} \operatorname{ReLU} \left( \mathbf{W}_{1} \mathbf{X} + \mathbf{b}_{1} \mathbf{1}^{\mathsf{T}} \right) + \mathbf{b}_{2} \mathbf{1}^{\mathsf{T}} \end{align*} $$

$$ \mathbf{W}_{1} \in \mathbb{R}^{r \times d}, \quad \mathbf{W}_{2} \in \mathbb{R}^{d \times r} $$

$$ \mathbf{b}_{1} \in \mathbb{R}^{r}, \quad \mathbf{b}_{2} \in \mathbb{R}^{d} $$

ここで$r$は$\operatorname{FF}$の隠れ層の次元であり、$\operatorname{ReLU}$はReLUを成分ごとに適用したものである。また$\mathbf{1} \in \mathbb{R}^{n}$はすべての成分が$1$のベクトルで、$\mathbf{b}_{k} \mathbf{1}^{\mathsf{T}}$はバイアス$\mathbf{b}_{k}$を$\mathbf{X}$のすべての列に同じように加えるブロードキャストを意味する。

トランスフォーマーブロックを以下のように定義しよう。

$$ \operatorname{Block} = \operatorname{FF} \circ \operatorname{Attention} $$

トランスフォーマー

トランスフォーマーブロック$N$個を合成したものをトランスフォーマーtransformerという。

$$ \operatorname{Transformer} := \overbrace{\operatorname{Block}_{N} \circ \operatorname{Block}_{N-1} \circ \cdots \circ \operatorname{Block}_{1}}^{N} $$

説明

定義における$\operatorname{Attention}$は残差層が含まれたマルチヘッドセルフアテンションである。数学的にドットプロダクトアテンションはマルチヘッドアテンションで$H=1$である特殊な場合に過ぎないので、数学論文においてアテンションは主に上のように定義される。詳しくはマルチヘッドアテンションの文書を参照せよ。

実際に🔒(26/08/27)トランスフォーマー論文で紹介された構造では位置エンコーディング、🔒(26/08/31)マスクドアテンション、🔒(26/08/29)層正規化などの要素が含まれるが、数学論文では上のように簡単に定義するのが普通である。

性質

(a) 任意の置換行列 $P$に対して次が成り立つ。

$$ \operatorname{Transformer}(\mathbf{X}P) = \operatorname{Transformer}(\mathbf{X})P $$

(b) ブロック1つのパラメータ数は$4Hmd + 2rd + r + d$であり、入力数列の長さ$n$に依存しない。


  1. Chulhee Yun et al. Are transformers universal approximators of sequence-to-sequence functions?. arXiv preprint arXiv:1912.10077 (2019). ↩︎

  2. Silas Alberti et al. Sumformer: Universal approximation for efficient transformers. Topological, Algebraic and Geometric Learning Workshops 2023. PMLR, 2023. ↩︎