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 12 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
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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.context import ParallelMode
  27. from mindspore.nn.wrap.loss_scale import DynamicLossScaleUpdateCell
  28. from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, TimeMonitor
  29. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  30. from mindspore.nn.optim import Lamb, Momentum, AdamWeightDecay
  31. from mindspore import log as logger
  32. from src import BertNetworkWithLoss, BertTrainOneStepCell, BertTrainOneStepWithLossScaleCell, \
  33. BertTrainAccumulateStepsWithLossScaleCell
  34. from src.dataset import create_bert_dataset
  35. from src.config import cfg, bert_net_cfg
  36. from src.utils import LossCallBack, BertLearningRate
  37. _current_dir = os.path.dirname(os.path.realpath(__file__))
  38. def run_pretrain():
  39. """pre-train bert_clue"""
  40. parser = argparse.ArgumentParser(description='bert pre_training')
  41. parser.add_argument('--device_target', type=str, default='Ascend', choices=['Ascend', 'GPU'],
  42. help='device where the code will be implemented. (Default: Ascend)')
  43. parser.add_argument("--distribute", type=str, default="false", choices=["true", "false"],
  44. help="Run distribute, default is false.")
  45. parser.add_argument("--epoch_size", type=int, default="1", help="Epoch size, default is 1.")
  46. parser.add_argument("--device_id", type=int, default=0, help="Device id, default is 0.")
  47. parser.add_argument("--device_num", type=int, default=1, help="Use device nums, default is 1.")
  48. parser.add_argument("--enable_save_ckpt", type=str, default="true", choices=["true", "false"],
  49. help="Enable save checkpoint, default is true.")
  50. parser.add_argument("--enable_lossscale", type=str, default="true", choices=["true", "false"],
  51. help="Use lossscale or not, default is not.")
  52. parser.add_argument("--do_shuffle", type=str, default="true", choices=["true", "false"],
  53. help="Enable shuffle for dataset, default is true.")
  54. parser.add_argument("--enable_data_sink", type=str, default="true", choices=["true", "false"],
  55. help="Enable data sink, default is true.")
  56. parser.add_argument("--data_sink_steps", type=int, default="1", help="Sink steps for each epoch, default is 1.")
  57. parser.add_argument("--accumulation_steps", type=int, default="1",
  58. help="Accumulating gradients N times before weight update, default is 1.")
  59. parser.add_argument("--save_checkpoint_path", type=str, default="", help="Save checkpoint path")
  60. parser.add_argument("--load_checkpoint_path", type=str, default="", help="Load checkpoint file path")
  61. parser.add_argument("--save_checkpoint_steps", type=int, default=1000, help="Save checkpoint steps, "
  62. "default is 1000.")
  63. parser.add_argument("--train_steps", type=int, default=-1, help="Training Steps, default is -1, "
  64. "meaning run all steps according to epoch number.")
  65. parser.add_argument("--save_checkpoint_num", type=int, default=1, help="Save checkpoint numbers, default is 1.")
  66. parser.add_argument("--data_dir", type=str, default="", help="Data path, it is better to use absolute path")
  67. parser.add_argument("--schema_dir", type=str, default="", help="Schema path, it is better to use absolute path")
  68. args_opt = parser.parse_args()
  69. context.set_context(mode=context.GRAPH_MODE, device_target=args_opt.device_target, device_id=args_opt.device_id)
  70. context.set_context(reserve_class_name_in_scope=False)
  71. ckpt_save_dir = args_opt.save_checkpoint_path
  72. if args_opt.distribute == "true":
  73. if args_opt.device_target == 'Ascend':
  74. D.init()
  75. device_num = args_opt.device_num
  76. rank = args_opt.device_id % device_num
  77. else:
  78. D.init()
  79. device_num = D.get_group_size()
  80. rank = D.get_rank()
  81. ckpt_save_dir = args_opt.save_checkpoint_path + 'ckpt_' + str(rank) + '/'
  82. context.reset_auto_parallel_context()
  83. context.set_auto_parallel_context(parallel_mode=ParallelMode.DATA_PARALLEL, mirror_mean=True,
  84. device_num=device_num)
  85. from mindspore.parallel._auto_parallel_context import auto_parallel_context
  86. if bert_net_cfg.num_hidden_layers == 12:
  87. if bert_net_cfg.use_relative_positions:
  88. auto_parallel_context().set_all_reduce_fusion_split_indices([29, 58, 87, 116, 145, 174, 203, 217])
  89. else:
  90. auto_parallel_context().set_all_reduce_fusion_split_indices([28, 55, 82, 109, 136, 163, 190, 205])
  91. elif bert_net_cfg.num_hidden_layers == 24:
  92. if bert_net_cfg.use_relative_positions:
  93. auto_parallel_context().set_all_reduce_fusion_split_indices([30, 90, 150, 210, 270, 330, 390, 421])
  94. else:
  95. auto_parallel_context().set_all_reduce_fusion_split_indices([38, 93, 148, 203, 258, 313, 368, 397])
  96. else:
  97. rank = 0
  98. device_num = 1
  99. if args_opt.device_target == 'GPU' and bert_net_cfg.compute_type != mstype.float32:
  100. logger.warning('Gpu only support fp32 temporarily, run with fp32.')
  101. bert_net_cfg.compute_type = mstype.float32
  102. if args_opt.accumulation_steps > 1:
  103. logger.info("accumulation steps: {}".format(args_opt.accumulation_steps))
  104. logger.info("global batch size: {}".format(bert_net_cfg.batch_size * args_opt.accumulation_steps))
  105. if args_opt.enable_data_sink == "true":
  106. args_opt.data_sink_steps *= args_opt.accumulation_steps
  107. logger.info("data sink steps: {}".format(args_opt.data_sink_steps))
  108. if args_opt.enable_save_ckpt == "true":
  109. args_opt.save_checkpoint_steps *= args_opt.accumulation_steps
  110. logger.info("save checkpoint steps: {}".format(args_opt.save_checkpoint_steps))
  111. ds = create_bert_dataset(device_num, rank, args_opt.do_shuffle, args_opt.data_dir, args_opt.schema_dir)
  112. net_with_loss = BertNetworkWithLoss(bert_net_cfg, True)
  113. new_repeat_count = args_opt.epoch_size * ds.get_dataset_size() // args_opt.data_sink_steps
  114. if args_opt.train_steps > 0:
  115. train_steps = args_opt.train_steps * args_opt.accumulation_steps
  116. new_repeat_count = min(new_repeat_count, train_steps // args_opt.data_sink_steps)
  117. else:
  118. args_opt.train_steps = args_opt.epoch_size * ds.get_dataset_size() // args_opt.accumulation_steps
  119. logger.info("train steps: {}".format(args_opt.train_steps))
  120. if cfg.optimizer == 'Lamb':
  121. lr_schedule = BertLearningRate(learning_rate=cfg.Lamb.learning_rate,
  122. end_learning_rate=cfg.Lamb.end_learning_rate,
  123. warmup_steps=cfg.Lamb.warmup_steps,
  124. decay_steps=args_opt.train_steps,
  125. power=cfg.Lamb.power)
  126. params = net_with_loss.trainable_params()
  127. decay_params = list(filter(cfg.Lamb.decay_filter, params))
  128. other_params = list(filter(lambda x: not cfg.Lamb.decay_filter(x), params))
  129. group_params = [{'params': decay_params, 'weight_decay': cfg.Lamb.weight_decay},
  130. {'params': other_params},
  131. {'order_params': params}]
  132. optimizer = Lamb(group_params, learning_rate=lr_schedule, eps=cfg.Lamb.eps)
  133. elif cfg.optimizer == 'Momentum':
  134. optimizer = Momentum(net_with_loss.trainable_params(), learning_rate=cfg.Momentum.learning_rate,
  135. momentum=cfg.Momentum.momentum)
  136. elif cfg.optimizer == 'AdamWeightDecay':
  137. lr_schedule = BertLearningRate(learning_rate=cfg.AdamWeightDecay.learning_rate,
  138. end_learning_rate=cfg.AdamWeightDecay.end_learning_rate,
  139. warmup_steps=cfg.AdamWeightDecay.warmup_steps,
  140. decay_steps=args_opt.train_steps,
  141. power=cfg.AdamWeightDecay.power)
  142. params = net_with_loss.trainable_params()
  143. decay_params = list(filter(cfg.AdamWeightDecay.decay_filter, params))
  144. other_params = list(filter(lambda x: not cfg.AdamWeightDecay.decay_filter(x), params))
  145. group_params = [{'params': decay_params, 'weight_decay': cfg.AdamWeightDecay.weight_decay},
  146. {'params': other_params, 'weight_decay': 0.0},
  147. {'order_params': params}]
  148. optimizer = AdamWeightDecay(group_params, learning_rate=lr_schedule, eps=cfg.AdamWeightDecay.eps)
  149. else:
  150. raise ValueError("Don't support optimizer {}, only support [Lamb, Momentum, AdamWeightDecay]".
  151. format(cfg.optimizer))
  152. callback = [TimeMonitor(args_opt.data_sink_steps), LossCallBack(ds.get_dataset_size())]
  153. if args_opt.enable_save_ckpt == "true" and args_opt.device_id % min(8, device_num) == 0:
  154. config_ck = CheckpointConfig(save_checkpoint_steps=args_opt.save_checkpoint_steps,
  155. keep_checkpoint_max=args_opt.save_checkpoint_num)
  156. ckpoint_cb = ModelCheckpoint(prefix='checkpoint_bert',
  157. directory=None if ckpt_save_dir == "" else ckpt_save_dir, config=config_ck)
  158. callback.append(ckpoint_cb)
  159. if args_opt.load_checkpoint_path:
  160. param_dict = load_checkpoint(args_opt.load_checkpoint_path)
  161. load_param_into_net(net_with_loss, param_dict)
  162. if args_opt.enable_lossscale == "true":
  163. update_cell = DynamicLossScaleUpdateCell(loss_scale_value=cfg.loss_scale_value,
  164. scale_factor=cfg.scale_factor,
  165. scale_window=cfg.scale_window)
  166. if args_opt.accumulation_steps <= 1:
  167. net_with_grads = BertTrainOneStepWithLossScaleCell(net_with_loss, optimizer=optimizer,
  168. scale_update_cell=update_cell,
  169. enable_global_norm=cfg.enable_global_norm)
  170. else:
  171. accumulation_steps = args_opt.accumulation_steps
  172. net_with_grads = BertTrainAccumulateStepsWithLossScaleCell(net_with_loss, optimizer=optimizer,
  173. scale_update_cell=update_cell,
  174. accumulation_steps=accumulation_steps,
  175. enable_global_norm=cfg.enable_global_norm)
  176. else:
  177. net_with_grads = BertTrainOneStepCell(net_with_loss, optimizer=optimizer)
  178. model = Model(net_with_grads)
  179. model.train(new_repeat_count, ds, callbacks=callback,
  180. dataset_sink_mode=(args_opt.enable_data_sink == "true"), sink_size=args_opt.data_sink_steps)
  181. if __name__ == '__main__':
  182. numpy.random.seed(0)
  183. run_pretrain()