18.10 Pretraining BERT
With the BERT model implemented in Section 18.8 and the pretraining examples generated from the WikiText-2 dataset in Section 18.9, we will pretrain BERT on the WikiText-2 dataset in this section.
To start, we load the WikiText-2 dataset as minibatches of pretraining examples for masked language modeling and next sentence prediction. The batch size is 512 and the maximum length of a BERT input sequence is 64. Note that in the original BERT model, the maximum length is 512.
batch_size, max_len = 512, 64
train_iter, vocab = d2l.load_data_wiki(batch_size, max_len)18.10.1 Pretraining BERT#
The original BERT has two versions of different model sizes (Devlin et al., 2018). The base model () uses 12 layers (Transformer encoder blocks) with 768 hidden units (hidden size) and 12 self-attention heads. The large model () 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.
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()
# Use reduction='none' so per-token losses can be masked properly below.
loss = nn.CrossEntropyLoss(reduction='none')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.
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 (mask per-token losses before summing)
mlm_l = loss(mlm_Y_hat.reshape(-1, vocab_size), mlm_Y.reshape(-1)) *\
mlm_weights_X.reshape(-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).mean()
l = mlm_l + nsp_l
return mlm_l, nsp_l, lInvoking 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 20.1),
the input num_steps of the following function
specifies the number of iteration steps for training.
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=1e-4)
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. The 50-step run below is a mechanics-only smoke test for the training loop; it is intentionally too short to produce a converged BERT model or meaningful downstream representations.
train_bert(train_iter, net, loss, len(vocab), devices, 50)MLM loss 9.572, NSP loss 0.695
17739.1 sentence pairs/sec on [device(type='cuda', index=0)]
18.10.2 Representing Text with BERT#
After pretraining BERT,
we can use it to represent single text, text pairs, or any token in them.
The following function returns the BERT (net) representations for all tokens
in tokens_a and tokens_b.
def get_bert_encoding(net, tokens_a, tokens_b=None):
tokens, segments = d2l.get_tokens_and_segments(tokens_a, tokens_b)
token_ids = torch.tensor(vocab[tokens], device=devices[0]).unsqueeze(0)
segments = torch.tensor(segments, device=devices[0]).unsqueeze(0)
valid_len = torch.tensor(len(tokens), device=devices[0]).unsqueeze(0)
encoded_X, _, _ = net(token_ids, segments, valid_len)
return encoded_XConsider the sentence "a crane is flying".
Recall the input representation of BERT as discussed in Section 18.8.4.
After inserting special tokens “<cls>” (used for classification)
and “<sep>” (used for separation),
the BERT input sequence has a length of six.
Since zero is the index of the “<cls>” token,
encoded_text[:, 0, :] is the BERT representation of the entire input sentence.
To evaluate the polysemy token "crane",
we also print out the first three elements of the BERT representation of the token.
tokens_a = ['a', 'crane', 'is', 'flying']
encoded_text = get_bert_encoding(net, tokens_a)
# Tokens: '<cls>', 'a', 'crane', 'is', 'flying', '<sep>'
encoded_text_cls = encoded_text[:, 0, :]
encoded_text_crane = encoded_text[:, 2, :]
encoded_text.shape, encoded_text_cls.shape, encoded_text_crane[0][:3](torch.Size([1, 6, 128]),
torch.Size([1, 128]),
tensor([ 0.9016, 0.4447, -0.0867], device='cuda:0', grad_fn=<SliceBackward0>))
Now consider a sentence pair
"a crane driver came" and "he just left".
Similarly, encoded_pair[:, 0, :] is the encoded result of the entire sentence pair from the pretrained BERT.
Note that the first three elements of the polysemy token "crane" are different from those when the context is different.
This supports that BERT representations are context-sensitive.
tokens_a, tokens_b = ['a', 'crane', 'driver', 'came'], ['he', 'just', 'left']
encoded_pair = get_bert_encoding(net, tokens_a, tokens_b)
# Tokens: '<cls>', 'a', 'crane', 'driver', 'came', '<sep>', 'he', 'just',
# 'left', '<sep>'
encoded_pair_cls = encoded_pair[:, 0, :]
encoded_pair_crane = encoded_pair[:, 2, :]
encoded_pair.shape, encoded_pair_cls.shape, encoded_pair_crane[0][:3](torch.Size([1, 10, 128]),
torch.Size([1, 128]),
tensor([0.7826, 0.3459, 0.4152], device='cuda:0', grad_fn=<SliceBackward0>))
In Chapter 19, we will fine-tune a pretrained BERT model for downstream natural language processing applications.
18.10.3 Summary#
- The original BERT has two versions, where the base model has 110 million parameters and the large model has 340 million parameters.
- After pretraining BERT, we can use it to represent single text, text pairs, or any token in them.
- In the experiment, the same token has different BERT representation when their contexts are different. This supports that BERT representations are context-sensitive.
18.10.4 Exercises#
- In the experiment, we can see that the masked language modeling loss is significantly higher than the next sentence prediction loss. Why?
- Set the maximum length of a BERT input sequence to be 512 (same as the original BERT model). Use the configurations of the original BERT model such as . Do you encounter any error when running this section? Why?
- The text quotes 110 million parameters for
and 340 million for
.
- Write the number of parameters of
BERTEncoderas a function of the vocabulary size , the hidden size , the hidden size of the positionwise feed-forward network, the number of blocks , andmax_len. Note that its attention projections have biases. - Evaluate the function for both models with ,
max_len= 512, and , and compare with the quoted numbers. - Count the parameters of
netin this section with code. What fraction lies in the token embedding and in the output layer ofMaskLM? How many parameters would tying the output weights ofMaskLMto the token embedding save?
- Write the number of parameters of
- The section compares the first three elements of the encoding of
"crane" in two contexts and concludes that BERT representations are
context-sensitive.
- Encode "a crane is flying" twice with
get_bert_encodingand compare the two encodings of "crane". If they differ, find the cause and fix it. - Construct a freshly initialized
BERTModelwith the same hyperparameters asnet. For both models, compute the cosine similarity between the encodings of "crane" in the two contexts of this section. - What does the comparison of this section show about pretraining, and
what does it not show? Design a comparison with several sentences
for each meaning of "crane" that tests whether pretraining made the
encodings depend on the meaning, run it on
net, and report the result.
- Encode "a crane is flying" twice with
_WikiTextDatasetdraws the masked positions of every example once, when the dataset is built, so that every pass over the data repeats the same masks.- How many passes over the dataset does the 50-step run of this section make? Could drawing new masks every time an example is loaded change its result?
- Implement such dynamic masking (Liu et al., 2019) by
calling
_get_mlm_data_from_tokensin__getitem__. Train once with static and once with dynamic masking for about ten passes over the data. For each model, report the masked language modeling loss at the end of training and on the same 5,000 examples with newly drawn masks. - Explain the differences among the four numbers.