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

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. """
  16. #################train googlent example on cifar10########################
  17. python train.py
  18. """
  19. import argparse
  20. import os
  21. import numpy as np
  22. import mindspore.nn as nn
  23. from mindspore import Tensor
  24. from mindspore import context
  25. from mindspore.communication.management import init, get_rank
  26. from mindspore.nn.optim.momentum import Momentum
  27. from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor, TimeMonitor
  28. from mindspore.train.loss_scale_manager import DynamicLossScaleManager, FixedLossScaleManager
  29. from mindspore.train.model import Model
  30. from mindspore.context import ParallelMode
  31. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  32. from mindspore.common import set_seed
  33. from src.config import cifar_cfg, imagenet_cfg
  34. from src.dataset import create_dataset_cifar10, create_dataset_imagenet
  35. from src.googlenet import GoogleNet
  36. from src.CrossEntropySmooth import CrossEntropySmooth
  37. set_seed(1)
  38. def lr_steps_cifar10(global_step, lr_max=None, total_epochs=None, steps_per_epoch=None):
  39. """Set learning rate."""
  40. lr_each_step = []
  41. total_steps = steps_per_epoch * total_epochs
  42. decay_epoch_index = [0.3 * total_steps, 0.6 * total_steps, 0.8 * total_steps]
  43. for i in range(total_steps):
  44. if i < decay_epoch_index[0]:
  45. lr_each_step.append(lr_max)
  46. elif i < decay_epoch_index[1]:
  47. lr_each_step.append(lr_max * 0.1)
  48. elif i < decay_epoch_index[2]:
  49. lr_each_step.append(lr_max * 0.01)
  50. else:
  51. lr_each_step.append(lr_max * 0.001)
  52. current_step = global_step
  53. lr_each_step = np.array(lr_each_step).astype(np.float32)
  54. learning_rate = lr_each_step[current_step:]
  55. return learning_rate
  56. def lr_steps_imagenet(_cfg, steps_per_epoch):
  57. """lr step for imagenet"""
  58. from src.lr_scheduler.warmup_step_lr import warmup_step_lr
  59. from src.lr_scheduler.warmup_cosine_annealing_lr import warmup_cosine_annealing_lr
  60. if _cfg.lr_scheduler == 'exponential':
  61. _lr = warmup_step_lr(_cfg.lr_init,
  62. _cfg.lr_epochs,
  63. steps_per_epoch,
  64. _cfg.warmup_epochs,
  65. _cfg.epoch_size,
  66. gamma=_cfg.lr_gamma,
  67. )
  68. elif _cfg.lr_scheduler == 'cosine_annealing':
  69. _lr = warmup_cosine_annealing_lr(_cfg.lr_init,
  70. steps_per_epoch,
  71. _cfg.warmup_epochs,
  72. _cfg.epoch_size,
  73. _cfg.T_max,
  74. _cfg.eta_min)
  75. else:
  76. raise NotImplementedError(_cfg.lr_scheduler)
  77. return _lr
  78. if __name__ == '__main__':
  79. parser = argparse.ArgumentParser(description='Classification')
  80. parser.add_argument('--dataset_name', type=str, default='cifar10', choices=['imagenet', 'cifar10'],
  81. help='dataset name.')
  82. parser.add_argument('--device_id', type=int, default=None, help='device id of GPU or Ascend. (Default: None)')
  83. args_opt = parser.parse_args()
  84. if args_opt.dataset_name == "cifar10":
  85. cfg = cifar_cfg
  86. elif args_opt.dataset_name == "imagenet":
  87. cfg = imagenet_cfg
  88. else:
  89. raise ValueError("Unsupported dataset.")
  90. # set context
  91. device_target = cfg.device_target
  92. context.set_context(mode=context.GRAPH_MODE, device_target=cfg.device_target)
  93. device_num = int(os.environ.get("DEVICE_NUM", 1))
  94. rank = 0
  95. if device_target == "Ascend":
  96. if args_opt.device_id is not None:
  97. context.set_context(device_id=args_opt.device_id)
  98. else:
  99. context.set_context(device_id=cfg.device_id)
  100. if device_num > 1:
  101. context.reset_auto_parallel_context()
  102. context.set_auto_parallel_context(device_num=device_num, parallel_mode=ParallelMode.DATA_PARALLEL,
  103. gradients_mean=True)
  104. init()
  105. rank = get_rank()
  106. elif device_target == "GPU":
  107. if device_num > 1:
  108. init()
  109. context.reset_auto_parallel_context()
  110. context.set_auto_parallel_context(device_num=device_num, parallel_mode=ParallelMode.DATA_PARALLEL,
  111. gradients_mean=True)
  112. rank = get_rank()
  113. else:
  114. raise ValueError("Unsupported platform.")
  115. if args_opt.dataset_name == "cifar10":
  116. dataset = create_dataset_cifar10(cfg.data_path, 1)
  117. elif args_opt.dataset_name == "imagenet":
  118. dataset = create_dataset_imagenet(cfg.data_path, 1)
  119. else:
  120. raise ValueError("Unsupported dataset.")
  121. batch_num = dataset.get_dataset_size()
  122. net = GoogleNet(num_classes=cfg.num_classes)
  123. # Continue training if set pre_trained to be True
  124. if cfg.pre_trained:
  125. param_dict = load_checkpoint(cfg.checkpoint_path)
  126. load_param_into_net(net, param_dict)
  127. loss_scale_manager = None
  128. if args_opt.dataset_name == 'cifar10':
  129. lr = lr_steps_cifar10(0, lr_max=cfg.lr_init, total_epochs=cfg.epoch_size, steps_per_epoch=batch_num)
  130. opt = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()),
  131. learning_rate=Tensor(lr),
  132. momentum=cfg.momentum,
  133. weight_decay=cfg.weight_decay)
  134. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
  135. elif args_opt.dataset_name == 'imagenet':
  136. lr = lr_steps_imagenet(cfg, batch_num)
  137. def get_param_groups(network):
  138. """ get param groups """
  139. decay_params = []
  140. no_decay_params = []
  141. for x in network.trainable_params():
  142. parameter_name = x.name
  143. if parameter_name.endswith('.bias'):
  144. # all bias not using weight decay
  145. no_decay_params.append(x)
  146. elif parameter_name.endswith('.gamma'):
  147. # bn weight bias not using weight decay, be carefully for now x not include BN
  148. no_decay_params.append(x)
  149. elif parameter_name.endswith('.beta'):
  150. # bn weight bias not using weight decay, be carefully for now x not include BN
  151. no_decay_params.append(x)
  152. else:
  153. decay_params.append(x)
  154. return [{'params': no_decay_params, 'weight_decay': 0.0}, {'params': decay_params}]
  155. if cfg.is_dynamic_loss_scale:
  156. cfg.loss_scale = 1
  157. opt = Momentum(params=get_param_groups(net),
  158. learning_rate=Tensor(lr),
  159. momentum=cfg.momentum,
  160. weight_decay=cfg.weight_decay,
  161. loss_scale=cfg.loss_scale)
  162. if not cfg.use_label_smooth:
  163. cfg.label_smooth_factor = 0.0
  164. loss = CrossEntropySmooth(sparse=True, reduction="mean",
  165. smooth_factor=cfg.label_smooth_factor, num_classes=cfg.num_classes)
  166. if cfg.is_dynamic_loss_scale == 1:
  167. loss_scale_manager = DynamicLossScaleManager(init_loss_scale=65536, scale_factor=2, scale_window=2000)
  168. else:
  169. loss_scale_manager = FixedLossScaleManager(cfg.loss_scale, drop_overflow_update=False)
  170. model = Model(net, loss_fn=loss, optimizer=opt, metrics={'acc'},
  171. amp_level="O2", keep_batchnorm_fp32=False, loss_scale_manager=loss_scale_manager)
  172. config_ck = CheckpointConfig(save_checkpoint_steps=batch_num * 5, keep_checkpoint_max=cfg.keep_checkpoint_max)
  173. time_cb = TimeMonitor(data_size=batch_num)
  174. ckpt_save_dir = "./ckpt_" + str(rank) + "/"
  175. ckpoint_cb = ModelCheckpoint(prefix="train_googlenet_" + args_opt.dataset_name, directory=ckpt_save_dir,
  176. config=config_ck)
  177. loss_cb = LossMonitor()
  178. model.train(cfg.epoch_size, dataset, callbacks=[time_cb, ckpoint_cb, loss_cb])
  179. print("train success")