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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. """train_imagenet."""
  16. import os
  17. import argparse
  18. import random
  19. import numpy as np
  20. from dataset import create_dataset
  21. from lr_generator import warmup_cosine_annealing_lr
  22. from config import config
  23. from mindspore import context
  24. from mindspore import Tensor
  25. from mindspore.model_zoo.resnet import resnet101
  26. from mindspore.parallel._auto_parallel_context import auto_parallel_context
  27. from mindspore.nn.optim.momentum import Momentum
  28. from mindspore.train.model import Model, ParallelMode
  29. from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor, TimeMonitor
  30. from mindspore.train.loss_scale_manager import FixedLossScaleManager
  31. import mindspore.dataset.engine as de
  32. from mindspore.communication.management import init
  33. import mindspore.nn as nn
  34. import mindspore.common.initializer as weight_init
  35. from crossentropy import CrossEntropy
  36. random.seed(1)
  37. np.random.seed(1)
  38. de.config.set_seed(1)
  39. parser = argparse.ArgumentParser(description='Image classification')
  40. parser.add_argument('--run_distribute', type=bool, default=False, help='Run distribute')
  41. parser.add_argument('--device_num', type=int, default=1, help='Device num.')
  42. parser.add_argument('--do_train', type=bool, default=True, help='Do train or not.')
  43. parser.add_argument('--do_eval', type=bool, default=False, help='Do eval or not.')
  44. parser.add_argument('--dataset_path', type=str, default=None, help='Dataset path')
  45. args_opt = parser.parse_args()
  46. device_id = int(os.getenv('DEVICE_ID'))
  47. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", save_graphs=False, device_id=device_id)
  48. context.set_context(enable_task_sink=True)
  49. context.set_context(enable_loop_sink=True)
  50. context.set_context(enable_mem_reuse=True)
  51. if __name__ == '__main__':
  52. if not args_opt.do_eval and args_opt.run_distribute:
  53. context.set_auto_parallel_context(device_num=args_opt.device_num, parallel_mode=ParallelMode.DATA_PARALLEL,
  54. mirror_mean=True, parameter_broadcast=True)
  55. auto_parallel_context().set_all_reduce_fusion_split_indices([180, 313])
  56. init()
  57. epoch_size = config.epoch_size
  58. net = resnet101(class_num=config.class_num)
  59. # weight init
  60. for _, cell in net.cells_and_names():
  61. if isinstance(cell, nn.Conv2d):
  62. cell.weight.default_input = weight_init.initializer(weight_init.XavierUniform(),
  63. cell.weight.default_input.shape(),
  64. cell.weight.default_input.dtype())
  65. if isinstance(cell, nn.Dense):
  66. cell.weight.default_input = weight_init.initializer(weight_init.TruncatedNormal(),
  67. cell.weight.default_input.shape(),
  68. cell.weight.default_input.dtype())
  69. if not config.label_smooth:
  70. config.label_smooth_factor = 0.0
  71. loss = CrossEntropy(smooth_factor=config.label_smooth_factor, num_classes=config.class_num)
  72. if args_opt.do_train:
  73. dataset = create_dataset(dataset_path=args_opt.dataset_path, do_train=True,
  74. repeat_num=epoch_size, batch_size=config.batch_size)
  75. step_size = dataset.get_dataset_size()
  76. loss_scale = FixedLossScaleManager(config.loss_scale, drop_overflow_update=False)
  77. # learning rate strategy with cosine
  78. lr = Tensor(warmup_cosine_annealing_lr(config.lr, step_size, config.warmup_epochs, config.epoch_size))
  79. opt = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), lr, config.momentum,
  80. config.weight_decay, config.loss_scale)
  81. model = Model(net, loss_fn=loss, optimizer=opt, amp_level='O2', keep_batchnorm_fp32=False,
  82. loss_scale_manager=loss_scale, metrics={'acc'})
  83. time_cb = TimeMonitor(data_size=step_size)
  84. loss_cb = LossMonitor()
  85. cb = [time_cb, loss_cb]
  86. if config.save_checkpoint:
  87. config_ck = CheckpointConfig(save_checkpoint_steps=config.save_checkpoint_epochs*step_size,
  88. keep_checkpoint_max=config.keep_checkpoint_max)
  89. ckpt_cb = ModelCheckpoint(prefix="resnet", directory=config.save_checkpoint_path, config=config_ck)
  90. cb += [ckpt_cb]
  91. model.train(epoch_size, dataset, callbacks=cb)