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.

train.py 6.0 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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. GPT train script
  17. """
  18. import os
  19. import argparse
  20. from mindspore import context
  21. from mindspore.train.model import Model
  22. import mindspore.communication.management as D
  23. from mindspore.context import ParallelMode
  24. import mindspore.nn as nn
  25. from mindspore.train.callback import TimeMonitor, LossMonitor, ModelCheckpoint, CheckpointConfig
  26. from mindspore.nn.wrap.loss_scale import DynamicLossScaleUpdateCell
  27. import mindspore.common.dtype as mstype
  28. from mindspore.common import set_seed
  29. from src.dataset import create_dataset
  30. from src.gpt import GPT, GPTWithLoss, CrossEntropyLoss
  31. from src.gpt_wrapcell import GPTTrainOneStepWithLossScaleCell
  32. from src.utils import GPTConfig, LearningRate
  33. def run_train():
  34. """train function for GPT"""
  35. parser = argparse.ArgumentParser(description="GPT training")
  36. parser.add_argument('--device_id', type=int, default=0, help="Device id, default is 0.")
  37. parser.add_argument("--device_num", type=int, default=1, help="Use device nums, default is 1.")
  38. parser.add_argument("--distribute", type=str, default="false", choices=["true", "false"],
  39. help="Run distribute, default is false.")
  40. parser.add_argument("--optimizer", type=str, default="adam", choices=["adam", "lamb"],
  41. help="select which optimizer to be used, default adam")
  42. parser.add_argument("--epoch_size", type=int, default=10, help="Epoch size, default is 10.")
  43. parser.add_argument("--warmup_step", type=int, default=10000, help="Warmup step, default is 10000.")
  44. parser.add_argument("--data_path", type=str, default="", help="Data path of your MindRecord files.")
  45. parser.add_argument("--start_lr", type=float, default="5e-5", help="Start learning rate, default is 5e-5.")
  46. parser.add_argument("--end_lr", type=float, default="1e-10", help="End learning rate, default is 1e-10.")
  47. parser.add_argument("--sink_size", type=int, default=100, help="Sink size for every iteration, default is 100")
  48. args_opt = parser.parse_args()
  49. device_id = int(os.getenv("DEVICE_ID"))
  50. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", device_id=device_id)
  51. if args_opt.distribute == "true":
  52. D.init()
  53. device_num = args_opt.device_num
  54. rank = device_id % device_num
  55. print("device_id is {}, rank_id is {}".format(device_id, rank))
  56. context.reset_auto_parallel_context()
  57. context.set_auto_parallel_context(parallel_mode=ParallelMode.DATA_PARALLEL, gradients_mean=True,
  58. device_num=device_num)
  59. else:
  60. rank = 0
  61. device_num = 1
  62. config = GPTConfig(batch_size=4,
  63. seq_length=1024,
  64. vocab_size=50257,
  65. embedding_size=1024,
  66. num_layers=24,
  67. num_heads=16,
  68. expand_ratio=4,
  69. post_layernorm_residual=False,
  70. dropout_rate=0.1,
  71. compute_dtype=mstype.float16,
  72. use_past=False)
  73. gpt = GPT(config)
  74. loss = CrossEntropyLoss(config)
  75. gpt_with_loss = GPTWithLoss(gpt, loss)
  76. ds = create_dataset(config.batch_size, data_path=args_opt.data_path, device_num=device_num, rank=rank)
  77. epoch_num = args_opt.epoch_size
  78. step_per_epoch = ds.get_dataset_size()
  79. lr = LearningRate(learning_rate=args_opt.start_lr,
  80. end_learning_rate=args_opt.end_lr,
  81. warmup_steps=args_opt.warmup_step,
  82. decay_steps=epoch_num*step_per_epoch)
  83. decay_filter = lambda x: 'layernorm' not in x.name.lower() and "bias" not in x.name.lower()
  84. params = gpt.trainable_params()
  85. decay_params = list(filter(decay_filter, params))
  86. other_params = list(filter(lambda x: not decay_filter(x), params))
  87. group_params = [{'params': decay_params, 'weight_decay': 1e-2},
  88. {'params': other_params, 'weight_decay': 0.0},
  89. {'order_params': params}]
  90. if args_opt.optimizer == "lamb":
  91. optimizer = nn.Lamb(group_params, learning_rate=lr)
  92. else:
  93. optimizer = nn.AdamWeightDecay(group_params, learning_rate=lr)
  94. callback_size = args_opt.sink_size
  95. actual_epoch_num = int(epoch_num * step_per_epoch/callback_size)
  96. callback = [TimeMonitor(callback_size), LossMonitor(callback_size)]
  97. config_ck = CheckpointConfig(save_checkpoint_steps=step_per_epoch, keep_checkpoint_max=1)
  98. ckpoint_cb = ModelCheckpoint(prefix="GPT2", config=config_ck)
  99. callback.append(ckpoint_cb)
  100. update_cell = DynamicLossScaleUpdateCell(loss_scale_value=1024,
  101. scale_factor=2,
  102. scale_window=1000)
  103. gpt_with_grads = GPTTrainOneStepWithLossScaleCell(gpt_with_loss, optimizer=optimizer,
  104. scale_update_cell=update_cell)
  105. model = Model(gpt_with_grads)
  106. model.train(actual_epoch_num, ds, callbacks=callback, sink_size=callback_size)
  107. if __name__ == "__main__":
  108. set_seed(12315)
  109. run_train()