第16章自然言語処理:応用
16.5.1. The Model16.5.1 モデル
Simpler than preserving the order of tokens in premises and hypotheses, we can just align tokens in one text sequence to every token in the other, and vice versa, then compare and aggregate such information to predict the logical relationships between premises and hypotheses. Similar to alignment of tokens between source and target sentences in machine translation, the alignment of tokens between premises and hypotheses can be neatly accomplished by attention mechanisms.
英語のヒント
前提と仮説の中のトークンの順序を保つよりも簡単に、一方のテキストの系列のトークンを他方のすべてのトークンに整列させ、その逆も行い、それからそうした情報を比較し集約して、前提と仮説の間の論理的な関係を予測することができる。機械翻訳での原文と訳文の間のトークンの整列と同じように、前提と仮説の間のトークンの整列は、注意機構できれいに達成できる。
Fig. 16.5.2図16.5.2
Natural language inference using attention mechanisms.
英語のヒント
注意機構を使った自然言語推論。
Fig. 16.5.2 depicts the natural language inference method using attention mechanisms. At a high level, it consists of three jointly trained steps: attending, comparing, and aggregating. We will illustrate them step by step in the following.
英語のヒント
図16.5.2は、注意機構を使った自然言語推論の方法を描いている。大まかに言えば、この方法は、一緒に訓練される三つの段階、つまり注意、比較、集約からなる。以下でそれらを一段階ずつ示す。
import torch
from torch import nn
from torch.nn import functional as F
from d2l import torch as d2l16.5.1.1. Attending16.5.1.1 注意する
The first step is to align tokens in one text sequence to each token in the other sequence. Suppose that the premise is “i do need sleep” and the hypothesis is “i am tired”. Due to semantical similarity, we may wish to align “i” in the hypothesis with “i” in the premise, and align “tired” in the hypothesis with “sleep” in the premise. Likewise, we may wish to align “i” in the premise with “i” in the hypothesis, and align “need” and “sleep” in the premise with “tired” in the hypothesis. Note that such alignment is soft using weighted average, where ideally large weights are associated with the tokens to be aligned. For ease of demonstration, Fig. 16.5.2 shows such alignment in a hard way.
英語のヒント
最初の段階は、一方のテキストの系列のトークンを、もう一方の系列の各トークンに整列させることである。前提が「i do need sleep」(本当に眠りが必要だ)で、仮説が「i am tired」(疲れている)だとしよう。意味が似ているので、仮説の「i」を前提の「i」に、仮説の「tired」を前提の「sleep」に整列させたいだろう。同じように、前提の「i」を仮説の「i」に、前提の「need」と「sleep」を仮説の「tired」に整列させたいだろう。そうした整列は加重平均を使うソフトなものであり、理想的には、整列させるべきトークンに大きな重みが結びつくことに注意しよう。説明しやすくするため、図16.5.2はそうした整列をハードなやり方で示している。
Now we describe the soft alignment using attention mechanisms in more detail. Denote by and the premise and hypothesis, whose number of tokens are and , respectively, where () is a -dimensional word vector. For soft alignment, we compute the attention weights as
英語のヒント
では、注意機構を使ったソフトな整列をもっと詳しく説明しよう。トークンの数がそれぞれとの前提と仮説を、とで表す。ここで、()は次元の単語ベクトルである。ソフトな整列のために、注意の重みを次のように計算する。
(16.5.1)
where the function is an MLP defined in the following
mlp function. The output dimension of is specified by the num_hiddens argument of mlp.英語のヒント
ここで、関数は、次の
mlp関数で定義するMLPである。の出力の次元は、mlpの引数num_hiddensで指定する。def mlp(num_inputs, num_hiddens, flatten):
net = []
net.append(nn.Dropout(0.2))
net.append(nn.Linear(num_inputs, num_hiddens))
net.append(nn.ReLU())
if flatten:
net.append(nn.Flatten(start_dim=1))
net.append(nn.Dropout(0.2))
net.append(nn.Linear(num_hiddens, num_hiddens))
net.append(nn.ReLU())
if flatten:
net.append(nn.Flatten(start_dim=1))
return nn.Sequential(*net)It should be highlighted that, in (16.5.1) takes inputs and separately rather than takes a pair of them together as input. This decomposition trick leads to only applications (linear complexity) of rather than applications (quadratic complexity).
英語のヒント
(16.5.1)で、は入力とを、対として一緒に入力にとるのではなく、別々にとることを強調しておくべきである。この分解の工夫により、の適用は、回(2次の計算量)ではなく回(線形の計算量)だけですむ。
Normalizing the attention weights in (16.5.1), we compute the weighted average of all the token vectors in the hypothesis to obtain representation of the hypothesis that is softly aligned with the token indexed by in the premise:
英語のヒント
(16.5.1)の注意の重みを正規化して、仮説のすべてのトークンのベクトルの加重平均を計算し、前提でをインデックスとするトークンにソフトに整列させた仮説の表現を得る。
(16.5.2)
Likewise, we compute soft alignment of premise tokens for each token indexed by in the hypothesis:
英語のヒント
同じように、仮説でをインデックスとする各トークンについて、前提のトークンのソフトな整列を計算する。
(16.5.3)
Below we define the
Attend class to compute the soft alignment of hypotheses (beta) with input premises A and soft alignment of premises (alpha) with input hypotheses B.英語のヒント
以下では、入力の前提
Aとの仮説のソフトな整列(beta)と、入力の仮説Bとの前提のソフトな整列(alpha)を計算するAttendクラスを定義する。class Attend(nn.Module):
def __init__(self, num_inputs, num_hiddens, **kwargs):
super(Attend, self).__init__(**kwargs)
self.f = mlp(num_inputs, num_hiddens, flatten=False)
def forward(self, A, B):
# Shape of `A`/`B`: (`batch_size`, no. of tokens in sequence A/B,
# `embed_size`)
# Shape of `f_A`/`f_B`: (`batch_size`, no. of tokens in sequence A/B,
# `num_hiddens`)
f_A = self.f(A)
f_B = self.f(B)
# Shape of `e`: (`batch_size`, no. of tokens in sequence A,
# no. of tokens in sequence B)
e = torch.bmm(f_A, f_B.permute(0, 2, 1))
# Shape of `beta`: (`batch_size`, no. of tokens in sequence A,
# `embed_size`), where sequence B is softly aligned with each token
# (axis 1 of `beta`) in sequence A
beta = torch.bmm(F.softmax(e, dim=-1), B)
# Shape of `alpha`: (`batch_size`, no. of tokens in sequence B,
# `embed_size`), where sequence A is softly aligned with each token
# (axis 1 of `alpha`) in sequence B
alpha = torch.bmm(F.softmax(e.permute(0, 2, 1), dim=-1), A)
return beta, alpha16.5.1.2. Comparing16.5.1.2 比較する
In the next step, we compare a token in one sequence with the other sequence that is softly aligned with that token. Note that in soft alignment, all the tokens from one sequence, though with probably different attention weights, will be compared with a token in the other sequence. For easy of demonstration, Fig. 16.5.2 pairs tokens with aligned tokens in a hard way. For example, suppose that the attending step determines that “need” and “sleep” in the premise are both aligned with “tired” in the hypothesis, the pair “tired–need sleep” will be compared.
英語のヒント
次の段階では、一方の系列のトークンを、そのトークンにソフトに整列させたもう一方の系列と比較する。ソフトな整列では、一方の系列のすべてのトークンが、おそらく異なる注意の重みをともなって、もう一方の系列のトークンと比較されることに注意しよう。説明しやすくするため、図16.5.2は、トークンを整列させたトークンとハードなやり方で対にしている。たとえば、注意の段階で前提の「need」と「sleep」がどちらも仮説の「tired」に整列すると決まったとすると、対「tired–need sleep」が比較される。
In the comparing step, we feed the concatenation (operator ) of tokens from one sequence and aligned tokens from the other sequence into a function (an MLP):
英語のヒント
比較の段階では、一方の系列のトークンと、もう一方の系列の整列させたトークンとの連結(演算子)を、関数(MLP)に入れる。
(16.5.4)
In (16.5.4), is the comparison between token in the premise and all the hypothesis tokens that are softly aligned with token ; while is the comparison between token in the hypothesis and all the premise tokens that are softly aligned with token . The following
Compare class defines such as comparing step.英語のヒント
(16.5.4)で、は、前提のトークンと、トークンにソフトに整列させた仮説のすべてのトークンとの比較である。一方、は、仮説のトークンと、トークンにソフトに整列させた前提のすべてのトークンとの比較である。次の
Compareクラスは、そうした比較の段階を定義する。class Compare(nn.Module):
def __init__(self, num_inputs, num_hiddens, **kwargs):
super(Compare, self).__init__(**kwargs)
self.g = mlp(num_inputs, num_hiddens, flatten=False)
def forward(self, A, B, beta, alpha):
V_A = self.g(torch.cat([A, beta], dim=2))
V_B = self.g(torch.cat([B, alpha], dim=2))
return V_A, V_B16.5.1.3. Aggregating16.5.1.3 集約する
With two sets of comparison vectors () and () on hand, in the last step we will aggregate such information to infer the logical relationship. We begin by summing up both sets:
英語のヒント
比較ベクトルの二つの集合()と()が手元にあるので、最後の段階では、そうした情報を集約して論理的な関係を推論する。まず、両方の集合を足し合わせる。
(16.5.5)
Next we feed the concatenation of both summarization results into function (an MLP) to obtain the classification result of the logical relationship:
英語のヒント
次に、両方の合計の結果を連結したものを関数(MLP)に入れて、論理的な関係の分類結果を得る。
(16.5.6)
The aggregation step is defined in the following
Aggregate class.英語のヒント
集約の段階は、次の
Aggregateクラスで定義する。class Aggregate(nn.Module):
def __init__(self, num_inputs, num_hiddens, num_outputs, **kwargs):
super(Aggregate, self).__init__(**kwargs)
self.h = mlp(num_inputs, num_hiddens, flatten=True)
self.linear = nn.Linear(num_hiddens, num_outputs)
def forward(self, V_A, V_B):
# Sum up both sets of comparison vectors
V_A = V_A.sum(dim=1)
V_B = V_B.sum(dim=1)
# Feed the concatenation of both summarization results into an MLP
Y_hat = self.linear(self.h(torch.cat([V_A, V_B], dim=1)))
return Y_hat16.5.1.4. Putting It All Together16.5.1.4 すべてをまとめる
By putting the attending, comparing, and aggregating steps together, we define the decomposable attention model to jointly train these three steps.
英語のヒント
注意、比較、集約の段階をまとめて、この三つの段階を一緒に訓練する分解可能な注意モデルを定義する。
class DecomposableAttention(nn.Module):
def __init__(self, vocab, embed_size, num_hiddens, num_inputs_attend=100,
num_inputs_compare=200, num_inputs_agg=400, **kwargs):
super(DecomposableAttention, self).__init__(**kwargs)
self.embedding = nn.Embedding(len(vocab), embed_size)
self.attend = Attend(num_inputs_attend, num_hiddens)
self.compare = Compare(num_inputs_compare, num_hiddens)
# There are 3 possible outputs: entailment, contradiction, and neutral
self.aggregate = Aggregate(num_inputs_agg, num_hiddens, num_outputs=3)
def forward(self, X):
premises, hypotheses = X
A = self.embedding(premises)
B = self.embedding(hypotheses)
beta, alpha = self.attend(A, B)
V_A, V_B = self.compare(A, B, beta, alpha)
Y_hat = self.aggregate(V_A, V_B)
return Y_hat