You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

run_pretrain.py 10 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """
  16. #################pre_train bert example on zh-wiki########################
  17. python run_pretrain.py
  18. """
  19. import os
  20. import argparse
  21. import numpy
  22. import mindspore.communication.management as D
  23. import mindspore.common.dtype as mstype
  24. from mindspore import context
  25. from mindspore.train.model import Model
  26. from mindspore.train.parallel_utils import ParallelMode
  27. from mindspore.nn.wrap.loss_scale import DynamicLossScaleUpdateCell
  28. from mindspore.train.callback import Callback, ModelCheckpoint, CheckpointConfig, TimeMonitor
  29. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  30. from mindspore.nn.optim import Lamb, Momentum, AdamWeightDecayDynamicLR
  31. from mindspore import log as logger
  32. from src import BertNetworkWithLoss, BertTrainOneStepCell, BertTrainOneStepWithLossScaleCell
  33. from src.dataset import create_bert_dataset
  34. from src.config import cfg, bert_net_cfg
  35. _current_dir = os.path.dirname(os.path.realpath(__file__))
  36. class LossCallBack(Callback):
  37. """
  38. Monitor the loss in training.
  39. If the loss in NAN or INF terminating training.
  40. Note:
  41. if per_print_times is 0 do not print loss.
  42. Args:
  43. per_print_times (int): Print loss every times. Default: 1.
  44. """
  45. def __init__(self, per_print_times=1):
  46. super(LossCallBack, self).__init__()
  47. if not isinstance(per_print_times, int) or per_print_times < 0:
  48. raise ValueError("print_step must be int and >= 0")
  49. self._per_print_times = per_print_times
  50. def step_end(self, run_context):
  51. cb_params = run_context.original_args()
  52. print("epoch: {}, step: {}, outputs are {}".format(cb_params.cur_epoch_num, cb_params.cur_step_num,
  53. str(cb_params.net_outputs)))
  54. def run_pretrain():
  55. """pre-train bert_clue"""
  56. parser = argparse.ArgumentParser(description='bert pre_training')
  57. parser.add_argument('--device_target', type=str, default='Ascend', choices=['Ascend', 'GPU'],
  58. help='device where the code will be implemented. (Default: Ascend)')
  59. parser.add_argument("--distribute", type=str, default="false", help="Run distribute, default is false.")
  60. parser.add_argument("--epoch_size", type=int, default="1", help="Epoch size, default is 1.")
  61. parser.add_argument("--device_id", type=int, default=0, help="Device id, default is 0.")
  62. parser.add_argument("--device_num", type=int, default=1, help="Use device nums, default is 1.")
  63. parser.add_argument("--enable_save_ckpt", type=str, default="true", help="Enable save checkpoint, default is true.")
  64. parser.add_argument("--enable_lossscale", type=str, default="true", help="Use lossscale or not, default is not.")
  65. parser.add_argument("--do_shuffle", type=str, default="true", help="Enable shuffle for dataset, default is true.")
  66. parser.add_argument("--enable_data_sink", type=str, default="true", help="Enable data sink, default is true.")
  67. parser.add_argument("--data_sink_steps", type=int, default="1", help="Sink steps for each epoch, default is 1.")
  68. parser.add_argument("--checkpoint_path", type=str, default="", help="Checkpoint file path")
  69. parser.add_argument("--save_checkpoint_steps", type=int, default=1000, help="Save checkpoint steps, "
  70. "default is 1000.")
  71. parser.add_argument("--train_steps", type=int, default=-1, help="Training Steps, default is -1, "
  72. "meaning run all steps according to epoch number.")
  73. parser.add_argument("--save_checkpoint_num", type=int, default=1, help="Save checkpoint numbers, default is 1.")
  74. parser.add_argument("--data_dir", type=str, default="", help="Data path, it is better to use absolute path")
  75. parser.add_argument("--schema_dir", type=str, default="", help="Schema path, it is better to use absolute path")
  76. args_opt = parser.parse_args()
  77. context.set_context(mode=context.GRAPH_MODE, device_target=args_opt.device_target, device_id=args_opt.device_id)
  78. context.set_context(reserve_class_name_in_scope=False)
  79. ckpt_save_dir = args_opt.checkpoint_path
  80. if args_opt.distribute == "true":
  81. if args_opt.device_target == 'Ascend':
  82. D.init('hccl')
  83. device_num = args_opt.device_num
  84. rank = args_opt.device_id % device_num
  85. else:
  86. D.init('nccl')
  87. device_num = D.get_group_size()
  88. rank = D.get_rank()
  89. ckpt_save_dir = args_opt.checkpoint_path + 'ckpt_' + str(rank) + '/'
  90. context.reset_auto_parallel_context()
  91. context.set_auto_parallel_context(parallel_mode=ParallelMode.DATA_PARALLEL, mirror_mean=True,
  92. device_num=device_num)
  93. from mindspore.parallel._auto_parallel_context import auto_parallel_context
  94. if bert_net_cfg.num_hidden_layers == 12:
  95. if bert_net_cfg.use_relative_positions:
  96. auto_parallel_context().set_all_reduce_fusion_split_indices([29, 58, 87, 116, 145, 174, 203, 217])
  97. else:
  98. auto_parallel_context().set_all_reduce_fusion_split_indices([28, 55, 82, 109, 136, 163, 190, 205])
  99. elif bert_net_cfg.num_hidden_layers == 24:
  100. if bert_net_cfg.use_relative_positions:
  101. auto_parallel_context().set_all_reduce_fusion_split_indices([30, 90, 150, 210, 270, 330, 390, 421])
  102. else:
  103. auto_parallel_context().set_all_reduce_fusion_split_indices([38, 93, 148, 203, 258, 313, 368, 397])
  104. else:
  105. rank = 0
  106. device_num = 1
  107. if args_opt.device_target == 'GPU' and bert_net_cfg.compute_type != mstype.float32:
  108. logger.warning('Gpu only support fp32 temporarily, run with fp32.')
  109. bert_net_cfg.compute_type = mstype.float32
  110. ds, new_repeat_count = create_bert_dataset(args_opt.epoch_size, device_num, rank, args_opt.do_shuffle,
  111. args_opt.enable_data_sink, args_opt.data_sink_steps,
  112. args_opt.data_dir, args_opt.schema_dir)
  113. if args_opt.train_steps > 0:
  114. new_repeat_count = min(new_repeat_count, args_opt.train_steps // args_opt.data_sink_steps)
  115. netwithloss = BertNetworkWithLoss(bert_net_cfg, True)
  116. if cfg.optimizer == 'Lamb':
  117. optimizer = Lamb(netwithloss.trainable_params(), decay_steps=ds.get_dataset_size() * new_repeat_count,
  118. start_learning_rate=cfg.Lamb.start_learning_rate, end_learning_rate=cfg.Lamb.end_learning_rate,
  119. power=cfg.Lamb.power, warmup_steps=cfg.Lamb.warmup_steps, weight_decay=cfg.Lamb.weight_decay,
  120. eps=cfg.Lamb.eps)
  121. elif cfg.optimizer == 'Momentum':
  122. optimizer = Momentum(netwithloss.trainable_params(), learning_rate=cfg.Momentum.learning_rate,
  123. momentum=cfg.Momentum.momentum)
  124. elif cfg.optimizer == 'AdamWeightDecayDynamicLR':
  125. optimizer = AdamWeightDecayDynamicLR(netwithloss.trainable_params(),
  126. decay_steps=ds.get_dataset_size() * new_repeat_count,
  127. learning_rate=cfg.AdamWeightDecayDynamicLR.learning_rate,
  128. end_learning_rate=cfg.AdamWeightDecayDynamicLR.end_learning_rate,
  129. power=cfg.AdamWeightDecayDynamicLR.power,
  130. weight_decay=cfg.AdamWeightDecayDynamicLR.weight_decay,
  131. eps=cfg.AdamWeightDecayDynamicLR.eps,
  132. warmup_steps=cfg.AdamWeightDecayDynamicLR.warmup_steps)
  133. else:
  134. raise ValueError("Don't support optimizer {}, only support [Lamb, Momentum, AdamWeightDecayDynamicLR]".
  135. format(cfg.optimizer))
  136. callback = [TimeMonitor(ds.get_dataset_size()), LossCallBack()]
  137. if args_opt.enable_save_ckpt == "true":
  138. config_ck = CheckpointConfig(save_checkpoint_steps=args_opt.save_checkpoint_steps,
  139. keep_checkpoint_max=args_opt.save_checkpoint_num)
  140. ckpoint_cb = ModelCheckpoint(prefix='checkpoint_bert', directory=ckpt_save_dir, config=config_ck)
  141. callback.append(ckpoint_cb)
  142. if args_opt.checkpoint_path:
  143. param_dict = load_checkpoint(args_opt.checkpoint_path)
  144. load_param_into_net(netwithloss, param_dict)
  145. if args_opt.enable_lossscale == "true":
  146. update_cell = DynamicLossScaleUpdateCell(loss_scale_value=cfg.loss_scale_value,
  147. scale_factor=cfg.scale_factor,
  148. scale_window=cfg.scale_window)
  149. netwithgrads = BertTrainOneStepWithLossScaleCell(netwithloss, optimizer=optimizer,
  150. scale_update_cell=update_cell)
  151. else:
  152. netwithgrads = BertTrainOneStepCell(netwithloss, optimizer=optimizer)
  153. model = Model(netwithgrads)
  154. model.train(new_repeat_count, ds, callbacks=callback, dataset_sink_mode=(args_opt.enable_data_sink == "true"))
  155. if __name__ == '__main__':
  156. numpy.random.seed(0)
  157. run_pretrain()