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.8 kB

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