Dlprof_pretrain_gpt.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  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. import pyprof
  29. pyprof.init(enable_function_stack=True)
  30. def model_provider(pre_process=True, post_process=True):
  31. """Build the model."""
  32. print_rank_0('building GPT model ...')
  33. model = GPTModel(
  34. num_tokentypes=0,
  35. parallel_output=True,
  36. pre_process=pre_process,
  37. post_process=post_process
  38. )
  39. return model
  40. def get_batch(data_iterator):
  41. """Generate a batch"""
  42. args = get_args()
  43. tokenizer = get_tokenizer()
  44. # Items and their type.
  45. keys = ['text']
  46. datatype = torch.int64
  47. # Broadcast data.
  48. if data_iterator is not None:
  49. data = next(data_iterator)
  50. else:
  51. data = None
  52. data_b = mpu.broadcast_data(keys, data, datatype)
  53. # Unpack.
  54. tokens_ = data_b['text'].long()
  55. labels = tokens_[:, 1:].contiguous()
  56. tokens = tokens_[:, :-1].contiguous()
  57. # Get the masks and postition ids.
  58. attention_mask, loss_mask, position_ids = get_ltor_masks_and_position_ids(
  59. tokens,
  60. tokenizer.eod,
  61. args.reset_position_ids,
  62. args.reset_attention_mask,
  63. args.eod_mask_loss)
  64. return tokens, labels, loss_mask, attention_mask, position_ids
  65. def loss_func(loss_mask, output_tensor):
  66. losses = output_tensor.float()
  67. loss_mask = loss_mask.view(-1).float()
  68. loss = torch.sum(losses.view(-1) * loss_mask) / loss_mask.sum()
  69. # Reduce loss for logging.
  70. averaged_loss = average_losses_across_data_parallel_group([loss])
  71. return loss, {'lm loss': averaged_loss[0]}
  72. def forward_step(data_iterator, model):
  73. """Forward step."""
  74. args = get_args()
  75. timers = get_timers()
  76. # Get the batch.
  77. timers('batch-generator').start()
  78. tokens, labels, loss_mask, attention_mask, position_ids = get_batch(
  79. data_iterator)
  80. timers('batch-generator').stop()
  81. output_tensor = model(tokens, position_ids, attention_mask,
  82. labels=labels)
  83. return output_tensor, partial(loss_func, loss_mask)
  84. def train_valid_test_datasets_provider(train_val_test_num_samples):
  85. """Build train, valid, and test datasets."""
  86. args = get_args()
  87. print_rank_0('> building train, validation, and test datasets '
  88. 'for GPT ...')
  89. train_ds, valid_ds, test_ds = build_train_valid_test_datasets(
  90. data_prefix=args.data_path,
  91. data_impl=args.data_impl,
  92. splits_string=args.split,
  93. train_valid_test_num_samples=train_val_test_num_samples,
  94. seq_length=args.seq_length,
  95. seed=args.seed,
  96. skip_warmup=(not args.mmap_warmup))
  97. print_rank_0("> finished creating GPT datasets ...")
  98. return train_ds, valid_ds, test_ds
  99. if __name__ == "__main__":
  100. with torch.autograd.profiler.emit_nvtx():
  101. pretrain(train_valid_test_datasets_provider, model_provider, forward_step,
  102. args_defaults={'tokenizer_type': 'GPT2BPETokenizer'})