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_pynative_resnet50.py 14 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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 time
  16. import random
  17. import numpy as np
  18. import pytest
  19. import mindspore.common.dtype as mstype
  20. import mindspore.dataset as ds
  21. import mindspore.dataset.transforms.c_transforms as C
  22. import mindspore.dataset.transforms.vision.c_transforms as vision
  23. import mindspore.nn as nn
  24. import mindspore.ops.functional as F
  25. from mindspore import Tensor
  26. from mindspore import context
  27. from mindspore import ParameterTuple
  28. from mindspore.nn import Cell
  29. from mindspore.ops import operations as P
  30. from mindspore.ops import composite as CP
  31. from mindspore.nn.optim.momentum import Momentum
  32. from mindspore.common.initializer import initializer
  33. from mindspore.nn.wrap.cell_wrapper import WithLossCell
  34. random.seed(1)
  35. np.random.seed(1)
  36. ds.config.set_seed(1)
  37. grad_by_list = CP.GradOperation(get_by_list=True)
  38. def weight_variable(shape):
  39. return initializer('XavierUniform', shape=shape, dtype=mstype.float32)
  40. def weight_variable_uniform(shape):
  41. return initializer('Uniform', shape=shape, dtype=mstype.float32)
  42. def weight_variable_0(shape):
  43. zeros = np.zeros(shape).astype(np.float32)
  44. return Tensor(zeros)
  45. def weight_variable_1(shape):
  46. ones = np.ones(shape).astype(np.float32)
  47. return Tensor(ones)
  48. def conv3x3(in_channels, out_channels, stride=1, padding=0):
  49. """3x3 convolution """
  50. weight_shape = (out_channels, in_channels, 3, 3)
  51. weight = weight_variable(weight_shape)
  52. return nn.Conv2d(in_channels, out_channels,
  53. kernel_size=3, stride=stride, padding=padding, weight_init=weight, has_bias=False, pad_mode="same")
  54. def conv1x1(in_channels, out_channels, stride=1, padding=0):
  55. """1x1 convolution"""
  56. weight_shape = (out_channels, in_channels, 1, 1)
  57. weight = weight_variable(weight_shape)
  58. return nn.Conv2d(in_channels, out_channels,
  59. kernel_size=1, stride=stride, padding=padding, weight_init=weight, has_bias=False, pad_mode="same")
  60. def conv7x7(in_channels, out_channels, stride=1, padding=0):
  61. """1x1 convolution"""
  62. weight_shape = (out_channels, in_channels, 7, 7)
  63. weight = weight_variable(weight_shape)
  64. return nn.Conv2d(in_channels, out_channels,
  65. kernel_size=7, stride=stride, padding=padding, weight_init=weight, has_bias=False, pad_mode="same")
  66. def bn_with_initialize(out_channels):
  67. shape = (out_channels)
  68. mean = weight_variable_0(shape)
  69. var = weight_variable_1(shape)
  70. beta = weight_variable_0(shape)
  71. gamma = weight_variable_uniform(shape)
  72. bn = nn.BatchNorm2d(out_channels, momentum=0.99, eps=0.00001, gamma_init=gamma,
  73. beta_init=beta, moving_mean_init=mean, moving_var_init=var)
  74. return bn
  75. def bn_with_initialize_last(out_channels):
  76. shape = (out_channels)
  77. mean = weight_variable_0(shape)
  78. var = weight_variable_1(shape)
  79. beta = weight_variable_0(shape)
  80. gamma = weight_variable_uniform(shape)
  81. bn = nn.BatchNorm2d(out_channels, momentum=0.99, eps=0.00001, gamma_init=gamma,
  82. beta_init=beta, moving_mean_init=mean, moving_var_init=var)
  83. return bn
  84. def fc_with_initialize(input_channels, out_channels):
  85. weight_shape = (out_channels, input_channels)
  86. weight = weight_variable(weight_shape)
  87. bias_shape = (out_channels)
  88. bias = weight_variable_uniform(bias_shape)
  89. return nn.Dense(input_channels, out_channels, weight, bias)
  90. class ResidualBlock(nn.Cell):
  91. expansion = 4
  92. def __init__(self,
  93. in_channels,
  94. out_channels,
  95. stride=1):
  96. super(ResidualBlock, self).__init__()
  97. out_chls = out_channels // self.expansion
  98. self.conv1 = conv1x1(in_channels, out_chls, stride=stride, padding=0)
  99. self.bn1 = bn_with_initialize(out_chls)
  100. self.conv2 = conv3x3(out_chls, out_chls, stride=1, padding=0)
  101. self.bn2 = bn_with_initialize(out_chls)
  102. self.conv3 = conv1x1(out_chls, out_channels, stride=1, padding=0)
  103. self.bn3 = bn_with_initialize_last(out_channels)
  104. self.relu = P.ReLU()
  105. self.add = P.TensorAdd()
  106. def construct(self, x):
  107. identity = x
  108. out = self.conv1(x)
  109. out = self.bn1(out)
  110. out = self.relu(out)
  111. out = self.conv2(out)
  112. out = self.bn2(out)
  113. out = self.relu(out)
  114. out = self.conv3(out)
  115. out = self.bn3(out)
  116. out = self.add(out, identity)
  117. out = self.relu(out)
  118. return out
  119. class ResidualBlockWithDown(nn.Cell):
  120. expansion = 4
  121. def __init__(self,
  122. in_channels,
  123. out_channels,
  124. stride=1,
  125. down_sample=False):
  126. super(ResidualBlockWithDown, self).__init__()
  127. out_chls = out_channels // self.expansion
  128. self.conv1 = conv1x1(in_channels, out_chls, stride=stride, padding=0)
  129. self.bn1 = bn_with_initialize(out_chls)
  130. self.conv2 = conv3x3(out_chls, out_chls, stride=1, padding=0)
  131. self.bn2 = bn_with_initialize(out_chls)
  132. self.conv3 = conv1x1(out_chls, out_channels, stride=1, padding=0)
  133. self.bn3 = bn_with_initialize_last(out_channels)
  134. self.relu = P.ReLU()
  135. self.downSample = down_sample
  136. self.conv_down_sample = conv1x1(in_channels, out_channels, stride=stride, padding=0)
  137. self.bn_down_sample = bn_with_initialize(out_channels)
  138. self.add = P.TensorAdd()
  139. def construct(self, x):
  140. identity = x
  141. out = self.conv1(x)
  142. out = self.bn1(out)
  143. out = self.relu(out)
  144. out = self.conv2(out)
  145. out = self.bn2(out)
  146. out = self.relu(out)
  147. out = self.conv3(out)
  148. out = self.bn3(out)
  149. identity = self.conv_down_sample(identity)
  150. identity = self.bn_down_sample(identity)
  151. out = self.add(out, identity)
  152. out = self.relu(out)
  153. return out
  154. class MakeLayer0(nn.Cell):
  155. def __init__(self, block, in_channels, out_channels, stride):
  156. super(MakeLayer0, self).__init__()
  157. self.a = ResidualBlockWithDown(in_channels, out_channels, stride=1, down_sample=True)
  158. self.b = block(out_channels, out_channels, stride=stride)
  159. self.c = block(out_channels, out_channels, stride=1)
  160. def construct(self, x):
  161. x = self.a(x)
  162. x = self.b(x)
  163. x = self.c(x)
  164. return x
  165. class MakeLayer1(nn.Cell):
  166. def __init__(self, block, in_channels, out_channels, stride):
  167. super(MakeLayer1, self).__init__()
  168. self.a = ResidualBlockWithDown(in_channels, out_channels, stride=stride, down_sample=True)
  169. self.b = block(out_channels, out_channels, stride=1)
  170. self.c = block(out_channels, out_channels, stride=1)
  171. self.d = block(out_channels, out_channels, stride=1)
  172. def construct(self, x):
  173. x = self.a(x)
  174. x = self.b(x)
  175. x = self.c(x)
  176. x = self.d(x)
  177. return x
  178. class MakeLayer2(nn.Cell):
  179. def __init__(self, block, in_channels, out_channels, stride):
  180. super(MakeLayer2, self).__init__()
  181. self.a = ResidualBlockWithDown(in_channels, out_channels, stride=stride, down_sample=True)
  182. self.b = block(out_channels, out_channels, stride=1)
  183. self.c = block(out_channels, out_channels, stride=1)
  184. self.d = block(out_channels, out_channels, stride=1)
  185. self.e = block(out_channels, out_channels, stride=1)
  186. self.f = block(out_channels, out_channels, stride=1)
  187. def construct(self, x):
  188. x = self.a(x)
  189. x = self.b(x)
  190. x = self.c(x)
  191. x = self.d(x)
  192. x = self.e(x)
  193. x = self.f(x)
  194. return x
  195. class MakeLayer3(nn.Cell):
  196. def __init__(self, block, in_channels, out_channels, stride):
  197. super(MakeLayer3, self).__init__()
  198. self.a = ResidualBlockWithDown(in_channels, out_channels, stride=stride, down_sample=True)
  199. self.b = block(out_channels, out_channels, stride=1)
  200. self.c = block(out_channels, out_channels, stride=1)
  201. def construct(self, x):
  202. x = self.a(x)
  203. x = self.b(x)
  204. x = self.c(x)
  205. return x
  206. class ResNet(nn.Cell):
  207. def __init__(self, block, num_classes=100, batch_size=32):
  208. super(ResNet, self).__init__()
  209. self.batch_size = batch_size
  210. self.num_classes = num_classes
  211. self.conv1 = conv7x7(3, 64, stride=2, padding=0)
  212. self.bn1 = bn_with_initialize(64)
  213. self.relu = P.ReLU()
  214. self.maxpool = P.MaxPoolWithArgmax(ksize=3, strides=2, padding="SAME")
  215. self.layer1 = MakeLayer0(block, in_channels=64, out_channels=256, stride=1)
  216. self.layer2 = MakeLayer1(block, in_channels=256, out_channels=512, stride=2)
  217. self.layer3 = MakeLayer2(block, in_channels=512, out_channels=1024, stride=2)
  218. self.layer4 = MakeLayer3(block, in_channels=1024, out_channels=2048, stride=2)
  219. self.pool = P.ReduceMean(keep_dims=True)
  220. self.squeeze = P.Squeeze(axis=(2, 3))
  221. self.fc = fc_with_initialize(512 * block.expansion, num_classes)
  222. def construct(self, x):
  223. x = self.conv1(x)
  224. x = self.bn1(x)
  225. x = self.relu(x)
  226. x = self.maxpool(x)[0]
  227. x = self.layer1(x)
  228. x = self.layer2(x)
  229. x = self.layer3(x)
  230. x = self.layer4(x)
  231. x = self.pool(x, (2, 3))
  232. x = self.squeeze(x)
  233. x = self.fc(x)
  234. return x
  235. def resnet50(batch_size, num_classes):
  236. return ResNet(ResidualBlock, num_classes, batch_size)
  237. def create_dataset(repeat_num=1, training=True, batch_size=32):
  238. data_home = "/home/workspace/mindspore_dataset"
  239. data_dir = data_home + "/cifar-10-batches-bin"
  240. if not training:
  241. data_dir = data_home + "/cifar-10-verify-bin"
  242. data_set = ds.Cifar10Dataset(data_dir)
  243. resize_height = 224
  244. resize_width = 224
  245. rescale = 1.0 / 255.0
  246. shift = 0.0
  247. # define map operations
  248. random_crop_op = vision.RandomCrop((32, 32), (4, 4, 4, 4)) # padding_mode default CONSTANT
  249. random_horizontal_op = vision.RandomHorizontalFlip()
  250. # interpolation default BILINEAR
  251. resize_op = vision.Resize((resize_height, resize_width))
  252. rescale_op = vision.Rescale(rescale, shift)
  253. normalize_op = vision.Normalize((0.4465, 0.4822, 0.4914), (0.2010, 0.1994, 0.2023))
  254. changeswap_op = vision.HWC2CHW()
  255. type_cast_op = C.TypeCast(mstype.int32)
  256. c_trans = []
  257. if training:
  258. c_trans = [random_crop_op, random_horizontal_op]
  259. c_trans += [resize_op, rescale_op, normalize_op,
  260. changeswap_op]
  261. # apply map operations on images
  262. data_set = data_set.map(input_columns="label", operations=type_cast_op)
  263. data_set = data_set.map(input_columns="image", operations=c_trans)
  264. # apply shuffle operations
  265. data_set = data_set.shuffle(buffer_size=1000)
  266. # apply batch operations
  267. data_set = data_set.batch(batch_size=batch_size, drop_remainder=True)
  268. # apply repeat operations
  269. data_set = data_set.repeat(repeat_num)
  270. return data_set
  271. class CrossEntropyLoss(nn.Cell):
  272. def __init__(self):
  273. super(CrossEntropyLoss, self).__init__()
  274. self.cross_entropy = P.SoftmaxCrossEntropyWithLogits()
  275. self.mean = P.ReduceMean()
  276. self.one_hot = P.OneHot()
  277. self.one = Tensor(1.0, mstype.float32)
  278. self.zero = Tensor(0.0, mstype.float32)
  279. def construct(self, logits, label):
  280. label = self.one_hot(label, F.shape(logits)[1], self.one, self.zero)
  281. loss = self.cross_entropy(logits, label)[0]
  282. loss = self.mean(loss, (-1,))
  283. return loss
  284. class GradWrap(Cell):
  285. """ GradWrap definition """
  286. def __init__(self, network):
  287. super(GradWrap, self).__init__()
  288. self.network = network
  289. self.weights = ParameterTuple(network.trainable_params())
  290. def construct(self, x, label):
  291. weights = self.weights
  292. return grad_by_list(self.network, weights)(x, label)
  293. @pytest.mark.level0
  294. @pytest.mark.platform_arm_ascend_training
  295. @pytest.mark.platform_x86_ascend_training
  296. @pytest.mark.env_onecard
  297. def test_pynative_resnet50():
  298. context.set_context(mode=context.PYNATIVE_MODE, device_target="Ascend")
  299. batch_size = 32
  300. num_classes = 10
  301. net = resnet50(batch_size, num_classes)
  302. criterion = CrossEntropyLoss()
  303. optimizer = Momentum(learning_rate=0.01, momentum=0.9,
  304. params=filter(lambda x: x.requires_grad, net.get_parameters()))
  305. net_with_criterion = WithLossCell(net, criterion)
  306. net_with_criterion.set_grad()
  307. train_network = GradWrap(net_with_criterion)
  308. train_network.set_train()
  309. step = 0
  310. max_step = 20
  311. exceed_num = 0
  312. data_set = create_dataset(repeat_num=1, training=True, batch_size=batch_size)
  313. for element in data_set.create_dict_iterator():
  314. step = step + 1
  315. if step > max_step:
  316. break
  317. start_time = time.time()
  318. input_data = Tensor(element["image"])
  319. input_label = Tensor(element["label"])
  320. loss_output = net_with_criterion(input_data, input_label)
  321. grads = train_network(input_data, input_label)
  322. optimizer(grads)
  323. end_time = time.time()
  324. cost_time = end_time - start_time
  325. print("======step: ", step, " loss: ", loss_output.asnumpy(), " cost time: ", cost_time)
  326. if step > 1 and cost_time > 0.23:
  327. exceed_num = exceed_num + 1
  328. assert exceed_num < 10