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

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