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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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. from mindspore import context
  19. from mindspore import Tensor
  20. from mindspore import nn
  21. from mindspore.train.model import Model
  22. from mindspore.context import ParallelMode
  23. from mindspore.train.loss_scale_manager import FixedLossScaleManager
  24. from mindspore.train.callback import ModelCheckpoint, CheckpointConfig
  25. from mindspore.train.serialization import load_checkpoint
  26. from mindspore.communication.management import init, get_group_size, get_rank
  27. from mindspore.train.quant import quant
  28. from mindspore.train.quant.quant_utils import load_nonquant_param_into_quant_net
  29. from mindspore.common import set_seed
  30. from src.dataset import create_dataset
  31. from src.lr_generator import get_lr
  32. from src.utils import Monitor, CrossEntropyWithLabelSmooth
  33. from src.config import config_ascend_quant, config_gpu_quant
  34. from src.mobilenetV2 import mobilenetV2
  35. set_seed(1)
  36. parser = argparse.ArgumentParser(description='Image classification')
  37. parser.add_argument('--dataset_path', type=str, default=None, help='Dataset path')
  38. parser.add_argument('--pre_trained', type=str, default=None, help='Pertained checkpoint path')
  39. parser.add_argument('--device_target', type=str, default=None, help='Run device target')
  40. args_opt = parser.parse_args()
  41. if args_opt.device_target == "Ascend":
  42. device_id = int(os.getenv('DEVICE_ID'))
  43. rank_id = int(os.getenv('RANK_ID'))
  44. rank_size = int(os.getenv('RANK_SIZE'))
  45. run_distribute = rank_size > 1
  46. device_id = int(os.getenv('DEVICE_ID'))
  47. context.set_context(mode=context.GRAPH_MODE,
  48. device_target="Ascend",
  49. device_id=device_id, save_graphs=False)
  50. elif args_opt.device_target == "GPU":
  51. init()
  52. context.set_auto_parallel_context(device_num=get_group_size(),
  53. parallel_mode=ParallelMode.DATA_PARALLEL,
  54. gradients_mean=True)
  55. context.set_context(mode=context.GRAPH_MODE,
  56. device_target="GPU",
  57. save_graphs=False)
  58. else:
  59. raise ValueError("Unsupported device target.")
  60. def train_on_ascend():
  61. config = config_ascend_quant
  62. print("training args: {}".format(args_opt))
  63. print("training configure: {}".format(config))
  64. print("parallel args: rank_id {}, device_id {}, rank_size {}".format(rank_id, device_id, rank_size))
  65. epoch_size = config.epoch_size
  66. # distribute init
  67. if run_distribute:
  68. context.set_auto_parallel_context(device_num=rank_size,
  69. parallel_mode=ParallelMode.DATA_PARALLEL,
  70. parameter_broadcast=True,
  71. gradients_mean=True)
  72. init()
  73. # define network
  74. network = mobilenetV2(num_classes=config.num_classes)
  75. # define loss
  76. if config.label_smooth > 0:
  77. loss = CrossEntropyWithLabelSmooth(smooth_factor=config.label_smooth, num_classes=config.num_classes)
  78. else:
  79. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
  80. # define dataset
  81. dataset = create_dataset(dataset_path=args_opt.dataset_path,
  82. do_train=True,
  83. config=config,
  84. device_target=args_opt.device_target,
  85. repeat_num=1,
  86. batch_size=config.batch_size)
  87. step_size = dataset.get_dataset_size()
  88. # load pre trained ckpt
  89. if args_opt.pre_trained:
  90. param_dict = load_checkpoint(args_opt.pre_trained)
  91. load_nonquant_param_into_quant_net(network, param_dict)
  92. # convert fusion network to quantization aware network
  93. network = quant.convert_quant_network(network,
  94. bn_fold=True,
  95. per_channel=[True, False],
  96. symmetric=[True, False])
  97. # get learning rate
  98. lr = Tensor(get_lr(global_step=config.start_epoch * step_size,
  99. lr_init=0,
  100. lr_end=0,
  101. lr_max=config.lr,
  102. warmup_epochs=config.warmup_epochs,
  103. total_epochs=epoch_size + config.start_epoch,
  104. steps_per_epoch=step_size))
  105. # define optimization
  106. opt = nn.Momentum(filter(lambda x: x.requires_grad, network.get_parameters()), lr, config.momentum,
  107. config.weight_decay)
  108. # define model
  109. model = Model(network, loss_fn=loss, optimizer=opt)
  110. print("============== Starting Training ==============")
  111. callback = None
  112. if rank_id == 0:
  113. callback = [Monitor(lr_init=lr.asnumpy())]
  114. if config.save_checkpoint:
  115. config_ck = CheckpointConfig(save_checkpoint_steps=config.save_checkpoint_epochs * step_size,
  116. keep_checkpoint_max=config.keep_checkpoint_max)
  117. ckpt_cb = ModelCheckpoint(prefix="mobilenetV2",
  118. directory=config.save_checkpoint_path,
  119. config=config_ck)
  120. callback += [ckpt_cb]
  121. model.train(epoch_size, dataset, callbacks=callback)
  122. print("============== End Training ==============")
  123. def train_on_gpu():
  124. config = config_gpu_quant
  125. print("training args: {}".format(args_opt))
  126. print("training configure: {}".format(config))
  127. # define network
  128. network = mobilenetV2(num_classes=config.num_classes)
  129. # define loss
  130. if config.label_smooth > 0:
  131. loss = CrossEntropyWithLabelSmooth(smooth_factor=config.label_smooth,
  132. num_classes=config.num_classes)
  133. else:
  134. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
  135. # define dataset
  136. epoch_size = config.epoch_size
  137. dataset = create_dataset(dataset_path=args_opt.dataset_path,
  138. do_train=True,
  139. config=config,
  140. device_target=args_opt.device_target,
  141. repeat_num=1,
  142. batch_size=config.batch_size)
  143. step_size = dataset.get_dataset_size()
  144. # resume
  145. if args_opt.pre_trained:
  146. param_dict = load_checkpoint(args_opt.pre_trained)
  147. load_nonquant_param_into_quant_net(network, param_dict)
  148. # convert fusion network to quantization aware network
  149. network = quant.convert_quant_network(network,
  150. bn_fold=True,
  151. per_channel=[True, False],
  152. symmetric=[True, False],
  153. freeze_bn=1000000,
  154. quant_delay=step_size * 2)
  155. # get learning rate
  156. loss_scale = FixedLossScaleManager(config.loss_scale, drop_overflow_update=False)
  157. lr = Tensor(get_lr(global_step=config.start_epoch * step_size,
  158. lr_init=0,
  159. lr_end=0,
  160. lr_max=config.lr,
  161. warmup_epochs=config.warmup_epochs,
  162. total_epochs=epoch_size + config.start_epoch,
  163. steps_per_epoch=step_size))
  164. # define optimization
  165. opt = nn.Momentum(filter(lambda x: x.requires_grad, network.get_parameters()), lr, config.momentum,
  166. config.weight_decay, config.loss_scale)
  167. # define model
  168. model = Model(network, loss_fn=loss, optimizer=opt, loss_scale_manager=loss_scale)
  169. print("============== Starting Training ==============")
  170. callback = [Monitor(lr_init=lr.asnumpy())]
  171. ckpt_save_dir = config.save_checkpoint_path + "ckpt_" + str(get_rank()) + "/"
  172. if config.save_checkpoint:
  173. config_ck = CheckpointConfig(save_checkpoint_steps=config.save_checkpoint_epochs * step_size,
  174. keep_checkpoint_max=config.keep_checkpoint_max)
  175. ckpt_cb = ModelCheckpoint(prefix="mobilenetV2", directory=ckpt_save_dir, config=config_ck)
  176. callback += [ckpt_cb]
  177. model.train(epoch_size, dataset, callbacks=callback)
  178. print("============== End Training ==============")
  179. if __name__ == '__main__':
  180. if args_opt.device_target == "Ascend":
  181. train_on_ascend()
  182. elif args_opt.device_target == "GPU":
  183. train_on_gpu()
  184. else:
  185. raise ValueError("Unsupported device target.")