プリンキピア

第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 𝐗∈ℝn×d contains the d-dimensional embeddings for n tokens of a sequence. The positional encoding outputs 𝐗+𝐏 using a positional embedding matrix 𝐏∈ℝn×d of the same shape, whose element on the ith row and the (2j)th or the (2j+1)th column is
英語のヒント
入力の表現𝐗∈ℝn×dが、系列のn個のトークンのd次元の埋め込みを含むとする。位置符号化は、同じ形状の位置埋め込み行列𝐏∈ℝn×dを使って𝐗+𝐏を出力する。そのithの行、(2j)thあるいは(2j+1)thの列にある要素は次のとおりである。
pi,2j=sin⁡(i100002j/d),pi,2j+1=cos⁡(i100002j/d).(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 6th and the 7th columns of the positional embedding matrix have a higher frequency than the 8th and the 9th columns. The offset between the 6th and the 7th (same for the 8th and the 9th) columns is due to the alternation of sine and cosine functions.
英語のヒント
位置埋め込み行列𝐏では、行が系列の中の位置に対応し、列が位置符号化の異なる次元を表す。以下の例では、位置埋め込み行列の6th列と7th列が、8th列と9th列より周波数が高いことがわかる。6th列と7th列のあいだ(8th列と9th列も同じ)のずれは、正弦と余弦の関数が交互に並んでいることによる。
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 0,1,…,7. 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.
英語のヒント
符号化の次元に沿って単調に下がる周波数が絶対的な位置の情報とどう関係するかを見るため、0,1,…,7の二進表現を表示しよう。見てのとおり、最下位ビット、下から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 111
In 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 i+δ can be represented by a linear projection of that at position i.
英語のヒント
絶対的な位置の情報をとらえるだけでなく、上の位置符号化は、モデルが相対的な位置によって注意を向けることを簡単に学習できるようにもする。これは、任意の固定された位置のずれδについて、位置i+δでの位置符号化が、位置iでのものの線形射影で表せるからである。
This projection can be explained mathematically. Denoting ωj=1/100002j/d, any pair of (pi,2j,pi,2j+1) in (11.6.2) can be linearly projected to (pi+δ,2j,pi+δ,2j+1) for any fixed offset δ:
英語のヒント
この射影は数学的に説明できる。ωj=1/100002j/dと表すと、(11.6.2)の任意の組(pi,2j,pi,2j+1)は、任意の固定されたずれδについて、(pi+δ,2j,pi+δ,2j+1)へと線形に射影できる。
[cos⁡(δωj)sin⁡(δωj)−sin⁡(δωj)cos⁡(δωj)][pi,2jpi,2j+1]=[cos⁡(δωj)sin⁡(iωj)+sin⁡(δωj)cos⁡(iωj)−sin⁡(δωj)sin⁡(iωj)+cos⁡(δωj)cos⁡(iωj)]=[sin⁡((i+δ)ωj)cos⁡((i+δ)ωj)]=[pi+δ,2jpi+δ,2j+1],(11.6.3)
where the 2×2 projection matrix does not depend on any position index i.
英語のヒント
ここで、2×2の射影行列は、どの位置のインデックスiにも依存しない。