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

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