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_quant.py 3.7 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. """
  16. ######################## train lenet example ########################
  17. train lenet and get network model files(.ckpt) :
  18. python train.py --data_path /YourDataPath
  19. """
  20. import os
  21. import argparse
  22. import mindspore.nn as nn
  23. from mindspore import context
  24. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  25. from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor, TimeMonitor
  26. from mindspore.train import Model
  27. from mindspore.nn.metrics import Accuracy
  28. from mindspore.train.quant import quant
  29. from src.dataset import create_dataset
  30. from src.config import mnist_cfg as cfg
  31. from src.lenet_fusion import LeNet5 as LeNet5Fusion
  32. parser = argparse.ArgumentParser(description='MindSpore MNIST Example')
  33. parser.add_argument('--device_target', type=str, default="Ascend",
  34. choices=['Ascend', 'GPU', 'CPU'],
  35. help='device where the code will be implemented (default: Ascend)')
  36. parser.add_argument('--data_path', type=str, default="./MNIST_Data",
  37. help='path where the dataset is saved')
  38. parser.add_argument('--ckpt_path', type=str, default="",
  39. help='if mode is test, must provide path where the trained ckpt file')
  40. parser.add_argument('--dataset_sink_mode', type=bool, default=True,
  41. help='dataset_sink_mode is False or True')
  42. args = parser.parse_args()
  43. if __name__ == "__main__":
  44. context.set_context(mode=context.GRAPH_MODE, device_target=args.device_target)
  45. ds_train = create_dataset(os.path.join(args.data_path, "train"), cfg.batch_size, cfg.epoch_size)
  46. step_size = ds_train.get_dataset_size()
  47. # define fusion network
  48. network = LeNet5Fusion(cfg.num_classes)
  49. # load quantization aware network checkpoint
  50. param_dict = load_checkpoint(args.ckpt_path, network.type)
  51. load_param_into_net(network, param_dict)
  52. # convert fusion network to quantization aware network
  53. network = quant.convert_quant_network(network, quant_delay=0, bn_fold=False, freeze_bn=10000)
  54. # define network loss
  55. net_loss = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True, reduction="mean")
  56. # define network optimization
  57. net_opt = nn.Momentum(network.trainable_params(), cfg.lr, cfg.momentum)
  58. # call back and monitor
  59. time_cb = TimeMonitor(data_size=ds_train.get_dataset_size())
  60. config_ckpt = CheckpointConfig(save_checkpoint_steps=cfg.epoch_size * step_size,
  61. keep_checkpoint_max=cfg.keep_checkpoint_max,
  62. model_type="quant")
  63. ckpt_callback = ModelCheckpoint(prefix="checkpoint_lenet", config=config_ckpt)
  64. # define model
  65. model = Model(network, net_loss, net_opt, metrics={"Accuracy": Accuracy()})
  66. print("============== Starting Training ==============")
  67. model.train(cfg['epoch_size'], ds_train, callbacks=[time_cb, ckpt_callback, LossMonitor()],
  68. dataset_sink_mode=args.dataset_sink_mode)
  69. print("============== End Training ==============")