第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 and a key , the additive attention scoring function (Bahdanau et al., 2014) is given by
英語のヒント
クエリとキーが異なる次元のベクトルのときは、行列を使ってによってその食い違いに対処するか、スコア関数として加法注意を使える。もう一つの利点は、その名前が示すとおり、注意が加法的なことである。これにより、計算をいくらか節約できることがある。クエリとキーが与えられたとき、加法注意のスコア関数(Bahdanau et al., 2014)は次で与えられる。
(11.3.7)
where , , and 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 as the activation function and disabling bias terms, we implement additive attention as follows:
英語のヒント
ここで、、、は学習できるパラメータである。この項はその後ソフトマックスに入れられ、非負性と正規化の両方が保証される。(11.3.7)と同値な解釈は、クエリとキーを連結し、隠れ層が一つのMLPに入れる、というものである。活性化関数としてを使い、バイアス項を無効にして、加法注意を次のように実装する。
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 , and , respectively. This is identical to our choice for DotProductAttention, except that now the queries are -dimensional. Likewise, we pick as the valid lengths for the sequences in the minibatch.英語のヒント
AdditiveAttentionがどう働くか見てみよう。簡単な例では、クエリ、キー、バリューの大きさをそれぞれ、、に選ぶ。これは、クエリが次元になった点を除けば、DotProductAttentionでの選び方と同じである。同じように、ミニバッチの系列の有効な長さとしてを選ぶ。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 are nonzero.英語のヒント
注意の関数を見直すと、
DotProductAttentionのものと質的にかなり似たふるまいが見られる。つまり、選んだ有効な長さの中の項だけが0でない。d2l.show_heatmaps(attention.attention_weights.reshape((1, 1, 2, 10)),
xlabel='Keys', ylabel='Queries')