pretrain_bert.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. # coding=utf-8
  2. # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Pretrain BERT"""
  16. from functools import partial
  17. import torch
  18. import torch.nn.functional as F
  19. from megatron import get_args
  20. from megatron import print_rank_0
  21. from megatron import get_timers
  22. from megatron import mpu
  23. from megatron.data.dataset_utils import build_train_valid_test_datasets
  24. from megatron.model import BertModel
  25. from megatron.training import pretrain
  26. from megatron.utils import average_losses_across_data_parallel_group
  27. def model_provider(pre_process=True, post_process=True):
  28. """Build the model."""
  29. print_rank_0('building BERT model ...')
  30. args = get_args()
  31. num_tokentypes = 2 if args.bert_binary_head else 0
  32. model = BertModel(
  33. num_tokentypes=num_tokentypes,
  34. add_binary_head=args.bert_binary_head,
  35. parallel_output=True,
  36. pre_process=pre_process,
  37. post_process=post_process)
  38. return model
  39. def get_batch(data_iterator):
  40. """Build the batch."""
  41. # Items and their type.
  42. keys = ['text', 'types', 'labels', 'is_random', 'loss_mask', 'padding_mask']
  43. datatype = torch.int64
  44. # Broadcast data.
  45. if data_iterator is not None:
  46. data = next(data_iterator)
  47. else:
  48. data = None
  49. data_b = mpu.broadcast_data(keys, data, datatype)
  50. # Unpack.
  51. tokens = data_b['text'].long()
  52. types = data_b['types'].long()
  53. sentence_order = data_b['is_random'].long()
  54. loss_mask = data_b['loss_mask'].float()
  55. lm_labels = data_b['labels'].long()
  56. padding_mask = data_b['padding_mask'].long()
  57. return tokens, types, sentence_order, loss_mask, lm_labels, padding_mask
  58. def loss_func(loss_mask, sentence_order, output_tensor):
  59. lm_loss_, sop_logits = output_tensor
  60. lm_loss_ = lm_loss_.float()
  61. loss_mask = loss_mask.float()
  62. lm_loss = torch.sum(
  63. lm_loss_.view(-1) * loss_mask.reshape(-1)) / loss_mask.sum()
  64. if sop_logits is not None:
  65. sop_loss = F.cross_entropy(sop_logits.view(-1, 2).float(),
  66. sentence_order.view(-1),
  67. ignore_index=-1)
  68. sop_loss = sop_loss.float()
  69. loss = lm_loss + sop_loss
  70. averaged_losses = average_losses_across_data_parallel_group(
  71. [lm_loss, sop_loss])
  72. return loss, {'lm loss': averaged_losses[0],
  73. 'sop loss': averaged_losses[1]}
  74. else:
  75. loss = lm_loss
  76. averaged_losses = average_losses_across_data_parallel_group(
  77. [lm_loss])
  78. return loss, {'lm loss': averaged_losses[0]}
  79. def forward_step(data_iterator, model):
  80. """Forward step."""
  81. args = get_args()
  82. timers = get_timers()
  83. # Get the batch.
  84. timers('batch-generator').start()
  85. tokens, types, sentence_order, loss_mask, lm_labels, padding_mask = get_batch(
  86. data_iterator)
  87. timers('batch-generator').stop()
  88. if not args.bert_binary_head:
  89. types = None
  90. # Forward pass through the model.
  91. output_tensor = model(tokens, padding_mask, tokentype_ids=types,
  92. lm_labels=lm_labels)
  93. return output_tensor, partial(loss_func, loss_mask, sentence_order)
  94. def train_valid_test_datasets_provider(train_val_test_num_samples):
  95. """Build train, valid, and test datasets."""
  96. args = get_args()
  97. print_rank_0('> building train, validation, and test datasets '
  98. 'for BERT ...')
  99. train_ds, valid_ds, test_ds = build_train_valid_test_datasets(
  100. data_prefix=args.data_path,
  101. data_impl=args.data_impl,
  102. splits_string=args.split,
  103. train_valid_test_num_samples=train_val_test_num_samples,
  104. max_seq_length=args.seq_length,
  105. masked_lm_prob=args.mask_prob,
  106. short_seq_prob=args.short_seq_prob,
  107. seed=args.seed,
  108. skip_warmup=(not args.mmap_warmup),
  109. binary_head=args.bert_binary_head)
  110. print_rank_0("> finished creating BERT datasets ...")
  111. return train_ds, valid_ds, test_ds
  112. if __name__ == "__main__":
  113. pretrain(train_valid_test_datasets_provider, model_provider, forward_step,
  114. args_defaults={'tokenizer_type': 'BertWordPieceLowerCase'})