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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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 mobilenetV2 on ImageNet"""
  16. import os
  17. import argparse
  18. import random
  19. import numpy as np
  20. from mindspore import context
  21. from mindspore import Tensor
  22. from mindspore import nn
  23. from mindspore.train.model import Model, ParallelMode
  24. from mindspore.train.callback import ModelCheckpoint, CheckpointConfig
  25. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  26. from mindspore.communication.management import init
  27. from mindspore.train.quant import quant
  28. import mindspore.dataset.engine as de
  29. from src.dataset import create_dataset
  30. from src.lr_generator import get_lr
  31. from src.utils import Monitor, CrossEntropyWithLabelSmooth
  32. from src.config import config_ascend, config_ascend_quant
  33. from src.mobilenetV2 import mobilenetV2
  34. random.seed(1)
  35. np.random.seed(1)
  36. de.config.set_seed(1)
  37. parser = argparse.ArgumentParser(description='Image classification')
  38. parser.add_argument('--dataset_path', type=str, default=None, help='Dataset path')
  39. parser.add_argument('--pre_trained', type=str, default=None, help='Pertained checkpoint path')
  40. parser.add_argument('--device_target', type=str, default=None, help='Run device target')
  41. parser.add_argument('--quantization_aware', type=bool, default=False, help='Use quantization aware training')
  42. args_opt = parser.parse_args()
  43. if args_opt.device_target == "Ascend":
  44. device_id = int(os.getenv('DEVICE_ID'))
  45. rank_id = int(os.getenv('RANK_ID'))
  46. rank_size = int(os.getenv('RANK_SIZE'))
  47. run_distribute = rank_size > 1
  48. device_id = int(os.getenv('DEVICE_ID'))
  49. context.set_context(mode=context.GRAPH_MODE,
  50. device_target="Ascend",
  51. device_id=device_id, save_graphs=False)
  52. else:
  53. raise ValueError("Unsupported device target.")
  54. if __name__ == '__main__':
  55. # train on ascend
  56. config = config_ascend_quant if args_opt.quantization_aware else config_ascend
  57. print("training args: {}".format(args_opt))
  58. print("training configure: {}".format(config))
  59. print("parallel args: rank_id {}, device_id {}, rank_size {}".format(rank_id, device_id, rank_size))
  60. epoch_size = config.epoch_size
  61. # distribute init
  62. if run_distribute:
  63. context.set_auto_parallel_context(device_num=rank_size,
  64. parallel_mode=ParallelMode.DATA_PARALLEL,
  65. parameter_broadcast=True,
  66. mirror_mean=True)
  67. init()
  68. # define network
  69. network = mobilenetV2(num_classes=config.num_classes)
  70. # define loss
  71. if config.label_smooth > 0:
  72. loss = CrossEntropyWithLabelSmooth(smooth_factor=config.label_smooth, num_classes=config.num_classes)
  73. else:
  74. loss = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True, reduction='mean')
  75. # define dataset
  76. dataset = create_dataset(dataset_path=args_opt.dataset_path,
  77. do_train=True,
  78. config=config,
  79. device_target=args_opt.device_target,
  80. repeat_num=epoch_size,
  81. batch_size=config.batch_size)
  82. step_size = dataset.get_dataset_size()
  83. # load pre trained ckpt
  84. if args_opt.pre_trained:
  85. param_dict = load_checkpoint(args_opt.pre_trained)
  86. load_param_into_net(network, param_dict)
  87. # convert fusion network to quantization aware network
  88. if config.quantization_aware:
  89. network = quant.convert_quant_network(network,
  90. bn_fold=True,
  91. per_channel=[True, False],
  92. symmetric=[True, False])
  93. # get learning rate
  94. lr = Tensor(get_lr(global_step=config.start_epoch * step_size,
  95. lr_init=0,
  96. lr_end=0,
  97. lr_max=config.lr,
  98. warmup_epochs=config.warmup_epochs,
  99. total_epochs=epoch_size + config.start_epoch,
  100. steps_per_epoch=step_size))
  101. # define optimization
  102. opt = nn.Momentum(filter(lambda x: x.requires_grad, network.get_parameters()), lr, config.momentum,
  103. config.weight_decay)
  104. # define model
  105. model = Model(network, loss_fn=loss, optimizer=opt)
  106. print("============== Starting Training ==============")
  107. callback = None
  108. if rank_id == 0:
  109. callback = [Monitor(lr_init=lr.asnumpy())]
  110. if config.save_checkpoint:
  111. config_ck = CheckpointConfig(save_checkpoint_steps=config.save_checkpoint_epochs * step_size,
  112. keep_checkpoint_max=config.keep_checkpoint_max)
  113. ckpt_cb = ModelCheckpoint(prefix="mobilenetV2",
  114. directory=config.save_checkpoint_path,
  115. config=config_ck)
  116. callback += [ckpt_cb]
  117. model.train(epoch_size, dataset, callbacks=callback)
  118. print("============== End Training ==============")