プリンキピア

第11章注意機構とTransformer

11.5. Multi-Head Attention11.5 マルチヘッド注意

In practice, given the same set of queries, keys, and values we may want our model to combine knowledge from different behaviors of the same attention mechanism, such as capturing dependencies of various ranges (e.g., shorter-range vs. longer-range) within a sequence. Thus, it may be beneficial to allow our attention mechanism to jointly use different representation subspaces of queries, keys, and values.
英語のヒント
実際には、同じクエリ、キー、バリューの集合が与えられたとき、系列の中のさまざまな範囲(たとえば短距離と長距離)の依存関係をとらえるといった、同じ注意機構の異なるふるまいからの知識をモデルに組み合わせてほしいことがある。そのため、注意機構がクエリ、キー、バリューの異なる表現部分空間を一緒に使えるようにすると役に立つかもしれない。
To this end, instead of performing a single attention pooling, queries, keys, and values can be transformed with h independently learned linear projections. Then these h projected queries, keys, and values are fed into attention pooling in parallel. In the end, h attention-pooling outputs are concatenated and transformed with another learned linear projection to produce the final output. This design is called multi-head attention, where each of the h attention pooling outputs is a head (Vaswani et al., 2017). Using fully connected layers to perform learnable linear transformations, Fig. 11.5.1 describes multi-head attention.
英語のヒント
そのために、一つの注意プーリングを行う代わりに、クエリ、キー、バリューを、h個の独立に学習した線形射影で変換できる。そして、これらh個の射影したクエリ、キー、バリューを、並列に注意プーリングに入れる。最後に、h個の注意プーリングの出力を連結し、別の学習した線形射影で変換して、最終的な出力を生み出す。この設計はマルチヘッド注意と呼ばれ、h個の注意プーリングの出力のそれぞれがヘッドである(Vaswani et al., 2017)。学習できる線形変換を行うのに全結合層を使って、図11.5.1はマルチヘッド注意を描いている。
Fig. 11.5.1図11.5.1
Multi-head attention, where multiple heads are concatenated then linearly transformed.
英語のヒント
マルチヘッド注意。複数のヘッドが連結され、その後線形変換される。
import math
import torch
from torch import nn
from d2l import torch as d2l