第11章注意機構とTransformer
11.3.2. Convenience Functions11.3.2 便利な関数
We need a few functions to make the attention mechanism efficient to deploy. This includes tools for dealing with strings of variable lengths (common for natural language processing) and tools for efficient evaluation on minibatches (batch matrix multiplication).
英語のヒント
注意機構を効率よく使えるようにするには、いくつかの関数が必要である。これには、(自然言語処理でよくある)可変長の文字列を扱うための道具と、ミニバッチで効率よく評価するための道具(バッチ行列積)が含まれる。
11.3.2.1. Masked Softmax Operation11.3.2.1 マスクつきソフトマックス演算
One of the most popular applications of the attention mechanism is to sequence models. Hence we need to be able to deal with sequences of different lengths. In some cases, such sequences may end up in the same minibatch, necessitating padding with dummy tokens for shorter sequences (see Section 10.5 for an example). These special tokens do not carry meaning. For instance, assume that we have the following three sentences:
英語のヒント
注意機構の最も人気のある応用の一つは、系列モデルである。そのため、長さの異なる系列を扱える必要がある。場合によっては、そうした系列が同じミニバッチに入り、短い系列にはダミーのトークンで詰め物をする必要が出てくる(例は10.5節を参照)。これらの特別なトークンは意味を担わない。たとえば、次の三つの文があるとしよう。
Dive into Deep Learning
Learn to code <blank>
Hello world <blank> <blank>Since we do not want blanks in our attention model we simply need to limit to for however long, , the actual sentence is. Since it is such a common problem, it has a name: the masked softmax operation.
英語のヒント
注意のモデルに空白は入れたくないので、実際の文の長さがどれだけであれ、について、をに制限すればよい。これはとてもよくある問題なので、名前がついている。マスクつきソフトマックス演算である。
Let’s implement it. Actually, the implementation cheats ever so slightly by setting the values of , for , to zero. Moreover, it sets the attention weights to a large negative number, such as , in order to make their contribution to gradients and values vanish in practice. This is done since linear algebra kernels and operators are heavily optimized for GPUs and it is faster to be slightly wasteful in computation rather than to have code with conditional (if then else) statements.
英語のヒント
実装しよう。実は、この実装は、についての値を0に設定するという、ほんの少しのごまかしをしている。さらに、勾配と値への寄与が実際上消えるように、注意の重みをのような大きな負の数に設定する。こうするのは、線形代数のカーネルと演算子はGPU向けに高度に最適化されており、条件(if then else)文をもつコードにするより、計算を少し無駄にするほうが速いからである。
def masked_softmax(X, valid_lens): #@save
"""Perform softmax operation by masking elements on the last axis."""
# X: 3D tensor, valid_lens: 1D or 2D tensor
def _sequence_mask(X, valid_len, value=0):
maxlen = X.size(1)
mask = torch.arange((maxlen), dtype=torch.float32,
device=X.device)[None, :] < valid_len[:, None]
X[~mask] = value
return X
if valid_lens is None:
return nn.functional.softmax(X, dim=-1)
else:
shape = X.shape
if valid_lens.dim() == 1:
valid_lens = torch.repeat_interleave(valid_lens, shape[1])
else:
valid_lens = valid_lens.reshape(-1)
# On the last axis, replace masked elements with a very large negative
# value, whose exponentiation outputs 0
X = _sequence_mask(X.reshape(-1, shape[-1]), valid_lens, value=-1e6)
return nn.functional.softmax(X.reshape(shape), dim=-1)To illustrate how this function works, consider a minibatch of two examples of size , where their valid lengths are and , respectively. As a result of the masked softmax operation, values beyond the valid lengths for each pair of vectors are all masked as zero.
英語のヒント
この関数がどう働くかを示すため、大きさの二つの事例からなるミニバッチを考えよう。その有効な長さはそれぞれとである。マスクつきソフトマックス演算の結果、ベクトルの各組で有効な長さを超える値は、すべて0としてマスクされる。
masked_softmax(torch.rand(2, 2, 4), torch.tensor([2, 3]))tensor([[[0.4448, 0.5552, 0.0000, 0.0000],
[0.4032, 0.5968, 0.0000, 0.0000]],
[[0.2795, 0.2805, 0.4400, 0.0000],
[0.2798, 0.3092, 0.4110, 0.0000]]])If we need more fine-grained control to specify the valid length for each of the two vectors of every example, we simply use a two-dimensional tensor of valid lengths. This yields:
英語のヒント
各事例の二つのベクトルそれぞれについて有効な長さを指定するもっと細かい制御が必要なら、有効な長さの2次元テンソルを使えばよい。すると次のようになる。
masked_softmax(torch.rand(2, 2, 4), torch.tensor([[1, 3], [2, 4]]))tensor([[[1.0000, 0.0000, 0.0000, 0.0000],
[0.4109, 0.2794, 0.3097, 0.0000]],
[[0.3960, 0.6040, 0.0000, 0.0000],
[0.2557, 0.1833, 0.2420, 0.3190]]])11.3.2.2. Batch Matrix Multiplication11.3.2.2 バッチ行列積
Another commonly used operation is to multiply batches of matrices by one another. This comes in handy when we have minibatches of queries, keys, and values. More specifically, assume that
英語のヒント
もう一つのよく使われる演算は、行列のバッチどうしを掛け合わせることである。これは、クエリ、キー、バリューのミニバッチがあるときに役に立つ。もっと具体的には、次のようだとする。
(11.3.4)
Then the batch matrix multiplication (BMM) computes the elementwise product
英語のヒント
すると、バッチ行列積(BMM)は、要素ごとの積を計算する。
(11.3.5)
Let’s see this in action in a deep learning framework.
英語のヒント
深層学習のフレームワークでこれが働くところを見てみよう。
Q = torch.ones((2, 3, 4))
K = torch.ones((2, 4, 6))
d2l.check_shape(torch.bmm(Q, K), (2, 3, 6))