プリンキピア

第15章自然言語処理:事前学習

15.8.5. Pretraining Tasks15.8.5 事前学習のタスク

The forward inference of BERTEncoder gives the BERT representation of each token of the input text and the inserted special tokens “<cls>” and “<seq>”. Next, we will use these representations to compute the loss function for pretraining BERT. The pretraining is composed of the following two tasks: masked language modeling and next sentence prediction.
英語のヒント
BERTEncoderの順伝播による推論は、入力テキストの各トークンと、挿入した特殊トークン「<cls>」と「<seq>」のBERT表現を与える。次に、これらの表現を使って、BERTを事前学習するための損失関数を計算する。事前学習は、次の二つのタスク、つまりマスク言語モデリングと次文予測からなる。

15.8.5.1. Masked Language Modeling15.8.5.1 マスク言語モデリング

As illustrated in Section 9.3, a language model predicts a token using the context on its left. To encode context bidirectionally for representing each token, BERT randomly masks tokens and uses tokens from the bidirectional context to predict the masked tokens in a self-supervised fashion. This task is referred to as a masked language model.
英語のヒント
9.3節で示したように、言語モデルは、トークンをその左側の文脈を使って予測する。各トークンを表すために文脈を双方向に符号化するため、BERTはランダムにトークンをマスクし、双方向の文脈のトークンを使って、マスクしたトークンを自己教師ありのやり方で予測する。このタスクはマスク言語モデルと呼ばれる。
In this pretraining task, 15% of tokens will be selected at random as the masked tokens for prediction. To predict a masked token without cheating by using the label, one straightforward approach is to always replace it with a special “<mask>” token in the BERT input sequence. However, the artificial special token “<mask>” will never appear in fine-tuning. To avoid such a mismatch between pretraining and fine-tuning, if a token is masked for prediction (e.g., “great” is selected to be masked and predicted in “this movie is great”), in the input it will be replaced with:
英語のヒント
この事前学習のタスクでは、トークンの15%を、予測するためのマスクするトークンとしてランダムに選ぶ。ラベルを使うずるをせずにマスクしたトークンを予測するには、BERTの入力系列の中で、それを常に特殊な「<mask>」トークンに置き換えるのが一つの素直なやり方である。しかし、人工的な特殊トークン「<mask>」は、微調整のときには決して現れない。事前学習と微調整の間のそうした食い違いを避けるため、予測のためにトークンをマスクする場合(たとえば「this movie is great」で「great」がマスクして予測するものとして選ばれた場合)、入力の中でそれを次のものに置き換える。
  • a special “<mask>” token for 80% of the time (e.g., “this movie is great” becomes “this movie is <mask>”);
    英語のヒント
    80%の確率で特殊な「<mask>」トークン(たとえば「this movie is great」は「this movie is <mask>」になる)。
  • a random token for 10% of the time (e.g., “this movie is great” becomes “this movie is drink”);
    英語のヒント
    10%の確率でランダムなトークン(たとえば「this movie is great」は「this movie is drink」になる)。
  • the unchanged label token for 10% of the time (e.g., “this movie is great” becomes “this movie is great”).
    英語のヒント
    10%の確率で変えないラベルのトークン(たとえば「this movie is great」は「this movie is great」のままになる)。
Note that for 10% of 15% time a random token is inserted. This occasional noise encourages BERT to be less biased towards the masked token (especially when the label token remains unchanged) in its bidirectional context encoding.
英語のヒント
15%のうちの10%の場合には、ランダムなトークンが挿入されることに注意しよう。このときどきのノイズは、BERTが双方向の文脈を符号化するときに、マスクしたトークンへの偏り(特にラベルのトークンが変わらないままのとき)を減らすよう促す。
We implement the following MaskLM class to predict masked tokens in the masked language model task of BERT pretraining. The prediction uses a one-hidden-layer MLP (self.mlp). In forward inference, it takes two inputs: the encoded result of BERTEncoder and the token positions for prediction. The output is the prediction results at these positions.
英語のヒント
BERTの事前学習のマスク言語モデルのタスクで、マスクしたトークンを予測するため、次のMaskLMクラスを実装する。予測には、隠れ層が一つのMLP(self.mlp)を使う。順伝播による推論では、二つの入力、つまりBERTEncoderで符号化した結果と、予測するトークンの位置をとる。出力は、それらの位置での予測結果である。
#@save
class MaskLM(nn.Module):
    """The masked language model task of BERT."""
    def __init__(self, vocab_size, num_hiddens, **kwargs):
        super(MaskLM, self).__init__(**kwargs)
        self.mlp = nn.Sequential(nn.LazyLinear(num_hiddens),
                                 nn.ReLU(),
                                 nn.LayerNorm(num_hiddens),
                                 nn.LazyLinear(vocab_size))

    def forward(self, X, pred_positions):
        num_pred_positions = pred_positions.shape[1]
        pred_positions = pred_positions.reshape(-1)
        batch_size = X.shape[0]
        batch_idx = torch.arange(0, batch_size)
        # Suppose that `batch_size` = 2, `num_pred_positions` = 3, then
        # `batch_idx` is `torch.tensor([0, 0, 0, 1, 1, 1])`
        batch_idx = torch.repeat_interleave(batch_idx, num_pred_positions)
        masked_X = X[batch_idx, pred_positions]
        masked_X = masked_X.reshape((batch_size, num_pred_positions, -1))
        mlm_Y_hat = self.mlp(masked_X)
        return mlm_Y_hat
To demonstrate the forward inference of MaskLM, we create its instance mlm and initialize it. Recall that encoded_X from the forward inference of BERTEncoder represents 2 BERT input sequences. We define mlm_positions as the 3 indices to predict in either BERT input sequence of encoded_X. The forward inference of mlm returns prediction results mlm_Y_hat at all the masked positions mlm_positions of encoded_X. For each prediction, the size of the result is equal to the vocabulary size.
英語のヒント
MaskLMの順伝播による推論を示すため、そのインスタンスmlmを作って初期化する。BERTEncoderの順伝播による推論で得たencoded_Xは、二つのBERTの入力系列を表していたことを思い出そう。encoded_XのどちらのBERTの入力系列でも予測する三つのインデックスとして、mlm_positionsを定める。mlmの順伝播による推論は、encoded_Xのマスクしたすべての位置mlm_positionsでの予測結果mlm_Y_hatを返す。各予測について、結果の大きさは語彙の大きさに等しい。
mlm = MaskLM(vocab_size, num_hiddens)
mlm_positions = torch.tensor([[1, 5, 2], [6, 1, 5]])
mlm_Y_hat = mlm(encoded_X, mlm_positions)
mlm_Y_hat.shape
torch.Size([2, 3, 10000])
With the ground truth labels mlm_Y of the predicted tokens mlm_Y_hat under masks, we can calculate the cross-entropy loss of the masked language model task in BERT pretraining.
英語のヒント
マスクのもとで予測したトークンmlm_Y_hatの正解ラベルmlm_Yがあれば、BERTの事前学習でのマスク言語モデルのタスクの交差エントロピー損失を計算できる。
mlm_Y = torch.tensor([[7, 8, 9], [10, 20, 30]])
loss = nn.CrossEntropyLoss(reduction='none')
mlm_l = loss(mlm_Y_hat.reshape((-1, vocab_size)), mlm_Y.reshape(-1))
mlm_l.shape
torch.Size([6])

15.8.5.2. Next Sentence Prediction15.8.5.2 次文予測

Although masked language modeling is able to encode bidirectional context for representing words, it does not explicitly model the logical relationship between text pairs. To help understand the relationship between two text sequences, BERT considers a binary classification task, next sentence prediction, in its pretraining. When generating sentence pairs for pretraining, for half of the time they are indeed consecutive sentences with the label “True”; while for the other half of the time the second sentence is randomly sampled from the corpus with the label “False”.
英語のヒント
マスク言語モデリングは、単語を表すために双方向の文脈を符号化できるが、テキストの対の間の論理的な関係を明示的にはモデル化しない。二つのテキストの系列の間の関係を理解しやすくするため、BERTは事前学習の中で、二値分類のタスクである次文予測を考える。事前学習のために文の対を生成するとき、半分の場合には、それらは実際に連続した文で、ラベルは「True」である。残りの半分の場合には、二つ目の文はコーパスからランダムに抜き出したもので、ラベルは「False」である。
The following NextSentencePred class uses a one-hidden-layer MLP to predict whether the second sentence is the next sentence of the first in the BERT input sequence. Due to self-attention in the Transformer encoder, the BERT representation of the special token “<cls>” encodes both the two sentences from the input. Hence, the output layer (self.output) of the MLP classifier takes X as input, where X is the output of the MLP hidden layer whose input is the encoded “<cls>” token.
英語のヒント
次のNextSentencePredクラスは、隠れ層が一つのMLPを使って、BERTの入力系列の中で二つ目の文が一つ目の文の次の文かどうかを予測する。Transformerのエンコーダの自己注意のおかげで、特殊トークン「<cls>」のBERT表現は、入力の二つの文の両方を符号化している。したがって、MLP分類器の出力層(self.output)はXを入力にとる。ここで、Xは、符号化した「<cls>」トークンを入力とするMLPの隠れ層の出力である。
#@save
class NextSentencePred(nn.Module):
    """The next sentence prediction task of BERT."""
    def __init__(self, **kwargs):
        super(NextSentencePred, self).__init__(**kwargs)
        self.output = nn.LazyLinear(2)

    def forward(self, X):
        # `X` shape: (batch size, `num_hiddens`)
        return self.output(X)
We can see that the forward inference of an NextSentencePred instance returns binary predictions for each BERT input sequence.
英語のヒント
NextSentencePredのインスタンスの順伝播による推論が、各BERTの入力系列について二値の予測を返すことがわかる。
# PyTorch by default will not flatten the tensor as seen in mxnet where, if
# flatten=True, all but the first axis of input data are collapsed together
encoded_X = torch.flatten(encoded_X, start_dim=1)
# input_shape for NSP: (batch size, `num_hiddens`)
nsp = NextSentencePred()
nsp_Y_hat = nsp(encoded_X)
nsp_Y_hat.shape
torch.Size([2, 2])
The cross-entropy loss of the 2 binary classifications can also be computed.
英語のヒント
二つの二値分類の交差エントロピー損失も計算できる。
nsp_y = torch.tensor([0, 1])
nsp_l = loss(nsp_Y_hat, nsp_y)
nsp_l.shape
torch.Size([2])
It is noteworthy that all the labels in both the aforementioned pretraining tasks can be trivially obtained from the pretraining corpus without manual labeling effort. The original BERT has been pretrained on the concatenation of BookCorpus (Zhu et al., 2015) and English Wikipedia. These two text corpora are huge: they have 800 million words and 2.5 billion words, respectively.
英語のヒント
前に述べた二つの事前学習のタスクのラベルはすべて、手作業でラベルをつける手間なしに、事前学習のコーパスからたやすく得られることは注目に値する。元のBERTは、BookCorpus(Zhu et al., 2015)と英語版ウィキペディアを連結したもので事前学習された。この二つのテキストコーパスは巨大で、それぞれ8億語と25億語がある。