The Dataset for Pretraining BERT

:label:sec_bert-dataset

To pretrain the BERT model as implemented in :numref:sec_bert, we need to generate the dataset in the ideal format to facilitate the two pretraining tasks: masked language modeling and next sentence prediction. On one hand, the original BERT model is pretrained on the concatenation of two huge corpora BookCorpus and English Wikipedia (see :numref:subsec_bert_pretraining_tasks), making it hard to run for most readers of this book. On the other hand, the off-the-shelf pretrained BERT model may not fit for applications from specific domains like medicine. Thus, it is getting popular to pretrain BERT on a customized dataset. To facilitate the demonstration of BERT pretraining, we use a smaller corpus WikiText-2 :cite:Merity.Xiong.Bradbury.ea.2016.

Comparing with the PTB dataset used for pretraining word2vec in :numref:sec_word2vec_data, WikiText-2 (i) retains the original punctuation, making it suitable for next sentence prediction; (ii) retains the original case and numbers; (iii) is over twice larger.

```{.python .input} from d2l import mxnet as d2l from mxnet import gluon, np, npx import os import random

npx.set_np()

  1. ```{.python .input}
  2. #@tab pytorch
  3. from d2l import torch as d2l
  4. import os
  5. import random
  6. import torch

In the WikiText-2 dataset, each line represents a paragraph where space is inserted between any punctuation and its preceding token. Paragraphs with at least two sentences are retained. To split sentences, we only use the period as the delimiter for simplicity. We leave discussions of more complex sentence splitting techniques in the exercises at the end of this section.

```{.python .input}

@tab all

@save

d2l.DATA_HUB[‘wikitext-2’] = ( ‘https://s3.amazonaws.com/research.metamind.io/wikitext/‘ ‘wikitext-2-v1.zip’, ‘3c914d17d80b1459be871a5039ac23e752a53cbe’)

@save

def _read_wiki(data_dir): file_name = os.path.join(data_dir, ‘wiki.train.tokens’) with open(file_name, ‘r’) as f: lines = f.readlines()

  1. # Uppercase letters are converted to lowercase ones
  2. paragraphs = [line.strip().lower().split(' . ')
  3. for line in lines if len(line.split(' . ')) >= 2]
  4. random.shuffle(paragraphs)
  5. return paragraphs
  1. ## Defining Helper Functions for Pretraining Tasks
  2. In the following,
  3. we begin by implementing helper functions for the two BERT pretraining tasks:
  4. next sentence prediction and masked language modeling.
  5. These helper functions will be invoked later
  6. when transforming the raw text corpus
  7. into the dataset of the ideal format to pretrain BERT.
  8. ### Generating the Next Sentence Prediction Task
  9. According to descriptions of :numref:`subsec_nsp`,
  10. the `_get_next_sentence` function generates a training example
  11. for the binary classification task.
  12. ```{.python .input}
  13. #@tab all
  14. #@save
  15. def _get_next_sentence(sentence, next_sentence, paragraphs):
  16. if random.random() < 0.5:
  17. is_next = True
  18. else:
  19. # `paragraphs` is a list of lists of lists
  20. next_sentence = random.choice(random.choice(paragraphs))
  21. is_next = False
  22. return sentence, next_sentence, is_next

The following function generates training examples for next sentence prediction from the input paragraph by invoking the _get_next_sentence function. Here paragraph is a list of sentences, where each sentence is a list of tokens. The argument max_len specifies the maximum length of a BERT input sequence during pretraining.

```{.python .input}

@tab all

@save

def _get_nsp_data_from_paragraph(paragraph, paragraphs, vocab, max_len): nsp_data_from_paragraph = [] for i in range(len(paragraph) - 1): tokens_a, tokens_b, is_next = _get_next_sentence( paragraph[i], paragraph[i + 1], paragraphs)

  1. # Consider 1 '<cls>' token and 2 '<sep>' tokens
  2. if len(tokens_a) + len(tokens_b) + 3 > max_len:
  3. continue
  4. tokens, segments = d2l.get_tokens_and_segments(tokens_a, tokens_b)
  5. nsp_data_from_paragraph.append((tokens, segments, is_next))
  6. return nsp_data_from_paragraph
  1. ### Generating the Masked Language Modeling Task
  2. :label:`subsec_prepare_mlm_data`
  3. In order to generate training examples
  4. for the masked language modeling task
  5. from a BERT input sequence,
  6. we define the following `_replace_mlm_tokens` function.
  7. In its inputs, `tokens` is a list of tokens representing a BERT input sequence,
  8. `candidate_pred_positions` is a list of token indices of the BERT input sequence
  9. excluding those of special tokens (special tokens are not predicted in the masked language modeling task),
  10. and `num_mlm_preds` indicates the number of predictions (recall 15% random tokens to predict).
  11. Following the definition of the masked language modeling task in :numref:`subsec_mlm`,
  12. at each prediction position, the input may be replaced by
  13. a special “&lt;mask&gt;” token or a random token, or remain unchanged.
  14. In the end, the function returns the input tokens after possible replacement,
  15. the token indices where predictions take place and labels for these predictions.
  16. ```{.python .input}
  17. #@tab all
  18. #@save
  19. def _replace_mlm_tokens(tokens, candidate_pred_positions, num_mlm_preds,
  20. vocab):
  21. # Make a new copy of tokens for the input of a masked language model,
  22. # where the input may contain replaced '<mask>' or random tokens
  23. mlm_input_tokens = [token for token in tokens]
  24. pred_positions_and_labels = []
  25. # Shuffle for getting 15% random tokens for prediction in the masked
  26. # language modeling task
  27. random.shuffle(candidate_pred_positions)
  28. for mlm_pred_position in candidate_pred_positions:
  29. if len(pred_positions_and_labels) >= num_mlm_preds:
  30. break
  31. masked_token = None
  32. # 80% of the time: replace the word with the '<mask>' token
  33. if random.random() < 0.8:
  34. masked_token = '<mask>'
  35. else:
  36. # 10% of the time: keep the word unchanged
  37. if random.random() < 0.5:
  38. masked_token = tokens[mlm_pred_position]
  39. # 10% of the time: replace the word with a random word
  40. else:
  41. masked_token = random.randint(0, len(vocab) - 1)
  42. mlm_input_tokens[mlm_pred_position] = masked_token
  43. pred_positions_and_labels.append(
  44. (mlm_pred_position, tokens[mlm_pred_position]))
  45. return mlm_input_tokens, pred_positions_and_labels

By invoking the aforementioned _replace_mlm_tokens function, the following function takes a BERT input sequence (tokens) as an input and returns indices of the input tokens (after possible token replacement as described in :numref:subsec_mlm), the token indices where predictions take place, and label indices for these predictions.

```{.python .input}

@tab all

@save

def _get_mlm_data_from_tokens(tokens, vocab): candidate_pred_positions = []

  1. # `tokens` is a list of strings
  2. for i, token in enumerate(tokens):
  3. # Special tokens are not predicted in the masked language modeling
  4. # task
  5. if token in ['<cls>', '<sep>']:
  6. continue
  7. candidate_pred_positions.append(i)
  8. # 15% of random tokens are predicted in the masked language modeling task
  9. num_mlm_preds = max(1, round(len(tokens) * 0.15))
  10. mlm_input_tokens, pred_positions_and_labels = _replace_mlm_tokens(
  11. tokens, candidate_pred_positions, num_mlm_preds, vocab)
  12. pred_positions_and_labels = sorted(pred_positions_and_labels,
  13. key=lambda x: x[0])
  14. pred_positions = [v[0] for v in pred_positions_and_labels]
  15. mlm_pred_labels = [v[1] for v in pred_positions_and_labels]
  16. return vocab[mlm_input_tokens], pred_positions, vocab[mlm_pred_labels]
  1. ## Transforming Text into the Pretraining Dataset
  2. Now we are almost ready to customize a `Dataset` class for pretraining BERT.
  3. Before that,
  4. we still need to define a helper function `_pad_bert_inputs`
  5. to append the special “&lt;mask&gt;” tokens to the inputs.
  6. Its argument `examples` contain the outputs from the helper functions `_get_nsp_data_from_paragraph` and `_get_mlm_data_from_tokens` for the two pretraining tasks.
  7. ```{.python .input}
  8. #@save
  9. def _pad_bert_inputs(examples, max_len, vocab):
  10. max_num_mlm_preds = round(max_len * 0.15)
  11. all_token_ids, all_segments, valid_lens, = [], [], []
  12. all_pred_positions, all_mlm_weights, all_mlm_labels = [], [], []
  13. nsp_labels = []
  14. for (token_ids, pred_positions, mlm_pred_label_ids, segments,
  15. is_next) in examples:
  16. all_token_ids.append(np.array(token_ids + [vocab['<pad>']] * (
  17. max_len - len(token_ids)), dtype='int32'))
  18. all_segments.append(np.array(segments + [0] * (
  19. max_len - len(segments)), dtype='int32'))
  20. # `valid_lens` excludes count of '<pad>' tokens
  21. valid_lens.append(np.array(len(token_ids), dtype='float32'))
  22. all_pred_positions.append(np.array(pred_positions + [0] * (
  23. max_num_mlm_preds - len(pred_positions)), dtype='int32'))
  24. # Predictions of padded tokens will be filtered out in the loss via
  25. # multiplication of 0 weights
  26. all_mlm_weights.append(
  27. np.array([1.0] * len(mlm_pred_label_ids) + [0.0] * (
  28. max_num_mlm_preds - len(pred_positions)), dtype='float32'))
  29. all_mlm_labels.append(np.array(mlm_pred_label_ids + [0] * (
  30. max_num_mlm_preds - len(mlm_pred_label_ids)), dtype='int32'))
  31. nsp_labels.append(np.array(is_next))
  32. return (all_token_ids, all_segments, valid_lens, all_pred_positions,
  33. all_mlm_weights, all_mlm_labels, nsp_labels)

```{.python .input}

@tab pytorch

@save

def _pad_bert_inputs(examples, max_len, vocab): max_num_mlm_preds = round(max_len 0.15) all_token_ids, all_segments, valid_lens, = [], [], [] all_pred_positions, all_mlm_weights, all_mlm_labels = [], [], [] nsp_labels = [] for (token_ids, pred_positions, mlm_pred_label_ids, segments, is_next) in examples: all_token_ids.append(torch.tensor(token_ids + [vocab[‘‘]] ( max_len - len(token_ids)), dtype=torch.long)) all_segments.append(torch.tensor(segments + [0] * ( max_len - len(segments)), dtype=torch.long))

  1. # `valid_lens` excludes count of '<pad>' tokens
  2. valid_lens.append(torch.tensor(len(token_ids), dtype=torch.float32))
  3. all_pred_positions.append(torch.tensor(pred_positions + [0] * (
  4. max_num_mlm_preds - len(pred_positions)), dtype=torch.long))
  5. # Predictions of padded tokens will be filtered out in the loss via
  6. # multiplication of 0 weights
  7. all_mlm_weights.append(
  8. torch.tensor([1.0] * len(mlm_pred_label_ids) + [0.0] * (
  9. max_num_mlm_preds - len(pred_positions)),
  10. dtype=torch.float32))
  11. all_mlm_labels.append(torch.tensor(mlm_pred_label_ids + [0] * (
  12. max_num_mlm_preds - len(mlm_pred_label_ids)), dtype=torch.long))
  13. nsp_labels.append(torch.tensor(is_next, dtype=torch.long))
  14. return (all_token_ids, all_segments, valid_lens, all_pred_positions,
  15. all_mlm_weights, all_mlm_labels, nsp_labels)
  1. Putting the helper functions for
  2. generating training examples of the two pretraining tasks,
  3. and the helper function for padding inputs together,
  4. we customize the following `_WikiTextDataset` class as the WikiText-2 dataset for pretraining BERT.
  5. By implementing the `__getitem__ `function,
  6. we can arbitrarily access the pretraining (masked language modeling and next sentence prediction) examples
  7. generated from a pair of sentences from the WikiText-2 corpus.
  8. The original BERT model uses WordPiece embeddings whose vocabulary size is 30000 :cite:`Wu.Schuster.Chen.ea.2016`.
  9. The tokenization method of WordPiece is a slight modification of
  10. the original byte pair encoding algorithm in :numref:`subsec_Byte_Pair_Encoding`.
  11. For simplicity, we use the `d2l.tokenize` function for tokenization.
  12. Infrequent tokens that appear less than five times are filtered out.
  13. ```{.python .input}
  14. #@save
  15. class _WikiTextDataset(gluon.data.Dataset):
  16. def __init__(self, paragraphs, max_len):
  17. # Input `paragraphs[i]` is a list of sentence strings representing a
  18. # paragraph; while output `paragraphs[i]` is a list of sentences
  19. # representing a paragraph, where each sentence is a list of tokens
  20. paragraphs = [d2l.tokenize(
  21. paragraph, token='word') for paragraph in paragraphs]
  22. sentences = [sentence for paragraph in paragraphs
  23. for sentence in paragraph]
  24. self.vocab = d2l.Vocab(sentences, min_freq=5, reserved_tokens=[
  25. '<pad>', '<mask>', '<cls>', '<sep>'])
  26. # Get data for the next sentence prediction task
  27. examples = []
  28. for paragraph in paragraphs:
  29. examples.extend(_get_nsp_data_from_paragraph(
  30. paragraph, paragraphs, self.vocab, max_len))
  31. # Get data for the masked language model task
  32. examples = [(_get_mlm_data_from_tokens(tokens, self.vocab)
  33. + (segments, is_next))
  34. for tokens, segments, is_next in examples]
  35. # Pad inputs
  36. (self.all_token_ids, self.all_segments, self.valid_lens,
  37. self.all_pred_positions, self.all_mlm_weights,
  38. self.all_mlm_labels, self.nsp_labels) = _pad_bert_inputs(
  39. examples, max_len, self.vocab)
  40. def __getitem__(self, idx):
  41. return (self.all_token_ids[idx], self.all_segments[idx],
  42. self.valid_lens[idx], self.all_pred_positions[idx],
  43. self.all_mlm_weights[idx], self.all_mlm_labels[idx],
  44. self.nsp_labels[idx])
  45. def __len__(self):
  46. return len(self.all_token_ids)

```{.python .input}

@tab pytorch

@save

class WikiTextDataset(torch.utils.data.Dataset): def _init(self, paragraphs, max_len):

  1. # Input `paragraphs[i]` is a list of sentence strings representing a
  2. # paragraph; while output `paragraphs[i]` is a list of sentences
  3. # representing a paragraph, where each sentence is a list of tokens
  4. paragraphs = [d2l.tokenize(
  5. paragraph, token='word') for paragraph in paragraphs]
  6. sentences = [sentence for paragraph in paragraphs
  7. for sentence in paragraph]
  8. self.vocab = d2l.Vocab(sentences, min_freq=5, reserved_tokens=[
  9. '<pad>', '<mask>', '<cls>', '<sep>'])
  10. # Get data for the next sentence prediction task
  11. examples = []
  12. for paragraph in paragraphs:
  13. examples.extend(_get_nsp_data_from_paragraph(
  14. paragraph, paragraphs, self.vocab, max_len))
  15. # Get data for the masked language model task
  16. examples = [(_get_mlm_data_from_tokens(tokens, self.vocab)
  17. + (segments, is_next))
  18. for tokens, segments, is_next in examples]
  19. # Pad inputs
  20. (self.all_token_ids, self.all_segments, self.valid_lens,
  21. self.all_pred_positions, self.all_mlm_weights,
  22. self.all_mlm_labels, self.nsp_labels) = _pad_bert_inputs(
  23. examples, max_len, self.vocab)
  24. def __getitem__(self, idx):
  25. return (self.all_token_ids[idx], self.all_segments[idx],
  26. self.valid_lens[idx], self.all_pred_positions[idx],
  27. self.all_mlm_weights[idx], self.all_mlm_labels[idx],
  28. self.nsp_labels[idx])
  29. def __len__(self):
  30. return len(self.all_token_ids)
  1. By using the `_read_wiki` function and the `_WikiTextDataset` class,
  2. we define the following `load_data_wiki` to download and WikiText-2 dataset
  3. and generate pretraining examples from it.
  4. ```{.python .input}
  5. #@save
  6. def load_data_wiki(batch_size, max_len):
  7. """Load the WikiText-2 dataset."""
  8. num_workers = d2l.get_dataloader_workers()
  9. data_dir = d2l.download_extract('wikitext-2', 'wikitext-2')
  10. paragraphs = _read_wiki(data_dir)
  11. train_set = _WikiTextDataset(paragraphs, max_len)
  12. train_iter = gluon.data.DataLoader(train_set, batch_size, shuffle=True,
  13. num_workers=num_workers)
  14. return train_iter, train_set.vocab

```{.python .input}

@tab pytorch

@save

def load_data_wiki(batch_size, max_len): “””Load the WikiText-2 dataset.””” num_workers = d2l.get_dataloader_workers() data_dir = d2l.download_extract(‘wikitext-2’, ‘wikitext-2’) paragraphs = _read_wiki(data_dir) train_set = _WikiTextDataset(paragraphs, max_len) train_iter = torch.utils.data.DataLoader(train_set, batch_size, shuffle=True, num_workers=num_workers) return train_iter, train_set.vocab

  1. Setting the batch size to 512 and the maximum length of a BERT input sequence to be 64,
  2. we print out the shapes of a minibatch of BERT pretraining examples.
  3. Note that in each BERT input sequence,
  4. $10$ ($64 \times 0.15$) positions are predicted for the masked language modeling task.
  5. ```{.python .input}
  6. #@tab all
  7. batch_size, max_len = 512, 64
  8. train_iter, vocab = load_data_wiki(batch_size, max_len)
  9. for (tokens_X, segments_X, valid_lens_x, pred_positions_X, mlm_weights_X,
  10. mlm_Y, nsp_y) in train_iter:
  11. print(tokens_X.shape, segments_X.shape, valid_lens_x.shape,
  12. pred_positions_X.shape, mlm_weights_X.shape, mlm_Y.shape,
  13. nsp_y.shape)
  14. break

In the end, let us take a look at the vocabulary size. Even after filtering out infrequent tokens, it is still over twice larger than that of the PTB dataset.

```{.python .input}

@tab all

len(vocab) ```

Summary

  • Comparing with the PTB dataset, the WikiText-2 dateset retains the original punctuation, case and numbers, and is over twice larger.
  • We can arbitrarily access the pretraining (masked language modeling and next sentence prediction) examples generated from a pair of sentences from the WikiText-2 corpus.

Exercises

  1. For simplicity, the period is used as the only delimiter for splitting sentences. Try other sentence splitting techniques, such as the spaCy and NLTK. Take NLTK as an example. You need to install NLTK first: pip install nltk. In the code, first import nltk. Then, download the Punkt sentence tokenizer: nltk.download('punkt'). To split sentences such as sentences = 'This is great ! Why not ?', invoking nltk.tokenize.sent_tokenize(sentences) will return a list of two sentence strings: ['This is great !', 'Why not ?'].
  2. What is the vocabulary size if we do not filter out any infrequent token?

:begin_tab:mxnet Discussions :end_tab:

:begin_tab:pytorch Discussions :end_tab: