第11章注意機構とTransformer
11.6.3. Positional Encoding11.6.3 位置符号化
Unlike RNNs, which recurrently process tokens of a sequence one-by-one, self-attention ditches sequential operations in favor of parallel computation. Note that self-attention by itself does not preserve the order of the sequence. What do we do if it really matters that the model knows in which order the input sequence arrived?
英語のヒント
系列のトークンを一つずつ再帰的に処理するRNNとは違って、自己注意は並列計算のために逐次的な演算を捨てる。自己注意だけでは系列の順序が保たれないことに注意してほしい。入力系列がどの順序で届いたかをモデルが知ることが本当に重要な場合は、どうすればよいだろうか。
The dominant approach for preserving information about the order of tokens is to represent this to the model as an additional input associated with each token. These inputs are called positional encodings, and they can either be learned or fixed a priori. We now describe a simple scheme for fixed positional encodings based on sine and cosine functions (Vaswani et al., 2017).
英語のヒント
トークンの順序についての情報を保つための支配的なやり方は、これを各トークンに結びついた追加の入力としてモデルに表すことである。これらの入力は位置符号化と呼ばれ、学習することも、前もって固定することもできる。ここでは、正弦と余弦の関数にもとづく、固定された位置符号化の単純な仕組みを説明する(Vaswani et al., 2017)。
Suppose that the input representation contains the -dimensional embeddings for tokens of a sequence. The positional encoding outputs using a positional embedding matrix of the same shape, whose element on the row and the or the column is
英語のヒント
入力の表現が、系列の個のトークンの次元の埋め込みを含むとする。位置符号化は、同じ形状の位置埋め込み行列を使ってを出力する。そのの行、あるいはの列にある要素は次のとおりである。
(11.6.2)
At first glance, this trigonometric function design looks weird. Before we give explanations of this design, let’s first implement it in the following
PositionalEncoding class.英語のヒント
一見すると、この三角関数による設計は奇妙に見える。この設計の説明をする前に、まず以下の
PositionalEncodingクラスで実装しよう。class PositionalEncoding(nn.Module): #@save
"""Positional encoding."""
def __init__(self, num_hiddens, dropout, max_len=1000):
super().__init__()
self.dropout = nn.Dropout(dropout)
# Create a long enough P
self.P = torch.zeros((1, max_len, num_hiddens))
X = torch.arange(max_len, dtype=torch.float32).reshape(
-1, 1) / torch.pow(10000, torch.arange(
0, num_hiddens, 2, dtype=torch.float32) / num_hiddens)
self.P[:, :, 0::2] = torch.sin(X)
self.P[:, :, 1::2] = torch.cos(X)
def forward(self, X):
X = X + self.P[:, :X.shape[1], :].to(X.device)
return self.dropout(X)In the positional embedding matrix , rows correspond to positions within a sequence and columns represent different positional encoding dimensions. In the example below, we can see that the and the columns of the positional embedding matrix have a higher frequency than the and the columns. The offset between the and the (same for the and the ) columns is due to the alternation of sine and cosine functions.
英語のヒント
位置埋め込み行列では、行が系列の中の位置に対応し、列が位置符号化の異なる次元を表す。以下の例では、位置埋め込み行列の列と列が、列と列より周波数が高いことがわかる。列と列のあいだ(列と列も同じ)のずれは、正弦と余弦の関数が交互に並んでいることによる。
encoding_dim, num_steps = 32, 60
pos_encoding = PositionalEncoding(encoding_dim, 0)
X = pos_encoding(torch.zeros((1, num_steps, encoding_dim)))
P = pos_encoding.P[:, :X.shape[1], :]
d2l.plot(torch.arange(num_steps), P[0, :, 6:10].T, xlabel='Row (position)',
figsize=(6, 2.5), legend=["Col %d" % d for d in torch.arange(6, 10)])11.6.3.1. Absolute Positional Information11.6.3.1 絶対的な位置の情報
To see how the monotonically decreased frequency along the encoding dimension relates to absolute positional information, let’s print out the binary representations of . As we can see, the lowest bit, the second-lowest bit, and the third-lowest bit alternate on every number, every two numbers, and every four numbers, respectively.
英語のヒント
符号化の次元に沿って単調に下がる周波数が絶対的な位置の情報とどう関係するかを見るため、の二進表現を表示しよう。見てのとおり、最下位ビット、下から2番目のビット、下から3番目のビットは、それぞれ一つごと、二つごと、四つごとに入れ替わる。
for i in range(8):
print(f'{i} in binary is {i:>03b}')0 in binary is 000
1 in binary is 001
2 in binary is 010
3 in binary is 011
4 in binary is 100
5 in binary is 101
6 in binary is 110
7 in binary is 111In binary representations, a higher bit has a lower frequency than a lower bit. Similarly, as demonstrated in the heat map below, the positional encoding decreases frequencies along the encoding dimension by using trigonometric functions. Since the outputs are float numbers, such continuous representations are more space-efficient than binary representations.
英語のヒント
二進表現では、上位のビットは下位のビットより周波数が低い。同じように、下のヒートマップに示すように、位置符号化は三角関数を使って符号化の次元に沿って周波数を下げる。出力は浮動小数点数なので、こうした連続的な表現は二進表現より空間の効率がよい。
P = P[0, :, :].unsqueeze(0).unsqueeze(0)
d2l.show_heatmaps(P, xlabel='Column (encoding dimension)',
ylabel='Row (position)', figsize=(3.5, 4), cmap='Blues')11.6.3.2. Relative Positional Information11.6.3.2 相対的な位置の情報
Besides capturing absolute positional information, the above positional encoding also allows a model to easily learn to attend by relative positions. This is because for any fixed position offset , the positional encoding at position can be represented by a linear projection of that at position .
英語のヒント
絶対的な位置の情報をとらえるだけでなく、上の位置符号化は、モデルが相対的な位置によって注意を向けることを簡単に学習できるようにもする。これは、任意の固定された位置のずれについて、位置での位置符号化が、位置でのものの線形射影で表せるからである。
This projection can be explained mathematically. Denoting , any pair of in (11.6.2) can be linearly projected to for any fixed offset :
英語のヒント
この射影は数学的に説明できる。と表すと、(11.6.2)の任意の組は、任意の固定されたずれについて、へと線形に射影できる。
(11.6.3)
where the projection matrix does not depend on any position index .
英語のヒント
ここで、の射影行列は、どの位置のインデックスにも依存しない。