pretrain_gpt.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  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 GPT"""
  16. import torch
  17. from functools import partial
  18. from megatron import get_args
  19. from megatron import print_rank_0
  20. from megatron import get_timers
  21. from megatron import get_tokenizer
  22. from megatron import mpu
  23. from megatron.data.gpt_dataset import build_train_valid_test_datasets
  24. from megatron.model import GPTModel
  25. from megatron.training import pretrain
  26. from megatron.utils import get_ltor_masks_and_position_ids
  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. print_rank_0('building GPT model ...')
  31. model = GPTModel(
  32. num_tokentypes=0,
  33. parallel_output=True,
  34. pre_process=pre_process,
  35. post_process=post_process
  36. )
  37. return model
  38. def get_batch(data_iterator):
  39. """Generate a batch"""
  40. args = get_args()
  41. tokenizer = get_tokenizer()
  42. # Items and their type.
  43. keys = ['text']
  44. datatype = torch.int64
  45. # Broadcast data.
  46. if data_iterator is not None:
  47. data = next(data_iterator)
  48. else:
  49. data = None
  50. data_b = mpu.broadcast_data(keys, data, datatype)
  51. # Unpack.
  52. tokens_ = data_b['text'].long()
  53. labels = tokens_[:, 1:].contiguous()
  54. tokens = tokens_[:, :-1].contiguous()
  55. # Get the masks and postition ids.
  56. attention_mask, loss_mask, position_ids = get_ltor_masks_and_position_ids(
  57. tokens,
  58. tokenizer.eod,
  59. args.reset_position_ids,
  60. args.reset_attention_mask,
  61. args.eod_mask_loss)
  62. return tokens, labels, loss_mask, attention_mask, position_ids
  63. def loss_func(loss_mask, output_tensor):
  64. losses = output_tensor.float()
  65. loss_mask = loss_mask.view(-1).float()
  66. loss = torch.sum(losses.view(-1) * loss_mask) / loss_mask.sum()
  67. # Reduce loss for logging.
  68. averaged_loss = average_losses_across_data_parallel_group([loss])
  69. return loss, {'lm loss': averaged_loss[0]}
  70. def forward_step(data_iterator, model):
  71. """Forward step."""
  72. args = get_args()
  73. timers = get_timers()
  74. # Get the batch.
  75. timers('batch-generator').start()
  76. tokens, labels, loss_mask, attention_mask, position_ids = get_batch(
  77. data_iterator)
  78. timers('batch-generator').stop()
  79. output_tensor = model(tokens, position_ids, attention_mask,
  80. labels=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 GPT ...')
  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. seq_length=args.seq_length,
  93. seed=args.seed,
  94. skip_warmup=(not args.mmap_warmup))
  95. print_rank_0("> finished creating GPT datasets ...")
  96. return train_ds, valid_ds, test_ds
  97. if __name__ == "__main__":
  98. pretrain(train_valid_test_datasets_provider, model_provider, forward_step,
  99. args_defaults={'tokenizer_type': 'GPT2BPETokenizer'})