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.9 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 math
  16. import argparse
  17. import mindspore.nn as nn
  18. from mindspore import context
  19. from mindspore.communication.management import init, get_rank
  20. from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, TimeMonitor
  21. from mindspore.train.model import Model, 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. 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 lr_generator(start_lr, lr_scale, total_iters):
  39. lrs = [start_lr * (lr_scale ** math.floor(cur_iter * 1.0 / (total_iters / 3))) for cur_iter in range(total_iters)]
  40. return lrs
  41. def train():
  42. rank_id = 0
  43. if args.run_distribute:
  44. context.set_auto_parallel_context(device_num=args.device_num, parallel_mode=ParallelMode.DATA_PARALLEL,
  45. gradients_mean=True, parameter_broadcast=True)
  46. init()
  47. rank_id = get_rank()
  48. # dataset/network/criterion/optim
  49. ds = train_dataset_creator()
  50. step_size = ds.get_dataset_size()
  51. print('Create dataset done!')
  52. config.INFERENCE = False
  53. net = ETSNet(config)
  54. net = net.set_train()
  55. param_dict = load_checkpoint(args.pre_trained)
  56. load_param_into_net(net, param_dict)
  57. print('Load Pretrained parameters done!')
  58. criterion = DiceLoss(batch_size=config.TRAIN_BATCH_SIZE)
  59. lrs = lr_generator(start_lr=1e-3, lr_scale=0.1, total_iters=config.TRAIN_TOTAL_ITER)
  60. opt = nn.SGD(params=net.trainable_params(), learning_rate=lrs, momentum=0.99, weight_decay=5e-4)
  61. # warp model
  62. net = WithLossCell(net, criterion)
  63. if args.run_distribute:
  64. net = TrainOneStepCell(net, opt, reduce_flag=True, mean=True, degree=args.device_num)
  65. else:
  66. net = TrainOneStepCell(net, opt)
  67. time_cb = TimeMonitor(data_size=step_size)
  68. loss_cb = LossCallBack(per_print_times=10)
  69. # set and apply parameters of check point config.TRAIN_MODEL_SAVE_PATH
  70. ckpoint_cf = CheckpointConfig(save_checkpoint_steps=1875, keep_checkpoint_max=2)
  71. ckpoint_cb = ModelCheckpoint(prefix="ETSNet", config=ckpoint_cf,
  72. directory="./ckpt_{}".format(rank_id))
  73. model = Model(net)
  74. model.train(config.TRAIN_REPEAT_NUM, ds, dataset_sink_mode=True, callbacks=[time_cb, loss_cb, ckpoint_cb])
  75. if __name__ == '__main__':
  76. train()