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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. from dataset import create_dataset
  19. from lr_generator import get_lr
  20. from config import config
  21. from mindspore import context
  22. from mindspore import Tensor
  23. from mindspore.model_zoo.resnet import resnet50
  24. from mindspore.parallel._auto_parallel_context import auto_parallel_context
  25. from mindspore.nn.optim.momentum import Momentum
  26. from mindspore.nn.loss import SoftmaxCrossEntropyWithLogits
  27. from mindspore.train.model import Model, ParallelMode
  28. from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor, TimeMonitor
  29. from mindspore.train.loss_scale_manager import FixedLossScaleManager
  30. from mindspore.communication.management import init
  31. parser = argparse.ArgumentParser(description='Image classification')
  32. parser.add_argument('--run_distribute', type=bool, default=False, help='Run distribute')
  33. parser.add_argument('--device_num', type=int, default=1, help='Device num.')
  34. parser.add_argument('--do_train', type=bool, default=True, help='Do train or not.')
  35. parser.add_argument('--do_eval', type=bool, default=False, help='Do eval or not.')
  36. parser.add_argument('--dataset_path', type=str, default=None, help='Dataset path')
  37. args_opt = parser.parse_args()
  38. device_id = int(os.getenv('DEVICE_ID'))
  39. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", save_graphs=False, device_id=device_id,
  40. enable_auto_mixed_precision=True)
  41. if __name__ == '__main__':
  42. if not args_opt.do_eval and args_opt.run_distribute:
  43. context.set_auto_parallel_context(device_num=args_opt.device_num, parallel_mode=ParallelMode.DATA_PARALLEL,
  44. mirror_mean=True)
  45. auto_parallel_context().set_all_reduce_fusion_split_indices([107, 160])
  46. init()
  47. epoch_size = config.epoch_size
  48. net = resnet50(class_num=config.class_num)
  49. loss = SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
  50. if args_opt.do_train:
  51. dataset = create_dataset(dataset_path=args_opt.dataset_path, do_train=True,
  52. repeat_num=epoch_size, batch_size=config.batch_size)
  53. step_size = dataset.get_dataset_size()
  54. loss_scale = FixedLossScaleManager(config.loss_scale, drop_overflow_update=False)
  55. lr = Tensor(get_lr(global_step=0, lr_init=config.lr_init, lr_end=config.lr_end, lr_max=config.lr_max,
  56. warmup_epochs=config.warmup_epochs, total_epochs=epoch_size, steps_per_epoch=step_size,
  57. lr_decay_mode='poly'))
  58. opt = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), lr, config.momentum,
  59. config.weight_decay, config.loss_scale)
  60. model = Model(net, loss_fn=loss, optimizer=opt, loss_scale_manager=loss_scale, metrics={'acc'}, amp_level="O2",
  61. keep_batchnorm_fp32=False)
  62. time_cb = TimeMonitor(data_size=step_size)
  63. loss_cb = LossMonitor()
  64. cb = [time_cb, loss_cb]
  65. if config.save_checkpoint:
  66. config_ck = CheckpointConfig(save_checkpoint_steps=config.save_checkpoint_steps,
  67. keep_checkpoint_max=config.keep_checkpoint_max)
  68. ckpt_cb = ModelCheckpoint(prefix="resnet", directory=config.save_checkpoint_path, config=config_ck)
  69. cb += [ckpt_cb]
  70. model.train(epoch_size, dataset, callbacks=cb)