プリンキピア

第11章注意機構とTransformer

11.3.4. Additive Attention11.3.4 加法注意

When queries 𝐪 and keys 𝐤 are vectors of different dimension, we can either use a matrix to address the mismatch via 𝐪⊤𝐌𝐤, or we can use additive attention as the scoring function. Another benefit is that, as its name indicates, the attention is additive. This can lead to some minor computational savings. Given a query 𝐪∈ℝq and a key 𝐤∈ℝk, the additive attention scoring function (Bahdanau et al., 2014) is given by
英語のヒント
クエリ𝐪とキー𝐤が異なる次元のベクトルのときは、行列を使って𝐪⊤𝐌𝐤によってその食い違いに対処するか、スコア関数として加法注意を使える。もう一つの利点は、その名前が示すとおり、注意が加法的なことである。これにより、計算をいくらか節約できることがある。クエリ𝐪∈ℝqとキー𝐤∈ℝkが与えられたとき、加法注意のスコア関数(Bahdanau et al., 2014)は次で与えられる。
a(𝐪,𝐤)=𝐰v⊤tanh(𝐖q𝐪+𝐖k𝐤)∈ℝ,(11.3.7)
where 𝐖q∈ℝh×q, 𝐖k∈ℝh×k, and 𝐰v∈ℝh are the learnable parameters. This term is then fed into a softmax to ensure both nonnegativity and normalization. An equivalent interpretation of (11.3.7) is that the query and key are concatenated and fed into an MLP with a single hidden layer. Using tanh as the activation function and disabling bias terms, we implement additive attention as follows:
英語のヒント
ここで、𝐖q∈ℝh×q、𝐖k∈ℝh×k、𝐰v∈ℝhは学習できるパラメータである。この項はその後ソフトマックスに入れられ、非負性と正規化の両方が保証される。(11.3.7)と同値な解釈は、クエリとキーを連結し、隠れ層が一つのMLPに入れる、というものである。活性化関数としてtanhを使い、バイアス項を無効にして、加法注意を次のように実装する。
class AdditiveAttention(nn.Module):  #@save
    """Additive attention."""
    def __init__(self, num_hiddens, dropout, **kwargs):
        super(AdditiveAttention, self).__init__(**kwargs)
        self.W_k = nn.LazyLinear(num_hiddens, bias=False)
        self.W_q = nn.LazyLinear(num_hiddens, bias=False)
        self.w_v = nn.LazyLinear(1, bias=False)
        self.dropout = nn.Dropout(dropout)

    def forward(self, queries, keys, values, valid_lens):
        queries, keys = self.W_q(queries), self.W_k(keys)
        # After dimension expansion, shape of queries: (batch_size, no. of
        # queries, 1, num_hiddens) and shape of keys: (batch_size, 1, no. of
        # key-value pairs, num_hiddens). Sum them up with broadcasting
        features = queries.unsqueeze(2) + keys.unsqueeze(1)
        features = torch.tanh(features)
        # There is only one output of self.w_v, so we remove the last
        # one-dimensional entry from the shape. Shape of scores: (batch_size,
        # no. of queries, no. of key-value pairs)
        scores = self.w_v(features).squeeze(-1)
        self.attention_weights = masked_softmax(scores, valid_lens)
        # Shape of values: (batch_size, no. of key-value pairs, value
        # dimension)
        return torch.bmm(self.dropout(self.attention_weights), values)
Let’s see how AdditiveAttention works. In our toy example we pick queries, keys and values of size (2,1,20), (2,10,2) and (2,10,4), respectively. This is identical to our choice for DotProductAttention, except that now the queries are 20-dimensional. Likewise, we pick (2,6) as the valid lengths for the sequences in the minibatch.
英語のヒント
AdditiveAttentionがどう働くか見てみよう。簡単な例では、クエリ、キー、バリューの大きさをそれぞれ(2,1,20)、(2,10,2)、(2,10,4)に選ぶ。これは、クエリが20次元になった点を除けば、DotProductAttentionでの選び方と同じである。同じように、ミニバッチの系列の有効な長さとして(2,6)を選ぶ。
queries = torch.normal(0, 1, (2, 1, 20))

attention = AdditiveAttention(num_hiddens=8, dropout=0.1)
attention.eval()
d2l.check_shape(attention(queries, keys, values, valid_lens), (2, 1, 4))
When reviewing the attention function we see a behavior that is qualitatively quite similar to that of DotProductAttention. That is, only terms within the chosen valid length (2,6) are nonzero.
英語のヒント
注意の関数を見直すと、DotProductAttentionのものと質的にかなり似たふるまいが見られる。つまり、選んだ有効な長さ(2,6)の中の項だけが0でない。
d2l.show_heatmaps(attention.attention_weights.reshape((1, 1, 2, 10)),
                  xlabel='Keys', ylabel='Queries')