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_memreuse.py 6.4 kB

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