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 3.8 kB

5 years ago
5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. import argparse
  16. import mindspore.nn as nn
  17. from mindspore import context
  18. from mindspore.communication.management import init, get_rank
  19. from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, TimeMonitor
  20. from mindspore.train.model import Model
  21. from mindspore.context import ParallelMode
  22. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  23. from mindspore.common import set_seed
  24. from src.dataset import train_dataset_creator
  25. from src.config import config
  26. from src.ETSNET.etsnet import ETSNet
  27. from src.ETSNET.dice_loss import DiceLoss
  28. from src.network_define import WithLossCell, TrainOneStepCell, LossCallBack
  29. from src.lr_schedule import dynamic_lr
  30. parser = argparse.ArgumentParser(description='Hyperparams')
  31. parser.add_argument('--run_distribute', default=False, action='store_true',
  32. help='Run distribute, default is false.')
  33. parser.add_argument('--pre_trained', type=str, default='', help='Pretrain file path.')
  34. parser.add_argument('--device_id', type=int, default=0, help='Device id, default is 0.')
  35. parser.add_argument('--device_num', type=int, default=1, help='Use device nums, default is 1.')
  36. args = parser.parse_args()
  37. set_seed(1)
  38. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", device_id=args.device_id)
  39. def train():
  40. rank_id = 0
  41. if args.run_distribute:
  42. context.set_auto_parallel_context(device_num=args.device_num, parallel_mode=ParallelMode.DATA_PARALLEL,
  43. gradients_mean=True)
  44. init()
  45. rank_id = get_rank()
  46. # dataset/network/criterion/optim
  47. ds = train_dataset_creator(rank_id, args.device_num)
  48. step_size = ds.get_dataset_size()
  49. print('Create dataset done!')
  50. config.INFERENCE = False
  51. net = ETSNet(config)
  52. net = net.set_train()
  53. param_dict = load_checkpoint(args.pre_trained)
  54. load_param_into_net(net, param_dict)
  55. print('Load Pretrained parameters done!')
  56. criterion = DiceLoss(batch_size=config.TRAIN_BATCH_SIZE)
  57. lrs = dynamic_lr(config.BASE_LR, config.TRAIN_TOTAL_ITER, config.WARMUP_STEP, config.WARMUP_RATIO)
  58. opt = nn.SGD(params=net.trainable_params(), learning_rate=lrs, momentum=0.99, weight_decay=5e-4)
  59. # warp model
  60. net = WithLossCell(net, criterion)
  61. if args.run_distribute:
  62. net = TrainOneStepCell(net, opt, reduce_flag=True, mean=True, degree=args.device_num)
  63. else:
  64. net = TrainOneStepCell(net, opt)
  65. time_cb = TimeMonitor(data_size=step_size)
  66. loss_cb = LossCallBack(per_print_times=10)
  67. # set and apply parameters of check point config.TRAIN_MODEL_SAVE_PATH
  68. ckpoint_cf = CheckpointConfig(save_checkpoint_steps=1875, keep_checkpoint_max=2)
  69. ckpoint_cb = ModelCheckpoint(prefix="ETSNet", config=ckpoint_cf,
  70. directory="./ckpt_{}".format(rank_id))
  71. model = Model(net)
  72. model.train(config.TRAIN_REPEAT_NUM, ds, dataset_sink_mode=True, callbacks=[time_cb, loss_cb, ckpoint_cb])
  73. if __name__ == '__main__':
  74. train()