第11章注意機構とTransformer
11.3.3. Scaled Dot Product Attention11.3.3 スケール化内積注意
Let’s return to the dot product attention introduced in (11.3.2). In general, it requires that both the query and the key have the same vector length, say , even though this can be addressed easily by replacing with where is a matrix suitably chosen for translating between both spaces. For now assume that the dimensions match.
英語のヒント
(11.3.2)で紹介した内積注意に戻ろう。一般に、これはクエリとキーが同じベクトルの長さ、たとえばをもつことを必要とする。ただし、を二つの空間のあいだを変換するよう適切に選んだ行列として、をに置き換えれば、これは簡単に対処できる。今は次元が一致するとしよう。
In practice, we often think of minibatches for efficiency, such as computing attention for queries and key-value pairs, where queries and keys are of length and values are of length . The scaled dot product attention of queries , keys , and values thus can be written as
英語のヒント
実際には、効率のためにミニバッチで考えることが多い。たとえば、個のクエリと個のキーとバリューの組について注意を計算する場合で、クエリとキーの長さは、バリューの長さはである。そうすると、クエリ、キー、バリューのスケール化内積注意は次のように書ける。
(11.3.6)
Note that when applying this to a minibatch, we need the batch matrix multiplication introduced in (11.3.5). In the following implementation of the scaled dot product attention, we use dropout for model regularization.
英語のヒント
これをミニバッチに当てはめるときには、(11.3.5)で紹介したバッチ行列積が必要になることに注意してほしい。以下のスケール化内積注意の実装では、モデルの正則化のためにドロップアウトを使う。
class DotProductAttention(nn.Module): #@save
"""Scaled dot product attention."""
def __init__(self, dropout):
super().__init__()
self.dropout = nn.Dropout(dropout)
# Shape of queries: (batch_size, no. of queries, d)
# Shape of keys: (batch_size, no. of key-value pairs, d)
# Shape of values: (batch_size, no. of key-value pairs, value dimension)
# Shape of valid_lens: (batch_size,) or (batch_size, no. of queries)
def forward(self, queries, keys, values, valid_lens=None):
d = queries.shape[-1]
# Swap the last two dimensions of keys with keys.transpose(1, 2)
scores = torch.bmm(queries, keys.transpose(1, 2)) / math.sqrt(d)
self.attention_weights = masked_softmax(scores, valid_lens)
return torch.bmm(self.dropout(self.attention_weights), values)To illustrate how the
DotProductAttention class works, we use the same keys, values, and valid lengths from the earlier toy example for additive attention. For the purpose of our example we assume that we have a minibatch size of , a total of keys and values, and that the dimensionality of the values is . Lastly, we assume that the valid length per observation is and respectively. Given that, we expect the output to be a tensor, i.e., one row per example of the minibatch.英語のヒント
DotProductAttentionクラスがどう働くかを示すため、前の加法注意の簡単な例と同じキー、バリュー、有効な長さを使う。この例のために、ミニバッチの大きさが、キーとバリューが合計個、バリューの次元がだとする。最後に、観測ごとの有効な長さはそれぞれとだとする。そうすると、出力はのテンソル、つまりミニバッチの事例ごとに一行になると予想される。queries = torch.normal(0, 1, (2, 1, 2))
keys = torch.normal(0, 1, (2, 10, 2))
values = torch.normal(0, 1, (2, 10, 4))
valid_lens = torch.tensor([2, 6])
attention = DotProductAttention(dropout=0.5)
attention.eval()
d2l.check_shape(attention(queries, keys, values, valid_lens), (2, 1, 4))Let’s check whether the attention weights actually vanish for anything beyond the second and sixth column respectively (because of setting the valid length to and ).
英語のヒント
(有効な長さをとに設定したので)注意の重みが、それぞれ2列目と6列目より先で本当に消えるかどうか確かめよう。
d2l.show_heatmaps(attention.attention_weights.reshape((1, 1, 2, 10)),
xlabel='Keys', ylabel='Queries')