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.

resnet_cifar.py 6.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. # Copyright 2019 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. import argparse
  16. import mindspore.nn as nn
  17. from mindspore import Tensor
  18. from mindspore.ops import operations as P
  19. from mindspore.nn.optim.momentum import Momentum
  20. from mindspore.train.model import Model, ParallelMode
  21. from mindspore import context
  22. import mindspore.common.dtype as mstype
  23. import os
  24. import numpy as np
  25. import mindspore.ops.functional as F
  26. from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor
  27. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  28. import mindspore.dataset as ds
  29. import mindspore.dataset.transforms.c_transforms as C
  30. import mindspore.dataset.transforms.vision.c_transforms as vision
  31. from mindspore.communication.management import init
  32. from mindspore.parallel._auto_parallel_context import auto_parallel_context
  33. from resnet import resnet50
  34. import random
  35. random.seed(1)
  36. np.random.seed(1)
  37. ds.config.set_seed(1)
  38. parser = argparse.ArgumentParser(description='Image classification')
  39. parser.add_argument('--run_distribute', type=bool, default=False, help='Run distribute')
  40. parser.add_argument('--device_num', type=int, default=1, help='Device num.')
  41. parser.add_argument('--do_train', type=bool, default=True, help='Do train or not.')
  42. parser.add_argument('--do_eval', type=bool, default=False, help='Do eval or not.')
  43. parser.add_argument('--epoch_size', type=int, default=1, help='Epoch size.')
  44. parser.add_argument('--batch_size', type=int, default=32, help='Batch size.')
  45. parser.add_argument('--num_classes', type=int, default=10, help='Num classes.')
  46. parser.add_argument('--checkpoint_path', type=str, default=None, help='Checkpoint file path')
  47. parser.add_argument('--dataset_path', type=str, default="/var/log/npu/datasets/cifar", help='Dataset path')
  48. args_opt = parser.parse_args()
  49. device_id = int(os.getenv('DEVICE_ID'))
  50. data_home = args_opt.dataset_path
  51. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  52. context.set_context(enable_task_sink=True, device_id=device_id)
  53. context.set_context(enable_loop_sink=True)
  54. context.set_context(enable_mem_reuse=True)
  55. def create_dataset(repeat_num=1, training=True):
  56. data_dir = data_home + "/cifar-10-batches-bin"
  57. if not training:
  58. data_dir = data_home + "/cifar-10-verify-bin"
  59. data_set = ds.Cifar10Dataset(data_dir)
  60. if args_opt.run_distribute:
  61. rank_id = int(os.getenv('RANK_ID'))
  62. rank_size = int(os.getenv('RANK_SIZE'))
  63. data_set = ds.Cifar10Dataset(data_dir, num_shards=rank_size, shard_id=rank_id)
  64. resize_height = 224
  65. resize_width = 224
  66. rescale = 1.0 / 255.0
  67. shift = 0.0
  68. # define map operations
  69. random_crop_op = vision.RandomCrop((32, 32), (4, 4, 4, 4)) # padding_mode default CONSTANT
  70. random_horizontal_op = vision.RandomHorizontalFlip()
  71. resize_op = vision.Resize((resize_height, resize_width)) # interpolation default BILINEAR
  72. rescale_op = vision.Rescale(rescale, shift)
  73. normalize_op = vision.Normalize((0.4465, 0.4822, 0.4914), (0.2010, 0.1994, 0.2023))
  74. changeswap_op = vision.HWC2CHW()
  75. type_cast_op = C.TypeCast(mstype.int32)
  76. c_trans = []
  77. if training:
  78. c_trans = [random_crop_op, random_horizontal_op]
  79. c_trans += [resize_op, rescale_op, normalize_op,
  80. changeswap_op]
  81. # apply map operations on images
  82. data_set = data_set.map(input_columns="label", operations=type_cast_op)
  83. data_set = data_set.map(input_columns="image", operations=c_trans)
  84. # apply repeat operations
  85. data_set = data_set.repeat(repeat_num)
  86. # apply shuffle operations
  87. data_set = data_set.shuffle(buffer_size=10)
  88. # apply batch operations
  89. data_set = data_set.batch(batch_size=args_opt.batch_size, drop_remainder=True)
  90. return data_set
  91. class CrossEntropyLoss(nn.Cell):
  92. def __init__(self):
  93. super(CrossEntropyLoss, self).__init__()
  94. self.cross_entropy = P.SoftmaxCrossEntropyWithLogits()
  95. self.mean = P.ReduceMean()
  96. self.one_hot = P.OneHot()
  97. self.one = Tensor(1.0, mstype.float32)
  98. self.zero = Tensor(0.0, mstype.float32)
  99. def construct(self, logits, label):
  100. label = self.one_hot(label, F.shape(logits)[1], self.one, self.zero)
  101. loss = self.cross_entropy(logits, label)[0]
  102. loss = self.mean(loss, (-1,))
  103. return loss
  104. if __name__ == '__main__':
  105. if args_opt.do_eval:
  106. context.set_context(enable_hccl=False)
  107. else:
  108. if args_opt.run_distribute:
  109. context.set_context(enable_hccl=True)
  110. context.set_auto_parallel_context(device_num=args_opt.device_num, parallel_mode=ParallelMode.DATA_PARALLEL)
  111. auto_parallel_context().set_all_reduce_fusion_split_indices([140])
  112. init()
  113. else:
  114. context.set_context(enable_hccl=False)
  115. context.set_context(mode=context.GRAPH_MODE)
  116. epoch_size = args_opt.epoch_size
  117. net = resnet50(args_opt.batch_size, args_opt.num_classes)
  118. loss = CrossEntropyLoss()
  119. opt = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), 0.01, 0.9)
  120. model = Model(net, loss_fn=loss, optimizer=opt, metrics={'acc'})
  121. if args_opt.do_train:
  122. dataset = create_dataset(epoch_size)
  123. batch_num = dataset.get_dataset_size()
  124. config_ck = CheckpointConfig(save_checkpoint_steps=batch_num * 5, keep_checkpoint_max=10)
  125. ckpoint_cb = ModelCheckpoint(prefix="train_resnet_cifar10", directory="./", config=config_ck)
  126. loss_cb = LossMonitor()
  127. model.train(epoch_size, dataset, callbacks=[ckpoint_cb, loss_cb])
  128. if args_opt.do_eval:
  129. if args_opt.checkpoint_path:
  130. param_dict = load_checkpoint(args_opt.checkpoint_path)
  131. load_param_into_net(net, param_dict)
  132. net.set_train(False)
  133. eval_dataset = create_dataset(1, training=False)
  134. res = model.eval(eval_dataset)
  135. print("result: ", res)