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