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.

test_resnet50_quant.py 4.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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 Resnet50_quant on Cifar10"""
  16. import pytest
  17. import numpy as np
  18. from easydict import EasyDict as ed
  19. from mindspore import context
  20. from mindspore import Tensor
  21. from mindspore.nn.optim.momentum import Momentum
  22. from mindspore.train.model import Model
  23. from mindspore.train.quant import quant
  24. from mindspore import set_seed
  25. from resnet_quant_manual import resnet50_quant
  26. from dataset import create_dataset
  27. from lr_generator import get_lr
  28. from utils import Monitor, CrossEntropy
  29. config_quant = ed({
  30. "class_num": 10,
  31. "batch_size": 128,
  32. "step_threshold": 20,
  33. "loss_scale": 1024,
  34. "momentum": 0.9,
  35. "weight_decay": 1e-4,
  36. "epoch_size": 1,
  37. "pretrained_epoch_size": 90,
  38. "buffer_size": 1000,
  39. "image_height": 224,
  40. "image_width": 224,
  41. "data_load_mode": "mindata",
  42. "save_checkpoint": True,
  43. "save_checkpoint_epochs": 1,
  44. "keep_checkpoint_max": 50,
  45. "save_checkpoint_path": "./",
  46. "warmup_epochs": 0,
  47. "lr_decay_mode": "cosine",
  48. "use_label_smooth": True,
  49. "label_smooth_factor": 0.1,
  50. "lr_init": 0,
  51. "lr_max": 0.005,
  52. })
  53. dataset_path = "/home/workspace/mindspore_dataset/cifar-10-batches-bin/"
  54. @pytest.mark.level1
  55. @pytest.mark.platform_arm_ascend_training
  56. @pytest.mark.platform_x86_ascend_training
  57. @pytest.mark.env_onecard
  58. def test_resnet50_quant():
  59. set_seed(1)
  60. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  61. config = config_quant
  62. print("training configure: {}".format(config))
  63. epoch_size = config.epoch_size
  64. # define network
  65. net = resnet50_quant(class_num=config.class_num)
  66. net.set_train(True)
  67. # define loss
  68. if not config.use_label_smooth:
  69. config.label_smooth_factor = 0.0
  70. loss = CrossEntropy(
  71. smooth_factor=config.label_smooth_factor, num_classes=config.class_num)
  72. #loss_scale = FixedLossScaleManager(config.loss_scale, drop_overflow_update=False)
  73. # define dataset
  74. dataset = create_dataset(dataset_path=dataset_path,
  75. config=config,
  76. repeat_num=1,
  77. batch_size=config.batch_size)
  78. step_size = dataset.get_dataset_size()
  79. # convert fusion network to quantization aware network
  80. net = quant.convert_quant_network(net,
  81. bn_fold=True,
  82. per_channel=[True, False],
  83. symmetric=[True, False])
  84. # get learning rate
  85. lr = Tensor(get_lr(lr_init=config.lr_init,
  86. lr_end=0.0,
  87. lr_max=config.lr_max,
  88. warmup_epochs=config.warmup_epochs,
  89. total_epochs=config.epoch_size,
  90. steps_per_epoch=step_size,
  91. lr_decay_mode='cosine'))
  92. # define optimization
  93. opt = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), lr, config.momentum,
  94. config.weight_decay, config.loss_scale)
  95. # define model
  96. #model = Model(net, loss_fn=loss, optimizer=opt, loss_scale_manager=loss_scale, metrics={'acc'})
  97. model = Model(net, loss_fn=loss, optimizer=opt)
  98. print("============== Starting Training ==============")
  99. monitor = Monitor(lr_init=lr.asnumpy(),
  100. step_threshold=config.step_threshold)
  101. callbacks = [monitor]
  102. model.train(epoch_size, dataset, callbacks=callbacks,
  103. dataset_sink_mode=False)
  104. print("============== End Training ==============")
  105. expect_avg_step_loss = 2.40
  106. avg_step_loss = np.mean(np.array(monitor.losses))
  107. print("average step loss:{}".format(avg_step_loss))
  108. assert avg_step_loss < expect_avg_step_loss
  109. if __name__ == '__main__':
  110. test_resnet50_quant()