pretrain_t5.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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 T5"""
  16. from functools import partial
  17. import torch
  18. from megatron import (
  19. get_args,
  20. get_timers,
  21. mpu,
  22. print_rank_0
  23. )
  24. from megatron.data.dataset_utils import build_train_valid_test_datasets
  25. from megatron.model import T5Model
  26. from megatron.training import pretrain
  27. from megatron.utils import average_losses_across_data_parallel_group
  28. def model_provider(pre_process=True, post_process=True):
  29. """Build the model."""
  30. assert pre_process and post_process, "T5 doesn't yet support pipelining"
  31. print_rank_0('building T5 model ...')
  32. model = T5Model(num_tokentypes=0,
  33. parallel_output=True)
  34. return model
  35. def get_batch(data_iterator):
  36. """Build the batch."""
  37. keys = ['text_enc', 'text_dec', 'labels', 'loss_mask',
  38. 'enc_mask', 'dec_mask', 'enc_dec_mask']
  39. datatype = torch.int64
  40. # Broadcast data.
  41. if data_iterator is not None:
  42. data = next(data_iterator)
  43. else:
  44. data = None
  45. data_b = mpu.broadcast_data(keys, data, datatype)
  46. # Unpack.
  47. tokens_enc = data_b['text_enc'].long()
  48. tokens_dec = data_b['text_dec'].long()
  49. labels = data_b['labels'].long()
  50. loss_mask = data_b['loss_mask'].float()
  51. enc_mask = (data_b['enc_mask'] < 0.5)
  52. dec_mask = (data_b['dec_mask'] < 0.5)
  53. enc_dec_mask = (data_b['enc_dec_mask'] < 0.5)
  54. return tokens_enc, tokens_dec, loss_mask, labels, \
  55. enc_mask, dec_mask, enc_dec_mask
  56. def loss_func(loss_mask, output_tensor):
  57. lm_loss_, _ = output_tensor
  58. lm_loss_ = lm_loss_.float()
  59. lm_loss = torch.sum(
  60. lm_loss_.view(-1) * loss_mask.reshape(-1)) / loss_mask.sum()
  61. loss = lm_loss
  62. averaged_losses = average_losses_across_data_parallel_group([lm_loss])
  63. return loss, {'lm loss': averaged_losses[0]}
  64. def forward_step(data_iterator, model):
  65. """Forward step."""
  66. args = get_args()
  67. timers = get_timers()
  68. # Get the batch.
  69. timers('batch generator').start()
  70. tokens_enc, tokens_dec, loss_mask, lm_labels, enc_mask, dec_mask, enc_dec_mask \
  71. = get_batch(data_iterator)
  72. timers('batch generator').stop()
  73. # Forward model lm_labels
  74. output_tensor = model(tokens_enc,
  75. tokens_dec,
  76. enc_mask,
  77. dec_mask,
  78. enc_dec_mask,
  79. tokentype_ids=None,
  80. lm_labels=lm_labels)
  81. return output_tensor, partial(loss_func, loss_mask)
  82. def train_valid_test_datasets_provider(train_val_test_num_samples):
  83. """Build train, valid, and test datasets."""
  84. args = get_args()
  85. print_rank_0('> building train, validation, and test datasets '
  86. 'for T5 ...')
  87. train_ds, valid_ds, test_ds = build_train_valid_test_datasets(
  88. data_prefix=args.data_path,
  89. data_impl=args.data_impl,
  90. splits_string=args.split,
  91. train_valid_test_num_samples=train_val_test_num_samples,
  92. max_seq_length=args.encoder_seq_length,
  93. max_seq_length_dec=args.decoder_seq_length,
  94. masked_lm_prob=args.mask_prob,
  95. short_seq_prob=args.short_seq_prob,
  96. seed=args.seed,
  97. skip_warmup=(not args.mmap_warmup),
  98. dataset_type='t5')
  99. print_rank_0("> finished creating T5 datasets ...")
  100. return train_ds, valid_ds, test_ds
  101. if __name__ == "__main__":
  102. pretrain(train_valid_test_datasets_provider, model_provider, forward_step,
  103. args_defaults={'tokenizer_type': 'BertWordPieceLowerCase'})