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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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 time
  18. import random
  19. import numpy as np
  20. from mindspore import Tensor
  21. from mindspore.nn import WithLossCell, TrainOneStepCell
  22. from mindspore.nn.optim.momentum import Momentum
  23. from mindspore.nn.loss import SoftmaxCrossEntropyWithLogits
  24. from mindspore.common import dtype as mstype
  25. from mindspore.communication.management import get_rank
  26. from mindspore.train.model import Model
  27. from mindspore.train.loss_scale_manager import FixedLossScaleManager
  28. from mindspore.train.serialization import save_checkpoint
  29. from mindspore.common import set_seed
  30. from src.dataset import create_dataset, extract_features
  31. from src.lr_generator import get_lr
  32. from src.config import set_config
  33. from src.args import train_parse_args
  34. from src.utils import context_device_init, switch_precision, config_ckpoint
  35. from src.models import CrossEntropyWithLabelSmooth, define_net, load_ckpt
  36. set_seed(1)
  37. if __name__ == '__main__':
  38. args_opt = train_parse_args()
  39. config = set_config(args_opt)
  40. start = time.time()
  41. print(f"train args: {args_opt}\ncfg: {config}")
  42. #set context and device init
  43. context_device_init(config)
  44. # define network
  45. backbone_net, head_net, net = define_net(config, args_opt.is_training)
  46. if args_opt.pretrain_ckpt and args_opt.freeze_layer == "backbone":
  47. load_ckpt(backbone_net, args_opt.pretrain_ckpt, trainable=False)
  48. step_size = extract_features(backbone_net, args_opt.dataset_path, config)
  49. else:
  50. if args_opt.platform == "CPU":
  51. raise ValueError("CPU only support fine tune the head net, doesn't support fine tune the all net")
  52. if args_opt.pretrain_ckpt:
  53. load_ckpt(backbone_net, args_opt.pretrain_ckpt)
  54. dataset = create_dataset(dataset_path=args_opt.dataset_path, do_train=True, config=config)
  55. step_size = dataset.get_dataset_size()
  56. if step_size == 0:
  57. raise ValueError("The step_size of dataset is zero. Check if the images' count of train dataset is more \
  58. than batch_size in config.py")
  59. # Currently, only Ascend support switch precision.
  60. switch_precision(net, mstype.float16, config)
  61. # define loss
  62. if config.label_smooth > 0:
  63. loss = CrossEntropyWithLabelSmooth(
  64. smooth_factor=config.label_smooth, num_classes=config.num_classes)
  65. else:
  66. loss = SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
  67. epoch_size = config.epoch_size
  68. # get learning rate
  69. lr = Tensor(get_lr(global_step=0,
  70. lr_init=config.lr_init,
  71. lr_end=config.lr_end,
  72. lr_max=config.lr_max,
  73. warmup_epochs=config.warmup_epochs,
  74. total_epochs=epoch_size,
  75. steps_per_epoch=step_size))
  76. if args_opt.pretrain_ckpt is None or args_opt.freeze_layer == "none":
  77. loss_scale = FixedLossScaleManager(config.loss_scale, drop_overflow_update=False)
  78. opt = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), lr, config.momentum, \
  79. config.weight_decay, config.loss_scale)
  80. model = Model(net, loss_fn=loss, optimizer=opt, loss_scale_manager=loss_scale)
  81. cb = config_ckpoint(config, lr, step_size)
  82. print("============== Starting Training ==============")
  83. model.train(epoch_size, dataset, callbacks=cb)
  84. print("============== End Training ==============")
  85. else:
  86. opt = Momentum(filter(lambda x: x.requires_grad, head_net.get_parameters()), lr, config.momentum, config.weight_decay)
  87. network = WithLossCell(head_net, loss)
  88. network = TrainOneStepCell(network, opt)
  89. network.set_train()
  90. features_path = args_opt.dataset_path + '_features'
  91. idx_list = list(range(step_size))
  92. rank = 0
  93. if config.run_distribute:
  94. rank = get_rank()
  95. save_ckpt_path = os.path.join(config.save_checkpoint_path, 'ckpt_' + str(rank) + '/')
  96. if not os.path.isdir(save_ckpt_path):
  97. os.mkdir(save_ckpt_path)
  98. for epoch in range(epoch_size):
  99. random.shuffle(idx_list)
  100. epoch_start = time.time()
  101. losses = []
  102. for j in idx_list:
  103. feature = Tensor(np.load(os.path.join(features_path, f"feature_{j}.npy")))
  104. label = Tensor(np.load(os.path.join(features_path, f"label_{j}.npy")))
  105. losses.append(network(feature, label).asnumpy())
  106. epoch_mseconds = (time.time()-epoch_start) * 1000
  107. per_step_mseconds = epoch_mseconds / step_size
  108. print("epoch[{}/{}], iter[{}] cost: {:5.3f}, per step time: {:5.3f}, avg loss: {:5.3f}"\
  109. .format(epoch + 1, epoch_size, step_size, epoch_mseconds, per_step_mseconds, np.mean(np.array(losses))))
  110. if (epoch + 1) % config.save_checkpoint_epochs == 0:
  111. save_checkpoint(net, os.path.join(save_ckpt_path, f"mobilenetv2_{epoch+1}.ckpt"))
  112. print("total cost {:5.4f} s".format(time.time() - start))