0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Attention の行列計算を大雑把に見ていく

Posted at

Attention の行列計算

Attention 機構では Query, Key, Value として扱われる行列に対して以下の式で計算が行われる
$${\rm Attention}(Q,K,V)={\rm softmax}\left(\frac{QK^\top}{\sqrt{d}}\right)V$$

前提

Query, Key, Value は横向きのベクトルを集めて行列にしたものであり、内積は $xy^\top$, テンソル積は $x^\top y$ で表される

Query と Key の類似度を求める

クエリ(Query) と キー(Key) の類似度を求めよう
類似度は内積を取ることで求められる

$$Q K^\top = \begin{bmatrix}\boldsymbol{q}_1\\ \boldsymbol{q}_2\\ \boldsymbol{q}_3\\ \boldsymbol{q}_4\end{bmatrix}\begin{bmatrix}\boldsymbol{k}_1^\top\ \boldsymbol{k}_2^\top\ \boldsymbol{k}_3^\top\ \boldsymbol{k}_4^\top\end{bmatrix}$$

image.png

Value に重み付けをする

Value に重み付け(weight)をしよう
重み付けはテンソル積を取ることで求められる

$$W^\top Q=\begin{bmatrix}w_1^\top\ w_2^\top\ w_3^\top\ w_4^\top\end{bmatrix}\begin{bmatrix}v_1\\v_2\\v_3\\v_4\end{bmatrix}=w_1\otimes v_1+w_2\otimes v_2+w_3\otimes v_3+w_4\otimes v_4$$

image.png

Query, Key の類似度で Value に重み付けをする

全部まとめると Query, Key の類似度を用いて Value に重み付けできる

image.png

このときに重みを正規化したり $\left(\frac{1}{\sqrt{d}}\right)$ 確率的に表したり (softmax) する
$$\therefore {\rm Attention}(Q,K,V)={\rm softmax}\left(\frac{QK^\top}{\sqrt{d}}\right)V$$

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?