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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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
  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(args_opt, config)
  45. # CPU only support "incremental_learn"
  46. if args_opt.train_method == "incremental_learn":
  47. step_size = extract_features(backbone_net, args_opt.dataset_path, config)
  48. net = head_net
  49. elif args_opt.train_method in ("train", "fine_tune"):
  50. if args_opt.platform == "CPU":
  51. raise ValueError("Currently, CPU only support \"incremental_learn\", not \"fine_tune\" or \"train\".")
  52. dataset = create_dataset(dataset_path=args_opt.dataset_path, do_train=True, config=config)
  53. step_size = dataset.get_dataset_size()
  54. # Currently, only Ascend support switch precision.
  55. switch_precision(net, mstype.float16, config)
  56. # define loss
  57. if config.label_smooth > 0:
  58. loss = CrossEntropyWithLabelSmooth(
  59. smooth_factor=config.label_smooth, num_classes=config.num_classes)
  60. else:
  61. loss = SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
  62. epoch_size = config.epoch_size
  63. # get learning rate
  64. lr = Tensor(get_lr(global_step=0,
  65. lr_init=config.lr_init,
  66. lr_end=config.lr_end,
  67. lr_max=config.lr_max,
  68. warmup_epochs=config.warmup_epochs,
  69. total_epochs=epoch_size,
  70. steps_per_epoch=step_size))
  71. if args_opt.train_method == "incremental_learn":
  72. opt = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), lr, config.momentum, config.weight_decay)
  73. network = WithLossCell(net, loss)
  74. network = TrainOneStepCell(network, opt)
  75. network.set_train()
  76. features_path = args_opt.dataset_path + '_features'
  77. idx_list = list(range(step_size))
  78. if os.path.isdir(config.save_checkpoint_path):
  79. os.rename(config.save_checkpoint_path, "{}_{}".format(config.save_checkpoint_path, time.time()))
  80. os.mkdir(config.save_checkpoint_path)
  81. for epoch in range(epoch_size):
  82. random.shuffle(idx_list)
  83. epoch_start = time.time()
  84. losses = []
  85. for j in idx_list:
  86. feature = Tensor(np.load(os.path.join(features_path, f"feature_{j}.npy")))
  87. label = Tensor(np.load(os.path.join(features_path, f"label_{j}.npy")))
  88. losses.append(network(feature, label).asnumpy())
  89. epoch_mseconds = (time.time()-epoch_start) * 1000
  90. per_step_mseconds = epoch_mseconds / step_size
  91. print("\r epoch[{}], iter[{}] cost: {:5.3f}, per step time: {:5.3f}, avg loss: {:5.3f}"\
  92. .format(epoch + 1, step_size, epoch_mseconds, per_step_mseconds, np.mean(np.array(losses))), \
  93. end="")
  94. if (epoch + 1) % config.save_checkpoint_epochs == 0:
  95. save_checkpoint(network, os.path.join(config.save_checkpoint_path, \
  96. f"mobilenetv2_head_{epoch+1}.ckpt"))
  97. print("total cost {:5.4f} s".format(time.time() - start))
  98. elif args_opt.train_method in ("train", "fine_tune"):
  99. loss_scale = FixedLossScaleManager(config.loss_scale, drop_overflow_update=False)
  100. opt = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), lr, config.momentum, \
  101. config.weight_decay, config.loss_scale)
  102. model = Model(net, loss_fn=loss, optimizer=opt, loss_scale_manager=loss_scale)
  103. cb = config_ckpoint(config, lr, step_size)
  104. print("============== Starting Training ==============")
  105. model.train(epoch_size, dataset, callbacks=cb)
  106. print("============== End Training ==============")