プリンキピア

第11章注意機構とTransformer

11.6. Self-Attention and Positional Encoding11.6 自己注意と位置符号化

In deep learning, we often use CNNs or RNNs to encode sequences. Now with attention mechanisms in mind, imagine feeding a sequence of tokens into an attention mechanism such that at every step, each token has its own query, keys, and values. Here, when computing the value of a token’s representation at the next layer, the token can attend (via its query vector) to any other’s token (matching based on their key vectors). Using the full set of query-key compatibility scores, we can compute, for each token, a representation by building the appropriate weighted sum over the other tokens. Because every token is attending to each other token (unlike the case where decoder steps attend to encoder steps), such architectures are typically described as self-attention models (Lin et al., 2017, Vaswani et al., 2017), and elsewhere described as intra-attention model (Cheng et al., 2016, Parikh et al., 2016, Paulus et al., 2017). In this section, we will discuss sequence encoding using self-attention, including using additional information for the sequence order.
英語のヒント
深層学習では、系列を符号化するのにCNNやRNNをよく使う。ここで注意機構を念頭に置いて、トークンの系列を注意機構に入れ、各ステップで各トークンがそれぞれのクエリ、キー、バリューをもつようにすることを想像しよう。この場合、次の層でのトークンの表現の値を計算するとき、トークンは(クエリベクトルを通じて)ほかのどのトークンにも(それらのキーベクトルにもとづく照合で)注意を向けられる。クエリとキーの適合度のスコアをすべて使えば、各トークンについて、ほかのトークンにわたる適切な重みつきの和を組み立てることで表現を計算できる。すべてのトークンがほかの各トークンに注意を向けているので(デコーダのステップがエンコーダのステップに注意を向ける場合とは違って)、こうした構造はふつう自己注意のモデルと呼ばれ(Lin et al., 2017、Vaswani et al., 2017)、別のところではイントラ注意のモデルとも呼ばれる(Cheng et al., 2016、Parikh et al., 2016、Paulus et al., 2017)。この節では、系列の順序についての追加の情報を使うことも含めて、自己注意を使った系列の符号化を論じる。
import math
import torch
from torch import nn
from d2l import torch as d2l