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_gpu.py 13 kB

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