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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  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. "quantization_aware": True,
  49. })
  50. dataset_path = "/home/workspace/mindspore_dataset/cifar-10-batches-bin/"
  51. @pytest.mark.level1
  52. @pytest.mark.platform_arm_ascend_training
  53. @pytest.mark.platform_x86_ascend_training
  54. @pytest.mark.env_onecard
  55. def test_mobilenetv2_quant():
  56. set_seed(1)
  57. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  58. config = config_ascend_quant
  59. print("training configure: {}".format(config))
  60. epoch_size = config.epoch_size
  61. # define network
  62. network = mobilenetV2(num_classes=config.num_classes)
  63. # define loss
  64. if config.label_smooth > 0:
  65. loss = CrossEntropyWithLabelSmooth(
  66. smooth_factor=config.label_smooth, num_classes=config.num_classes)
  67. else:
  68. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
  69. # define dataset
  70. dataset = create_dataset(dataset_path=dataset_path,
  71. config=config,
  72. repeat_num=1,
  73. batch_size=config.batch_size)
  74. step_size = dataset.get_dataset_size()
  75. # convert fusion network to quantization aware network
  76. quantizer = QuantizationAwareTraining(bn_fold=True,
  77. per_channel=[True, False],
  78. symmetric=[True, False])
  79. network = quantizer.quantize(network)
  80. # get learning rate
  81. lr = Tensor(get_lr(global_step=config.start_epoch * step_size,
  82. lr_init=0,
  83. lr_end=0,
  84. lr_max=config.lr,
  85. warmup_epochs=config.warmup_epochs,
  86. total_epochs=epoch_size + config.start_epoch,
  87. steps_per_epoch=step_size))
  88. # define optimization
  89. opt = nn.Momentum(filter(lambda x: x.requires_grad, network.get_parameters()), lr, config.momentum,
  90. config.weight_decay)
  91. # define model
  92. model = Model(network, loss_fn=loss, optimizer=opt)
  93. print("============== Starting Training ==============")
  94. monitor = Monitor(lr_init=lr.asnumpy(),
  95. step_threshold=config.step_threshold)
  96. callback = [monitor]
  97. model.train(epoch_size, dataset, callbacks=callback,
  98. dataset_sink_mode=False)
  99. print("============== End Training ==============")
  100. expect_avg_step_loss = 2.32
  101. avg_step_loss = np.mean(np.array(monitor.losses))
  102. print("average step loss:{}".format(avg_step_loss))
  103. assert avg_step_loss < expect_avg_step_loss
  104. if __name__ == '__main__':
  105. test_mobilenetv2_quant()