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_mobilenetv2_quant.py 4.4 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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_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 import nn
  22. from mindspore.train.model import Model
  23. from mindspore.compression.quant import QuantizationAwareTraining
  24. from mindspore.common import set_seed
  25. from dataset import create_dataset
  26. from lr_generator import get_lr
  27. from utils import Monitor, CrossEntropyWithLabelSmooth
  28. from mobilenetV2 import mobilenetV2
  29. config_ascend_quant = ed({
  30. "num_classes": 10,
  31. "image_height": 224,
  32. "image_width": 224,
  33. "batch_size": 200,
  34. "step_threshold": 10,
  35. "data_load_mode": "mindata",
  36. "epoch_size": 1,
  37. "start_epoch": 200,
  38. "warmup_epochs": 1,
  39. "lr": 0.3,
  40. "momentum": 0.9,
  41. "weight_decay": 4e-5,
  42. "label_smooth": 0.1,
  43. "loss_scale": 1024,
  44. "save_checkpoint": True,
  45. "save_checkpoint_epochs": 1,
  46. "keep_checkpoint_max": 300,
  47. "save_checkpoint_path": "./checkpoint",
  48. })
  49. dataset_path = "/home/workspace/mindspore_dataset/cifar-10-batches-bin/"
  50. @pytest.mark.level0
  51. @pytest.mark.platform_arm_ascend_training
  52. @pytest.mark.platform_x86_ascend_training
  53. @pytest.mark.env_single
  54. def test_mobilenetv2_quant():
  55. set_seed(1)
  56. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  57. config = config_ascend_quant
  58. print("training configure: {}".format(config))
  59. epoch_size = config.epoch_size
  60. # define network
  61. network = mobilenetV2(num_classes=config.num_classes)
  62. # define loss
  63. if config.label_smooth > 0:
  64. loss = CrossEntropyWithLabelSmooth(
  65. smooth_factor=config.label_smooth, num_classes=config.num_classes)
  66. else:
  67. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
  68. # define dataset
  69. dataset = create_dataset(dataset_path=dataset_path,
  70. config=config,
  71. repeat_num=1,
  72. batch_size=config.batch_size)
  73. step_size = dataset.get_dataset_size()
  74. # convert fusion network to quantization aware network
  75. quantizer = QuantizationAwareTraining(bn_fold=True,
  76. per_channel=[True, False],
  77. symmetric=[True, False])
  78. network = quantizer.quantize(network)
  79. # get learning rate
  80. lr = Tensor(get_lr(global_step=config.start_epoch * step_size,
  81. lr_init=0,
  82. lr_end=0,
  83. lr_max=config.lr,
  84. warmup_epochs=config.warmup_epochs,
  85. total_epochs=epoch_size + config.start_epoch,
  86. steps_per_epoch=step_size))
  87. # define optimization
  88. opt = nn.Momentum(filter(lambda x: x.requires_grad, network.get_parameters()), lr, config.momentum,
  89. config.weight_decay)
  90. # define model
  91. model = Model(network, loss_fn=loss, optimizer=opt)
  92. print("============== Starting Training ==============")
  93. monitor = Monitor(lr_init=lr.asnumpy(),
  94. step_threshold=config.step_threshold)
  95. callback = [monitor]
  96. model.train(epoch_size, dataset, callbacks=callback,
  97. dataset_sink_mode=False)
  98. print("============== End Training ==============")
  99. export_time_used = 650
  100. train_time = monitor.step_mseconds
  101. print('train_time_used:{}'.format(train_time))
  102. assert train_time < export_time_used
  103. expect_avg_step_loss = 2.32
  104. avg_step_loss = np.mean(np.array(monitor.losses))
  105. print("average step loss:{}".format(avg_step_loss))
  106. assert avg_step_loss < expect_avg_step_loss
  107. if __name__ == '__main__':
  108. test_mobilenetv2_quant()