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_export.py 10 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. """Test network export."""
  15. import os
  16. import numpy as np
  17. import pytest
  18. import mindspore.context as context
  19. import mindspore.nn as nn
  20. from mindspore import Tensor
  21. from mindspore.nn import Dense
  22. from mindspore.nn.cell import Cell
  23. from mindspore.nn.layer.basic import Flatten
  24. from mindspore.nn.layer.conv import Conv2d
  25. from mindspore.nn.layer.normalization import BatchNorm2d
  26. from mindspore.nn.layer.pooling import MaxPool2d
  27. from mindspore.ops import operations as P
  28. from mindspore.ops.operations import TensorAdd
  29. from mindspore.train.serialization import export
  30. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  31. def random_normal_init(shape, mean=0.0, stddev=0.01, seed=None):
  32. init_value = np.ones(shape).astype(np.float32) * 0.01
  33. return Tensor(init_value)
  34. def variance_scaling_raw(shape):
  35. variance_scaling_value = np.ones(shape).astype(np.float32) * 0.01
  36. return Tensor(variance_scaling_value)
  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=1):
  44. """3x3 convolution """
  45. weight_shape = (out_channels, in_channels, 3, 3)
  46. weight = variance_scaling_raw(weight_shape)
  47. return Conv2d(in_channels, out_channels,
  48. kernel_size=3, stride=stride, weight_init=weight, has_bias=False, pad_mode="same")
  49. def conv1x1(in_channels, out_channels, stride=1, padding=0):
  50. """1x1 convolution"""
  51. weight_shape = (out_channels, in_channels, 1, 1)
  52. weight = variance_scaling_raw(weight_shape)
  53. return Conv2d(in_channels, out_channels,
  54. kernel_size=1, stride=stride, weight_init=weight, has_bias=False, pad_mode="same")
  55. def conv7x7(in_channels, out_channels, stride=1, padding=0):
  56. """1x1 convolution"""
  57. weight_shape = (out_channels, in_channels, 7, 7)
  58. weight = variance_scaling_raw(weight_shape)
  59. return Conv2d(in_channels, out_channels,
  60. kernel_size=7, stride=stride, weight_init=weight, has_bias=False, pad_mode="same")
  61. def bn_with_initialize(out_channels):
  62. shape = (out_channels)
  63. mean = weight_variable_0(shape)
  64. var = weight_variable_1(shape)
  65. beta = weight_variable_0(shape)
  66. gamma = weight_variable_1(shape)
  67. bn = BatchNorm2d(out_channels, momentum=0.1, eps=0.0001, gamma_init=gamma,
  68. beta_init=beta, moving_mean_init=mean, moving_var_init=var)
  69. return bn
  70. def bn_with_initialize_last(out_channels):
  71. shape = (out_channels)
  72. mean = weight_variable_0(shape)
  73. var = weight_variable_1(shape)
  74. beta = weight_variable_0(shape)
  75. gamma = weight_variable_0(shape)
  76. bn = BatchNorm2d(out_channels, momentum=0.1, eps=0.0001, gamma_init=gamma,
  77. beta_init=beta, moving_mean_init=mean, moving_var_init=var)
  78. return bn
  79. def fc_with_initialize(input_channels, out_channels):
  80. weight_shape = (out_channels, input_channels)
  81. bias_shape = (out_channels)
  82. weight = random_normal_init(weight_shape)
  83. bias = weight_variable_0(bias_shape)
  84. return Dense(input_channels, out_channels, weight, bias)
  85. class ResidualBlock(Cell):
  86. expansion = 4
  87. def __init__(self,
  88. in_channels,
  89. out_channels,
  90. stride=1,
  91. down_sample=False):
  92. super(ResidualBlock, self).__init__()
  93. out_chls = out_channels // self.expansion
  94. self.conv1 = conv1x1(in_channels, out_chls, stride=1, padding=0)
  95. self.bn1 = bn_with_initialize(out_chls)
  96. self.conv2 = conv3x3(out_chls, out_chls, stride=stride, padding=1)
  97. self.bn2 = bn_with_initialize(out_chls)
  98. self.conv3 = conv1x1(out_chls, out_channels, stride=1, padding=0)
  99. self.bn3 = bn_with_initialize_last(out_channels)
  100. self.relu = P.ReLU()
  101. self.add = TensorAdd()
  102. def construct(self, x):
  103. identity = x
  104. out = self.conv1(x)
  105. out = self.bn1(out)
  106. out = self.relu(out)
  107. out = self.conv2(out)
  108. out = self.bn2(out)
  109. out = self.relu(out)
  110. out = self.conv3(out)
  111. out = self.bn3(out)
  112. out = self.add(out, identity)
  113. out = self.relu(out)
  114. return out
  115. class ResidualBlockWithDown(Cell):
  116. expansion = 4
  117. def __init__(self,
  118. in_channels,
  119. out_channels,
  120. stride=1,
  121. down_sample=False):
  122. super(ResidualBlockWithDown, self).__init__()
  123. out_chls = out_channels // self.expansion
  124. self.conv1 = conv1x1(in_channels, out_chls, stride=1, padding=0)
  125. self.bn1 = bn_with_initialize(out_chls)
  126. self.conv2 = conv3x3(out_chls, out_chls, stride=stride, padding=1)
  127. self.bn2 = bn_with_initialize(out_chls)
  128. self.conv3 = conv1x1(out_chls, out_channels, stride=1, padding=0)
  129. self.bn3 = bn_with_initialize_last(out_channels)
  130. self.relu = P.ReLU()
  131. self.downSample = down_sample
  132. self.conv_down_sample = conv1x1(
  133. in_channels, out_channels, stride=stride, padding=0)
  134. self.bn_down_sample = bn_with_initialize(out_channels)
  135. self.add = TensorAdd()
  136. def construct(self, x):
  137. identity = x
  138. out = self.conv1(x)
  139. out = self.bn1(out)
  140. out = self.relu(out)
  141. out = self.conv2(out)
  142. out = self.bn2(out)
  143. out = self.relu(out)
  144. out = self.conv3(out)
  145. out = self.bn3(out)
  146. identity = self.conv_down_sample(identity)
  147. identity = self.bn_down_sample(identity)
  148. out = self.add(out, identity)
  149. out = self.relu(out)
  150. return out
  151. class MakeLayer0(Cell):
  152. def __init__(self, block, layer_num, in_channels, out_channels, stride):
  153. super(MakeLayer0, self).__init__()
  154. self.a = ResidualBlockWithDown(
  155. in_channels, out_channels, stride=1, down_sample=True)
  156. self.b = block(out_channels, out_channels, stride=stride)
  157. self.c = 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. return x
  163. class MakeLayer1(Cell):
  164. def __init__(self, block, layer_num, in_channels, out_channels, stride):
  165. super(MakeLayer1, self).__init__()
  166. self.a = ResidualBlockWithDown(
  167. 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(
  181. 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(Cell):
  196. def __init__(self, block, layer_num, in_channels, out_channels, stride):
  197. super(MakeLayer3, self).__init__()
  198. self.a = ResidualBlockWithDown(
  199. in_channels, out_channels, stride=stride, down_sample=True)
  200. self.b = block(out_channels, out_channels, stride=1)
  201. self.c = block(out_channels, out_channels, stride=1)
  202. def construct(self, x):
  203. x = self.a(x)
  204. x = self.b(x)
  205. x = self.c(x)
  206. return x
  207. class ResNet(Cell):
  208. def __init__(self, block, layer_num, num_classes=100):
  209. super(ResNet, self).__init__()
  210. self.conv1 = conv7x7(3, 64, stride=2, padding=3)
  211. self.bn1 = bn_with_initialize(64)
  212. self.relu = P.ReLU()
  213. self.maxpool = MaxPool2d(kernel_size=3, stride=2, pad_mode="same")
  214. self.layer1 = MakeLayer0(
  215. block, layer_num[0], in_channels=64, out_channels=256, stride=1)
  216. self.layer2 = MakeLayer1(
  217. block, layer_num[1], in_channels=256, out_channels=512, stride=2)
  218. self.layer3 = MakeLayer2(
  219. block, layer_num[2], in_channels=512, out_channels=1024, stride=2)
  220. self.layer4 = MakeLayer3(
  221. block, layer_num[3], in_channels=1024, out_channels=2048, stride=2)
  222. self.pool = nn.AvgPool2d(7, 1)
  223. self.fc = fc_with_initialize(512 * block.expansion, num_classes)
  224. self.flatten = Flatten()
  225. def construct(self, x):
  226. x = self.conv1(x)
  227. x = self.bn1(x)
  228. x = self.relu(x)
  229. x = self.maxpool(x)
  230. x = self.layer1(x)
  231. x = self.layer2(x)
  232. x = self.layer3(x)
  233. x = self.layer4(x)
  234. x = self.pool(x)
  235. x = self.flatten(x)
  236. x = self.fc(x)
  237. return x
  238. def resnet50(num_classes):
  239. return ResNet(ResidualBlock, [3, 4, 6, 3], num_classes)
  240. @pytest.mark.level0
  241. @pytest.mark.platform_x86_ascend_training
  242. @pytest.mark.platform_arm_ascend_training
  243. @pytest.mark.env_onecard
  244. def test_export_resnet_air():
  245. net = resnet50(10)
  246. inputs = Tensor(np.ones([1, 3, 224, 224]).astype(np.float32) * 0.01)
  247. file_name = "resnet.air"
  248. export(net, inputs, file_name=file_name, file_format='AIR')
  249. assert os.path.exists(file_name)
  250. os.remove(file_name)