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$은 헤드 하나의 차원이고, 각각의 $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}$는 렐루를 성분별로 적용한 것이다. 또한 $\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) 블럭 하나의 파라미터 수는 $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. ↩︎