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

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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. from __future__ import absolute_import
  16. from __future__ import division
  17. from __future__ import print_function
  18. import numpy as np
  19. import pytest
  20. import mindspore.context as context
  21. import mindspore.nn as nn
  22. from mindspore import Tensor
  23. from mindspore import amp
  24. from mindspore.nn import Dense
  25. from mindspore.nn import TrainOneStepCell, WithLossCell
  26. from mindspore.nn.cell import Cell
  27. from mindspore.nn.layer.basic import Flatten
  28. from mindspore.nn.layer.conv import Conv2d
  29. from mindspore.nn.layer.normalization import BatchNorm2d
  30. from mindspore.nn.layer.pooling import MaxPool2d
  31. from mindspore.nn.optim import Momentum
  32. from mindspore.ops import operations as P
  33. from mindspore.ops.operations import TensorAdd
  34. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  35. def random_normal_init(shape, mean=0.0, stddev=0.01, seed=None):
  36. init_value = np.ones(shape).astype(np.float32) * 0.01
  37. return Tensor(init_value)
  38. def variance_scaling_raw(shape):
  39. variance_scaling_value = np.ones(shape).astype(np.float32) * 0.01
  40. return Tensor(variance_scaling_value)
  41. def weight_variable_0(shape):
  42. zeros = np.zeros(shape).astype(np.float32)
  43. return Tensor(zeros)
  44. def weight_variable_1(shape):
  45. ones = np.ones(shape).astype(np.float32)
  46. return Tensor(ones)
  47. def conv3x3(in_channels, out_channels, stride=1, padding=1):
  48. """3x3 convolution """
  49. weight_shape = (out_channels, in_channels, 3, 3)
  50. weight = variance_scaling_raw(weight_shape)
  51. return Conv2d(in_channels, out_channels,
  52. kernel_size=3, stride=stride, weight_init=weight, has_bias=False, pad_mode="same")
  53. def conv1x1(in_channels, out_channels, stride=1, padding=0):
  54. """1x1 convolution"""
  55. weight_shape = (out_channels, in_channels, 1, 1)
  56. weight = variance_scaling_raw(weight_shape)
  57. return Conv2d(in_channels, out_channels,
  58. kernel_size=1, stride=stride, weight_init=weight, has_bias=False, pad_mode="same")
  59. def conv7x7(in_channels, out_channels, stride=1, padding=0):
  60. """1x1 convolution"""
  61. weight_shape = (out_channels, in_channels, 7, 7)
  62. weight = variance_scaling_raw(weight_shape)
  63. return Conv2d(in_channels, out_channels,
  64. kernel_size=7, stride=stride, weight_init=weight, has_bias=False, pad_mode="same")
  65. def bn_with_initialize(out_channels):
  66. shape = (out_channels)
  67. mean = weight_variable_0(shape)
  68. var = weight_variable_1(shape)
  69. beta = weight_variable_0(shape)
  70. gamma = weight_variable_1(shape)
  71. bn = BatchNorm2d(out_channels, momentum=0.1, eps=0.0001, gamma_init=gamma,
  72. beta_init=beta, moving_mean_init=mean, moving_var_init=var)
  73. return bn
  74. def bn_with_initialize_last(out_channels):
  75. shape = (out_channels)
  76. mean = weight_variable_0(shape)
  77. var = weight_variable_1(shape)
  78. beta = weight_variable_0(shape)
  79. gamma = weight_variable_0(shape)
  80. bn = BatchNorm2d(out_channels, momentum=0.1, eps=0.0001, gamma_init=gamma,
  81. beta_init=beta, moving_mean_init=mean, moving_var_init=var)
  82. return bn
  83. def fc_with_initialize(input_channels, out_channels):
  84. weight_shape = (out_channels, input_channels)
  85. bias_shape = (out_channels)
  86. weight = random_normal_init(weight_shape)
  87. bias = weight_variable_0(bias_shape)
  88. return Dense(input_channels, out_channels, weight, bias)
  89. class ResidualBlock(Cell):
  90. expansion = 4
  91. def __init__(self,
  92. in_channels,
  93. out_channels,
  94. stride=1,
  95. down_sample=False):
  96. super(ResidualBlock, self).__init__()
  97. out_chls = out_channels // self.expansion
  98. self.conv1 = conv1x1(in_channels, out_chls, stride=1, padding=0)
  99. self.bn1 = bn_with_initialize(out_chls)
  100. self.conv2 = conv3x3(out_chls, out_chls, stride=stride, padding=1)
  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 = 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(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=1, padding=0)
  129. self.bn1 = bn_with_initialize(out_chls)
  130. self.conv2 = conv3x3(out_chls, out_chls, stride=stride, padding=1)
  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(
  137. in_channels, out_channels, stride=stride, padding=0)
  138. self.bn_down_sample = bn_with_initialize(out_channels)
  139. self.add = TensorAdd()
  140. def construct(self, x):
  141. identity = x
  142. out = self.conv1(x)
  143. out = self.bn1(out)
  144. out = self.relu(out)
  145. out = self.conv2(out)
  146. out = self.bn2(out)
  147. out = self.relu(out)
  148. out = self.conv3(out)
  149. out = self.bn3(out)
  150. identity = self.conv_down_sample(identity)
  151. identity = self.bn_down_sample(identity)
  152. out = self.add(out, identity)
  153. out = self.relu(out)
  154. return out
  155. class MakeLayer0(Cell):
  156. def __init__(self, block, layer_num, in_channels, out_channels, stride):
  157. super(MakeLayer0, self).__init__()
  158. self.a = ResidualBlockWithDown(
  159. in_channels, out_channels, stride=1, down_sample=True)
  160. self.b = block(out_channels, out_channels, stride=stride)
  161. self.c = block(out_channels, out_channels, stride=1)
  162. def construct(self, x):
  163. x = self.a(x)
  164. x = self.b(x)
  165. x = self.c(x)
  166. return x
  167. class MakeLayer1(Cell):
  168. def __init__(self, block, layer_num, in_channels, out_channels, stride):
  169. super(MakeLayer1, self).__init__()
  170. self.a = ResidualBlockWithDown(
  171. in_channels, out_channels, stride=stride, down_sample=True)
  172. self.b = block(out_channels, out_channels, stride=1)
  173. self.c = block(out_channels, out_channels, stride=1)
  174. self.d = block(out_channels, out_channels, stride=1)
  175. def construct(self, x):
  176. x = self.a(x)
  177. x = self.b(x)
  178. x = self.c(x)
  179. x = self.d(x)
  180. return x
  181. class MakeLayer2(Cell):
  182. def __init__(self, block, layer_num, in_channels, out_channels, stride):
  183. super(MakeLayer2, self).__init__()
  184. self.a = ResidualBlockWithDown(
  185. in_channels, out_channels, stride=stride, down_sample=True)
  186. self.b = block(out_channels, out_channels, stride=1)
  187. self.c = block(out_channels, out_channels, stride=1)
  188. self.d = block(out_channels, out_channels, stride=1)
  189. self.e = block(out_channels, out_channels, stride=1)
  190. self.f = block(out_channels, out_channels, stride=1)
  191. def construct(self, x):
  192. x = self.a(x)
  193. x = self.b(x)
  194. x = self.c(x)
  195. x = self.d(x)
  196. x = self.e(x)
  197. x = self.f(x)
  198. return x
  199. class MakeLayer3(Cell):
  200. def __init__(self, block, layer_num, in_channels, out_channels, stride):
  201. super(MakeLayer3, self).__init__()
  202. self.a = ResidualBlockWithDown(
  203. in_channels, out_channels, stride=stride, down_sample=True)
  204. self.b = block(out_channels, out_channels, stride=1)
  205. self.c = block(out_channels, out_channels, stride=1)
  206. def construct(self, x):
  207. x = self.a(x)
  208. x = self.b(x)
  209. x = self.c(x)
  210. return x
  211. class ResNet(Cell):
  212. def __init__(self, block, layer_num, num_classes=100):
  213. super(ResNet, self).__init__()
  214. self.conv1 = conv7x7(3, 64, stride=2, padding=3)
  215. self.bn1 = bn_with_initialize(64)
  216. self.relu = P.ReLU()
  217. self.maxpool = MaxPool2d(kernel_size=3, stride=2, pad_mode="same")
  218. self.layer1 = MakeLayer0(
  219. block, layer_num[0], in_channels=64, out_channels=256, stride=1)
  220. self.layer2 = MakeLayer1(
  221. block, layer_num[1], in_channels=256, out_channels=512, stride=2)
  222. self.layer3 = MakeLayer2(
  223. block, layer_num[2], in_channels=512, out_channels=1024, stride=2)
  224. self.layer4 = MakeLayer3(
  225. block, layer_num[3], in_channels=1024, out_channels=2048, stride=2)
  226. self.pool = nn.AvgPool2d(7, 1)
  227. self.fc = fc_with_initialize(512 * block.expansion, num_classes)
  228. self.flatten = Flatten()
  229. def construct(self, x):
  230. x = self.conv1(x)
  231. x = self.bn1(x)
  232. x = self.relu(x)
  233. x = self.maxpool(x)
  234. x = self.layer1(x)
  235. x = self.layer2(x)
  236. x = self.layer3(x)
  237. x = self.layer4(x)
  238. x = self.pool(x)
  239. x = self.flatten(x)
  240. x = self.fc(x)
  241. return x
  242. def resnet50(num_classes):
  243. return ResNet(ResidualBlock, [3, 4, 6, 3], num_classes)
  244. @pytest.mark.level0
  245. @pytest.mark.platform_x86_gpu_training
  246. @pytest.mark.env_onecard
  247. def test_trainTensor(num_classes=10, epoch=8, batch_size=1):
  248. net = resnet50(num_classes)
  249. lr = 0.1
  250. momentum = 0.9
  251. optimizer = Momentum(filter(lambda x: x.requires_grad,
  252. net.get_parameters()), lr, momentum)
  253. criterion = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
  254. net_with_criterion = WithLossCell(net, criterion)
  255. train_network = TrainOneStepCell(
  256. net_with_criterion, optimizer) # optimizer
  257. train_network.set_train()
  258. losses = []
  259. for i in range(0, epoch):
  260. data = Tensor(np.ones([batch_size, 3, 224, 224]
  261. ).astype(np.float32) * 0.01)
  262. label = Tensor(np.ones([batch_size]).astype(np.int32))
  263. loss = train_network(data, label)
  264. losses.append(loss)
  265. assert (losses[-1].asnumpy() < 1)
  266. @pytest.mark.level0
  267. @pytest.mark.platform_x86_gpu_training
  268. @pytest.mark.env_onecard
  269. def test_trainTensor_big_batchSize(num_classes=10, epoch=8, batch_size=338):
  270. net = resnet50(num_classes)
  271. lr = 0.1
  272. momentum = 0.9
  273. optimizer = Momentum(filter(lambda x: x.requires_grad,
  274. net.get_parameters()), lr, momentum)
  275. criterion = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
  276. net_with_criterion = WithLossCell(net, criterion)
  277. train_network = TrainOneStepCell(
  278. net_with_criterion, optimizer) # optimizer
  279. train_network.set_train()
  280. losses = []
  281. for i in range(0, epoch):
  282. data = Tensor(np.ones([batch_size, 3, 224, 224]
  283. ).astype(np.float32) * 0.01)
  284. label = Tensor(np.ones([batch_size]).astype(np.int32))
  285. loss = train_network(data, label)
  286. losses.append(loss)
  287. assert (losses[-1].asnumpy() < 1)
  288. @pytest.mark.level0
  289. @pytest.mark.platform_x86_gpu_training
  290. @pytest.mark.env_onecard
  291. def test_trainTensor_amp(num_classes=10, epoch=18, batch_size=16):
  292. net = resnet50(num_classes)
  293. lr = 0.1
  294. momentum = 0.9
  295. optimizer = Momentum(filter(lambda x: x.requires_grad,
  296. net.get_parameters()), lr, momentum)
  297. criterion = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
  298. train_network = amp.build_train_network(
  299. net, optimizer, criterion, level="O2")
  300. train_network.set_train()
  301. losses = []
  302. for i in range(0, epoch):
  303. data = Tensor(np.ones([batch_size, 3, 224, 224]
  304. ).astype(np.float32) * 0.01)
  305. label = Tensor(np.ones([batch_size]).astype(np.int32))
  306. loss = train_network(data, label)
  307. losses.append(loss)
  308. assert (losses[-1][0].asnumpy() < 1)
  309. assert not losses[-1][1].asnumpy()
  310. assert (losses[-1][2].asnumpy() > 1)