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_onnx.py 7.5 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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. """ut for model serialize(save/load)"""
  16. import os
  17. import stat
  18. import numpy as np
  19. import pytest
  20. import mindspore.nn as nn
  21. from mindspore import context
  22. from mindspore.common.parameter import Parameter
  23. from mindspore.common.tensor import Tensor
  24. from mindspore.ops import operations as P
  25. from mindspore.train.serialization import export
  26. context.set_context(mode=context.GRAPH_MODE)
  27. def is_enable_onnxruntime():
  28. val = os.getenv("ENABLE_ONNXRUNTIME", "False")
  29. if val in ('ON', 'on', 'TRUE', 'True', 'true'):
  30. return True
  31. return False
  32. run_on_onnxruntime = pytest.mark.skipif(not is_enable_onnxruntime(), reason="Only support running on onnxruntime")
  33. def teardown_module():
  34. cur_dir = os.path.dirname(os.path.realpath(__file__))
  35. for filename in os.listdir(cur_dir):
  36. if filename.find('ms_output_') == 0 and filename.find('.pb') > 0:
  37. # delete temp files generated by run ut
  38. os.chmod(filename, stat.S_IWRITE)
  39. os.remove(filename)
  40. class BatchNormTester(nn.Cell):
  41. """used to test exporting network in training mode in onnx format"""
  42. def __init__(self, num_features):
  43. super(BatchNormTester, self).__init__()
  44. self.bn = nn.BatchNorm2d(num_features)
  45. def construct(self, x):
  46. return self.bn(x)
  47. def test_batchnorm_train_onnx_export():
  48. """test onnx export interface does not modify trainable flag of a network"""
  49. input_ = Tensor(np.ones([1, 3, 32, 32]).astype(np.float32) * 0.01)
  50. net = BatchNormTester(3)
  51. net.set_train()
  52. if not net.training:
  53. raise ValueError('netowrk is not in training mode')
  54. onnx_file = 'batch_norm'
  55. export(net, input_, file_name=onnx_file, file_format='ONNX')
  56. if not net.training:
  57. raise ValueError('netowrk is not in training mode')
  58. file_name = "batch_norm.onnx"
  59. assert os.path.exists(file_name)
  60. os.chmod(file_name, stat.S_IWRITE)
  61. os.remove(file_name)
  62. class LeNet5(nn.Cell):
  63. """LeNet5 definition"""
  64. def __init__(self):
  65. super(LeNet5, self).__init__()
  66. self.conv1 = nn.Conv2d(1, 6, 5, pad_mode='valid')
  67. self.conv2 = nn.Conv2d(6, 16, 5, pad_mode='valid')
  68. self.fc1 = nn.Dense(16 * 5 * 5, 120)
  69. self.fc2 = nn.Dense(120, 84)
  70. self.fc3 = nn.Dense(84, 10)
  71. self.relu = nn.ReLU()
  72. self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)
  73. self.flatten = P.Flatten()
  74. def construct(self, x):
  75. x = self.max_pool2d(self.relu(self.conv1(x)))
  76. x = self.max_pool2d(self.relu(self.conv2(x)))
  77. x = self.flatten(x)
  78. x = self.relu(self.fc1(x))
  79. x = self.relu(self.fc2(x))
  80. x = self.fc3(x)
  81. return x
  82. class DefinedNet(nn.Cell):
  83. """simple Net definition with maxpoolwithargmax."""
  84. def __init__(self, num_classes=10):
  85. super(DefinedNet, self).__init__()
  86. self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=0, weight_init="zeros")
  87. self.bn1 = nn.BatchNorm2d(64)
  88. self.relu = nn.ReLU()
  89. self.maxpool = P.MaxPoolWithArgmax(pad_mode="same", kernel_size=2, strides=2)
  90. self.flatten = nn.Flatten()
  91. self.fc = nn.Dense(int(56 * 56 * 64), num_classes)
  92. def construct(self, x):
  93. x = self.conv1(x)
  94. x = self.bn1(x)
  95. x = self.relu(x)
  96. x, argmax = self.maxpool(x)
  97. x = self.flatten(x)
  98. x = self.fc(x)
  99. return x
  100. class DepthwiseConv2dAndReLU6(nn.Cell):
  101. """Net for testing DepthwiseConv2d and ReLU6"""
  102. def __init__(self, input_channel, kernel_size):
  103. super(DepthwiseConv2dAndReLU6, self).__init__()
  104. weight_shape = [1, input_channel, kernel_size, kernel_size]
  105. from mindspore.common.initializer import initializer
  106. self.weight = Parameter(initializer('ones', weight_shape), name='weight')
  107. self.depthwise_conv = P.DepthwiseConv2dNative(channel_multiplier=1, kernel_size=(kernel_size, kernel_size))
  108. self.relu6 = nn.ReLU6()
  109. def construct(self, x):
  110. x = self.depthwise_conv(x, self.weight)
  111. x = self.relu6(x)
  112. return x
  113. class DeepFMOpNet(nn.Cell):
  114. """Net definition with Gatherv2 and Tile and Square."""
  115. def __init__(self):
  116. super(DeepFMOpNet, self).__init__()
  117. self.gather = P.GatherV2()
  118. self.square = P.Square()
  119. self.tile = P.Tile()
  120. def construct(self, x, y):
  121. x = self.tile(x, (1000, 1))
  122. x = self.square(x)
  123. x = self.gather(x, y, 0)
  124. return x
  125. def gen_tensor(shape, dtype=np.float32):
  126. return Tensor(np.ones(shape).astype(dtype))
  127. net_cfgs = [
  128. ('lenet', LeNet5(), gen_tensor([1, 1, 32, 32])),
  129. ('maxpoolwithargmax', DefinedNet(), gen_tensor([1, 3, 224, 224])),
  130. ('depthwiseconv_relu6', DepthwiseConv2dAndReLU6(3, kernel_size=3), gen_tensor([1, 3, 32, 32])),
  131. ('deepfm_ops', DeepFMOpNet(), (gen_tensor([1, 1]), gen_tensor([1000, 1], dtype=np.int32)))
  132. ]
  133. def get_id(cfg):
  134. _ = cfg
  135. return list(map(lambda x: x[0], net_cfgs))
  136. # use `pytest test_onnx.py::test_onnx_export[name]` or `pytest test_onnx.py::test_onnx_export -k name` to run single ut
  137. @pytest.mark.parametrize('name, net, inp', net_cfgs, ids=get_id(net_cfgs))
  138. def test_onnx_export(name, net, inp):
  139. if isinstance(inp, (tuple, list)):
  140. export(net, *inp, file_name=name, file_format='ONNX')
  141. else:
  142. export(net, inp, file_name=name, file_format='ONNX')
  143. file_file = name + ".onnx"
  144. assert os.path.exists(file_file)
  145. os.chmod(file_file, stat.S_IWRITE)
  146. os.remove(file_file)
  147. @run_on_onnxruntime
  148. @pytest.mark.parametrize('name, net, inp', net_cfgs, ids=get_id(net_cfgs))
  149. def test_onnx_export_load_run(name, net, inp):
  150. export(net, inp, file_name=name, file_format='ONNX')
  151. import onnx
  152. import onnxruntime as ort
  153. print('--------------------- onnx load ---------------------')
  154. # Load the ONNX model
  155. model = onnx.load(onnx_file)
  156. # Check that the IR is well formed
  157. onnx.checker.check_model(model)
  158. # Print a human readable representation of the graph
  159. g = onnx.helper.printable_graph(model.graph)
  160. print(g)
  161. print('------------------ onnxruntime run ------------------')
  162. ort_session = ort.InferenceSession(onnx_file)
  163. input_map = {'x': inp.asnumpy()}
  164. # provide only input x to run model
  165. outputs = ort_session.run(None, input_map)
  166. print(outputs[0])
  167. # overwrite default weight to run model
  168. for item in net.trainable_params():
  169. default_value = item.data.asnumpy()
  170. input_map[item.name] = np.ones(default_value.shape, dtype=default_value.dtype)
  171. outputs = ort_session.run(None, input_map)
  172. print(outputs[0])
  173. file_name = name + ".onnx"
  174. assert os.path.exists(file_name)
  175. os.chmod(file_name, stat.S_IWRITE)
  176. os.remove(file_name)