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 16 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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, ParameterTuple
  23. from mindspore import amp
  24. from mindspore.nn import Dense
  25. from mindspore.nn import TrainOneStepCell, WithLossCell, ForwardValueAndGrad
  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 import functional as F
  34. from mindspore.ops.operations import Add
  35. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  36. def random_normal_init(shape, mean=0.0, stddev=0.01, seed=None):
  37. init_value = np.ones(shape).astype(np.float32) * 0.01
  38. return Tensor(init_value)
  39. def variance_scaling_raw(shape):
  40. variance_scaling_value = np.ones(shape).astype(np.float32) * 0.01
  41. return Tensor(variance_scaling_value)
  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=1):
  49. """3x3 convolution """
  50. weight_shape = (out_channels, in_channels, 3, 3)
  51. weight = variance_scaling_raw(weight_shape)
  52. return Conv2d(in_channels, out_channels,
  53. kernel_size=3, stride=stride, 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 = variance_scaling_raw(weight_shape)
  58. return Conv2d(in_channels, out_channels,
  59. kernel_size=1, stride=stride, 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 = variance_scaling_raw(weight_shape)
  64. return Conv2d(in_channels, out_channels,
  65. kernel_size=7, stride=stride, 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_1(shape)
  72. bn = BatchNorm2d(out_channels, momentum=0.1, eps=0.0001, 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_0(shape)
  81. bn = BatchNorm2d(out_channels, momentum=0.1, eps=0.0001, 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. bias_shape = (out_channels)
  87. weight = random_normal_init(weight_shape)
  88. bias = weight_variable_0(bias_shape)
  89. return Dense(input_channels, out_channels, weight, bias)
  90. class ResidualBlock(Cell):
  91. expansion = 4
  92. def __init__(self,
  93. in_channels,
  94. out_channels,
  95. stride=1,
  96. down_sample=False):
  97. super(ResidualBlock, self).__init__()
  98. out_chls = out_channels // self.expansion
  99. self.conv1 = conv1x1(in_channels, out_chls, stride=1, padding=0)
  100. self.bn1 = bn_with_initialize(out_chls)
  101. self.conv2 = conv3x3(out_chls, out_chls, stride=stride, padding=1)
  102. self.bn2 = bn_with_initialize(out_chls)
  103. self.conv3 = conv1x1(out_chls, out_channels, stride=1, padding=0)
  104. self.bn3 = bn_with_initialize_last(out_channels)
  105. self.relu = P.ReLU()
  106. self.add = Add()
  107. def construct(self, x):
  108. identity = x
  109. out = self.conv1(x)
  110. out = self.bn1(out)
  111. out = self.relu(out)
  112. out = self.conv2(out)
  113. out = self.bn2(out)
  114. out = self.relu(out)
  115. out = self.conv3(out)
  116. out = self.bn3(out)
  117. out = self.add(out, identity)
  118. out = self.relu(out)
  119. return out
  120. class ResidualBlockWithDown(Cell):
  121. expansion = 4
  122. def __init__(self,
  123. in_channels,
  124. out_channels,
  125. stride=1,
  126. down_sample=False):
  127. super(ResidualBlockWithDown, self).__init__()
  128. out_chls = out_channels // self.expansion
  129. self.conv1 = conv1x1(in_channels, out_chls, stride=1, padding=0)
  130. self.bn1 = bn_with_initialize(out_chls)
  131. self.conv2 = conv3x3(out_chls, out_chls, stride=stride, padding=1)
  132. self.bn2 = bn_with_initialize(out_chls)
  133. self.conv3 = conv1x1(out_chls, out_channels, stride=1, padding=0)
  134. self.bn3 = bn_with_initialize_last(out_channels)
  135. self.relu = P.ReLU()
  136. self.downSample = down_sample
  137. self.conv_down_sample = conv1x1(
  138. in_channels, out_channels, stride=stride, padding=0)
  139. self.bn_down_sample = bn_with_initialize(out_channels)
  140. self.add = Add()
  141. def construct(self, x):
  142. identity = x
  143. out = self.conv1(x)
  144. out = self.bn1(out)
  145. out = self.relu(out)
  146. out = self.conv2(out)
  147. out = self.bn2(out)
  148. out = self.relu(out)
  149. out = self.conv3(out)
  150. out = self.bn3(out)
  151. identity = self.conv_down_sample(identity)
  152. identity = self.bn_down_sample(identity)
  153. out = self.add(out, identity)
  154. out = self.relu(out)
  155. return out
  156. class MakeLayer0(Cell):
  157. def __init__(self, block, layer_num, in_channels, out_channels, stride):
  158. super(MakeLayer0, self).__init__()
  159. self.a = ResidualBlockWithDown(
  160. in_channels, out_channels, stride=1, down_sample=True)
  161. self.b = block(out_channels, out_channels, stride=stride)
  162. self.c = block(out_channels, out_channels, stride=1)
  163. def construct(self, x):
  164. x = self.a(x)
  165. x = self.b(x)
  166. x = self.c(x)
  167. return x
  168. class MakeLayer1(Cell):
  169. def __init__(self, block, layer_num, in_channels, out_channels, stride):
  170. super(MakeLayer1, self).__init__()
  171. self.a = ResidualBlockWithDown(
  172. in_channels, out_channels, stride=stride, down_sample=True)
  173. self.b = block(out_channels, out_channels, stride=1)
  174. self.c = block(out_channels, out_channels, stride=1)
  175. self.d = block(out_channels, out_channels, stride=1)
  176. def construct(self, x):
  177. x = self.a(x)
  178. x = self.b(x)
  179. x = self.c(x)
  180. x = self.d(x)
  181. return x
  182. class MakeLayer2(Cell):
  183. def __init__(self, block, layer_num, in_channels, out_channels, stride):
  184. super(MakeLayer2, self).__init__()
  185. self.a = ResidualBlockWithDown(
  186. in_channels, out_channels, stride=stride, down_sample=True)
  187. self.b = block(out_channels, out_channels, stride=1)
  188. self.c = block(out_channels, out_channels, stride=1)
  189. self.d = block(out_channels, out_channels, stride=1)
  190. self.e = block(out_channels, out_channels, stride=1)
  191. self.f = block(out_channels, out_channels, stride=1)
  192. def construct(self, x):
  193. x = self.a(x)
  194. x = self.b(x)
  195. x = self.c(x)
  196. x = self.d(x)
  197. x = self.e(x)
  198. x = self.f(x)
  199. return x
  200. class MakeLayer3(Cell):
  201. def __init__(self, block, layer_num, in_channels, out_channels, stride):
  202. super(MakeLayer3, self).__init__()
  203. self.a = ResidualBlockWithDown(
  204. in_channels, out_channels, stride=stride, down_sample=True)
  205. self.b = block(out_channels, out_channels, stride=1)
  206. self.c = block(out_channels, out_channels, stride=1)
  207. def construct(self, x):
  208. x = self.a(x)
  209. x = self.b(x)
  210. x = self.c(x)
  211. return x
  212. class ResNet(Cell):
  213. def __init__(self, block, layer_num, num_classes=100):
  214. super(ResNet, self).__init__()
  215. self.conv1 = conv7x7(3, 64, stride=2, padding=3)
  216. self.bn1 = bn_with_initialize(64)
  217. self.relu = P.ReLU()
  218. self.maxpool = MaxPool2d(kernel_size=3, stride=2, pad_mode="same")
  219. self.layer1 = MakeLayer0(
  220. block, layer_num[0], in_channels=64, out_channels=256, stride=1)
  221. self.layer2 = MakeLayer1(
  222. block, layer_num[1], in_channels=256, out_channels=512, stride=2)
  223. self.layer3 = MakeLayer2(
  224. block, layer_num[2], in_channels=512, out_channels=1024, stride=2)
  225. self.layer4 = MakeLayer3(
  226. block, layer_num[3], in_channels=1024, out_channels=2048, stride=2)
  227. self.pool = nn.AvgPool2d(7, 1)
  228. self.fc = fc_with_initialize(512 * block.expansion, num_classes)
  229. self.flatten = Flatten()
  230. def construct(self, x):
  231. x = self.conv1(x)
  232. x = self.bn1(x)
  233. x = self.relu(x)
  234. x = self.maxpool(x)
  235. x = self.layer1(x)
  236. x = self.layer2(x)
  237. x = self.layer3(x)
  238. x = self.layer4(x)
  239. x = self.pool(x)
  240. x = self.flatten(x)
  241. x = self.fc(x)
  242. return x
  243. def resnet50(num_classes):
  244. return ResNet(ResidualBlock, [3, 4, 6, 3], num_classes)
  245. @pytest.mark.level0
  246. @pytest.mark.platform_x86_gpu_training
  247. @pytest.mark.env_onecard
  248. def test_trainTensor(num_classes=10, epoch=8, batch_size=1):
  249. net = resnet50(num_classes)
  250. lr = 0.1
  251. momentum = 0.9
  252. optimizer = Momentum(filter(lambda x: x.requires_grad,
  253. net.get_parameters()), lr, momentum)
  254. criterion = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
  255. net_with_criterion = WithLossCell(net, criterion)
  256. train_network = TrainOneStepCell(
  257. net_with_criterion, optimizer) # optimizer
  258. train_network.set_train()
  259. losses = []
  260. for i in range(0, epoch):
  261. data = Tensor(np.ones([batch_size, 3, 224, 224]
  262. ).astype(np.float32) * 0.01)
  263. label = Tensor(np.ones([batch_size]).astype(np.int32))
  264. loss = train_network(data, label)
  265. losses.append(loss)
  266. assert (losses[-1].asnumpy() < 1)
  267. @pytest.mark.level0
  268. @pytest.mark.platform_x86_gpu_training
  269. @pytest.mark.env_onecard
  270. def test_trainTensor_big_batchSize(num_classes=10, epoch=8, batch_size=338):
  271. net = resnet50(num_classes)
  272. lr = 0.1
  273. momentum = 0.9
  274. optimizer = Momentum(filter(lambda x: x.requires_grad,
  275. net.get_parameters()), lr, momentum)
  276. criterion = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
  277. net_with_criterion = WithLossCell(net, criterion)
  278. train_network = TrainOneStepCell(
  279. net_with_criterion, optimizer) # optimizer
  280. train_network.set_train()
  281. losses = []
  282. for i in range(0, epoch):
  283. data = Tensor(np.ones([batch_size, 3, 224, 224]
  284. ).astype(np.float32) * 0.01)
  285. label = Tensor(np.ones([batch_size]).astype(np.int32))
  286. loss = train_network(data, label)
  287. losses.append(loss)
  288. assert (losses[-1].asnumpy() < 1)
  289. @pytest.mark.level0
  290. @pytest.mark.platform_x86_gpu_training
  291. @pytest.mark.env_onecard
  292. def test_trainTensor_amp(num_classes=10, epoch=18, batch_size=16):
  293. net = resnet50(num_classes)
  294. lr = 0.1
  295. momentum = 0.9
  296. optimizer = Momentum(filter(lambda x: x.requires_grad,
  297. net.get_parameters()), lr, momentum)
  298. criterion = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
  299. train_network = amp.build_train_network(
  300. net, optimizer, criterion, level="O2")
  301. train_network.set_train()
  302. losses = []
  303. for i in range(0, epoch):
  304. data = Tensor(np.ones([batch_size, 3, 224, 224]
  305. ).astype(np.float32) * 0.01)
  306. label = Tensor(np.ones([batch_size]).astype(np.int32))
  307. loss = train_network(data, label)
  308. losses.append(loss)
  309. assert (losses[-1][0].asnumpy() < 1)
  310. assert not losses[-1][1].asnumpy()
  311. assert (losses[-1][2].asnumpy() > 1)
  312. @pytest.mark.level0
  313. @pytest.mark.platform_x86_gpu_training
  314. @pytest.mark.env_onecard
  315. def test_trainTensor_with_new_interface(num_classes=10, epoch=8, batch_size=1):
  316. net = resnet50(num_classes)
  317. criterion = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
  318. net_with_criterion = WithLossCell(net, criterion)
  319. net_with_criterion.set_train()
  320. weights = ParameterTuple(filter(lambda x: x.requires_grad, net.get_parameters()))
  321. optimizer = Momentum(weights, 0.1, 0.9)
  322. train_network = ForwardValueAndGrad(network=net_with_criterion, weights=weights, get_by_list=True, sens_param=True)
  323. losses = []
  324. for i in range(0, epoch):
  325. data = Tensor(np.ones([batch_size, 3, 224, 224]
  326. ).astype(np.float32) * 0.01)
  327. label = Tensor(np.ones([batch_size]).astype(np.int32))
  328. loss, grads = train_network(data, label, 1.0)
  329. grads = F.identity(grads)
  330. optimizer(grads)
  331. losses.append(loss)
  332. assert (losses[-1].asnumpy() < 0.8)
  333. @pytest.mark.level0
  334. @pytest.mark.platform_x86_gpu_training
  335. @pytest.mark.env_onecard
  336. def test_big_batchSize_with_new_interface(num_classes=10, epoch=8, batch_size=338):
  337. net = resnet50(num_classes)
  338. criterion = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
  339. net_with_criterion = WithLossCell(net, criterion)
  340. net_with_criterion.set_train()
  341. weights = ParameterTuple(filter(lambda x: x.requires_grad, net.get_parameters()))
  342. optimizer = Momentum(weights, 0.1, 0.9)
  343. train_network = ForwardValueAndGrad(network=net_with_criterion, weights=weights, get_by_list=True, sens_param=True)
  344. losses = []
  345. for i in range(0, epoch):
  346. data = Tensor(np.ones([batch_size, 3, 224, 224]
  347. ).astype(np.float32) * 0.01)
  348. label = Tensor(np.ones([batch_size]).astype(np.int32))
  349. loss, grads = train_network(data, label, 1.0)
  350. grads = F.identity(grads)
  351. optimizer(grads)
  352. losses.append(loss)
  353. assert (losses[-1].asnumpy() < 0.8)