プリンキピア

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

15.10.1. Pretraining BERT15.10.1 BERTを事前学習する

The original BERT has two versions of different model sizes (Devlin et al., 2018). The base model (BERTBASE) uses 12 layers (Transformer encoder blocks) with 768 hidden units (hidden size) and 12 self-attention heads. The large model (BERTLARGE) uses 24 layers with 1024 hidden units and 16 self-attention heads. Notably, the former has 110 million parameters while the latter has 340 million parameters. For demonstration with ease, we define a small BERT, using 2 layers, 128 hidden units, and 2 self-attention heads.
英語のヒント
元のBERTには、モデルの大きさが異なる二つの版がある(Devlin et al., 2018)。基本モデル(BERTBASE)は、768個の隠れユニット(隠れ層の大きさ)と12個の自己注意ヘッドをもつ12層(Transformerのエンコーダブロック)を使う。大規模モデル(BERTLARGE)は、1024個の隠れユニットと16個の自己注意ヘッドをもつ24層を使う。注目すべきことに、前者のパラメータは1億1000万個、後者は3億4000万個である。説明を簡単にするため、2層、128個の隠れユニット、2個の自己注意ヘッドを使う小さなBERTを定義する。
net = d2l.BERTModel(len(vocab), num_hiddens=128,
                    ffn_num_hiddens=256, num_heads=2, num_blks=2, dropout=0.2)
devices = d2l.try_all_gpus()
loss = nn.CrossEntropyLoss()
Before defining the training loop, we define a helper function _get_batch_loss_bert. Given the shard of training examples, this function computes the loss for both the masked language modeling and next sentence prediction tasks. Note that the final loss of BERT pretraining is just the sum of both the masked language modeling loss and the next sentence prediction loss.
英語のヒント
訓練ループを定義する前に、補助関数_get_batch_loss_bertを定義する。訓練事例の断片が与えられると、この関数は、マスク言語モデリングと次文予測の両方のタスクについて損失を計算する。BERTの事前学習の最終的な損失は、マスク言語モデリングの損失と次文予測の損失の単なる和であることに注意しよう。
#@save
def _get_batch_loss_bert(net, loss, vocab_size, tokens_X,
                         segments_X, valid_lens_x,
                         pred_positions_X, mlm_weights_X,
                         mlm_Y, nsp_y):
    # Forward pass
    _, mlm_Y_hat, nsp_Y_hat = net(tokens_X, segments_X,
                                  valid_lens_x.reshape(-1),
                                  pred_positions_X)
    # Compute masked language model loss
    mlm_l = loss(mlm_Y_hat.reshape(-1, vocab_size), mlm_Y.reshape(-1)) *\
    mlm_weights_X.reshape(-1, 1)
    mlm_l = mlm_l.sum() / (mlm_weights_X.sum() + 1e-8)
    # Compute next sentence prediction loss
    nsp_l = loss(nsp_Y_hat, nsp_y)
    l = mlm_l + nsp_l
    return mlm_l, nsp_l, l
Invoking the two aforementioned helper functions, the following train_bert function defines the procedure to pretrain BERT (net) on the WikiText-2 (train_iter) dataset. Training BERT can take very long. Instead of specifying the number of epochs for training as in the train_ch13 function (see Section 14.1), the input num_steps of the following function specifies the number of iteration steps for training.
英語のヒント
前に述べた二つの補助関数を呼び出して、次のtrain_bert関数は、WikiText-2(train_iter)のデータセットでBERT(net)を事前学習する手順を定義する。BERTの訓練にはとても長い時間がかかりうる。train_ch13関数(14.1節を参照)のように訓練のエポック数を指定する代わりに、次の関数の入力num_stepsは、訓練の反復ステップの数を指定する。
def train_bert(train_iter, net, loss, vocab_size, devices, num_steps):
    net(*next(iter(train_iter))[:4])
    net = nn.DataParallel(net, device_ids=devices).to(devices[0])
    trainer = torch.optim.Adam(net.parameters(), lr=0.01)
    step, timer = 0, d2l.Timer()
    animator = d2l.Animator(xlabel='step', ylabel='loss',
                            xlim=[1, num_steps], legend=['mlm', 'nsp'])
    # Sum of masked language modeling losses, sum of next sentence prediction
    # losses, no. of sentence pairs, count
    metric = d2l.Accumulator(4)
    num_steps_reached = False
    while step < num_steps and not num_steps_reached:
        for tokens_X, segments_X, valid_lens_x, pred_positions_X,\
            mlm_weights_X, mlm_Y, nsp_y in train_iter:
            tokens_X = tokens_X.to(devices[0])
            segments_X = segments_X.to(devices[0])
            valid_lens_x = valid_lens_x.to(devices[0])
            pred_positions_X = pred_positions_X.to(devices[0])
            mlm_weights_X = mlm_weights_X.to(devices[0])
            mlm_Y, nsp_y = mlm_Y.to(devices[0]), nsp_y.to(devices[0])
            trainer.zero_grad()
            timer.start()
            mlm_l, nsp_l, l = _get_batch_loss_bert(
                net, loss, vocab_size, tokens_X, segments_X, valid_lens_x,
                pred_positions_X, mlm_weights_X, mlm_Y, nsp_y)
            l.backward()
            trainer.step()
            metric.add(mlm_l, nsp_l, tokens_X.shape[0], 1)
            timer.stop()
            animator.add(step + 1,
                         (metric[0] / metric[3], metric[1] / metric[3]))
            step += 1
            if step == num_steps:
                num_steps_reached = True
                break

    print(f'MLM loss {metric[0] / metric[3]:.3f}, '
          f'NSP loss {metric[1] / metric[3]:.3f}')
    print(f'{metric[2] / timer.sum():.1f} sentence pairs/sec on '
          f'{str(devices)}')
We can plot both the masked language modeling loss and the next sentence prediction loss during BERT pretraining.
英語のヒント
BERTの事前学習のあいだの、マスク言語モデリングの損失と次文予測の損失の両方をプロットできる。
train_bert(train_iter, net, loss, len(vocab), devices, 50)
MLM loss 5.885, NSP loss 0.760
4413.2 sentence pairs/sec on [device(type='cuda', index=0), device(type='cuda', index=1)]