第16章自然言語処理:応用
16.7.3. Fine-Tuning BERT16.7.3 BERTを微調整する
As Fig. 16.6.2 indicates, fine-tuning BERT for natural language inference requires only an extra MLP consisting of two fully connected layers (see
self.hidden and self.output in the following BERTClassifier class). This MLP transforms the BERT representation of the special “<cls>” token, which encodes the information of both the premise and the hypothesis, into three outputs of natural language inference: entailment, contradiction, and neutral.英語のヒント
図16.6.2が示すように、自然言語推論のためにBERTを微調整するには、二つの全結合層からなる追加のMLPだけがあればよい(次の
BERTClassifierクラスのself.hiddenとself.outputを参照)。このMLPは、前提と仮説の両方の情報を符号化した特殊な「<cls>」トークンのBERT表現を、自然言語推論の三つの出力、つまり含意、矛盾、中立に変換する。class BERTClassifier(nn.Module):
def __init__(self, bert):
super(BERTClassifier, self).__init__()
self.encoder = bert.encoder
self.hidden = bert.hidden
self.output = nn.LazyLinear(3)
def forward(self, inputs):
tokens_X, segments_X, valid_lens_x = inputs
encoded_X = self.encoder(tokens_X, segments_X, valid_lens_x)
return self.output(self.hidden(encoded_X[:, 0, :]))In the following, the pretrained BERT model
bert is fed into the BERTClassifier instance net for the downstream application. In common implementations of BERT fine-tuning, only the parameters of the output layer of the additional MLP (net.output) will be learned from scratch. All the parameters of the pretrained BERT encoder (net.encoder) and the hidden layer of the additional MLP (net.hidden) will be fine-tuned.英語のヒント
以下では、下流の応用のために、事前学習したBERTモデル
bertをBERTClassifierのインスタンスnetに入れる。BERTの微調整のよくある実装では、追加のMLPの出力層(net.output)のパラメータだけが一から学習される。事前学習したBERTのエンコーダ(net.encoder)と追加のMLPの隠れ層(net.hidden)のパラメータは、すべて微調整される。net = BERTClassifier(bert)Recall that in Section 15.8 both the
MaskLM class and the NextSentencePred class have parameters in their employed MLPs. These parameters are part of those in the pretrained BERT model bert, and thus part of parameters in net. However, such parameters are only for computing the masked language modeling loss and the next sentence prediction loss during pretraining. These two loss functions are irrelevant to fine-tuning downstream applications, thus the parameters of the employed MLPs in MaskLM and NextSentencePred are not updated (staled) when BERT is fine-tuned.英語のヒント
15.8節で、
MaskLMクラスとNextSentencePredクラスのどちらも、使っているMLPにパラメータがあったことを思い出そう。これらのパラメータは、事前学習したBERTモデルbertのパラメータの一部であり、したがってnetのパラメータの一部である。しかし、そうしたパラメータは、事前学習のあいだにマスク言語モデリングの損失と次文予測の損失を計算するためだけのものである。この二つの損失関数は下流の応用の微調整とは無関係なので、BERTを微調整するとき、MaskLMとNextSentencePredで使っているMLPのパラメータは更新されない(古いままになる)。To allow parameters with stale gradients, the flag
ignore_stale_grad=True is set in the step function of d2l.train_batch_ch13. We use this function to train and evaluate the model net using the training set (train_iter) and the testing set (test_iter) of SNLI. Due to the limited computational resources, the training and testing accuracy can be further improved: we leave its discussions in the exercises.英語のヒント
古い勾配をもつパラメータを許すため、
d2l.train_batch_ch13のstep関数でフラグignore_stale_grad=Trueを設定する。この関数を使い、SNLIの訓練集合(train_iter)とテスト集合(test_iter)でモデルnetを訓練し評価する。計算資源が限られているため、訓練とテストの正解率はまだ改善できる。その議論は練習問題に残しておく。lr, num_epochs = 1e-4, 5
trainer = torch.optim.Adam(net.parameters(), lr=lr)
loss = nn.CrossEntropyLoss(reduction='none')
net(next(iter(train_iter))[0])
d2l.train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs, devices)loss 0.520, train acc 0.791, test acc 0.786
10588.8 examples/sec on [device(type='cuda', index=0), device(type='cuda', index=1)]