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_python_pass.py 12 kB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. import numpy as np
  16. import mindspore
  17. import mindspore.nn as nn
  18. from mindspore import context
  19. from mindspore.common.tensor import Tensor
  20. from mindspore.ops import operations as P
  21. from mindspore.ops import _constants as Constants
  22. from mindspore.graph_utils.python_pass import register_pass, unregister_pass, set_renorm, gen_new_parameter, \
  23. cancel_new_parameter, set_reopt
  24. from mindspore._c_expression import GraphExecutor_
  25. from mindspore.graph_utils.graph_pattern import OneOf, Prim, Call, NoneOf, Any, NewTensor, NewParameter, Imm
  26. context.set_context(mode=context.GRAPH_MODE)
  27. def get_func_graph(obj, *args, phase="validate"):
  28. _executor = GraphExecutor_.get_instance()
  29. key = _executor.generate_arguments_key(args, False)
  30. obj.arguments_key = str(key)
  31. phase = phase + '.' + str(obj.create_time) + '.' + str(id(obj)) + '.' + obj.arguments_key
  32. _executor.compile(obj, args, phase, False)
  33. return _executor.get_func_graph(phase)
  34. def test_softmax_relu():
  35. """
  36. Use python pass to transform from Softmax to ReLU.
  37. """
  38. inputs = Tensor(np.ones([42]), mindspore.float16)
  39. softmax_model = nn.Softmax()
  40. @register_pass(run_only_once=True)
  41. def softmax_relu_pass():
  42. x = Any()
  43. pattern = Call(P.Softmax(), [x])
  44. target = Call(P.ReLU(), [x])
  45. return pattern, target
  46. transformed_repr = get_func_graph(softmax_model, inputs).get_return().expanded_str(2)
  47. unregister_pass(softmax_relu_pass)
  48. assert "ReLU" in transformed_repr
  49. assert "Softmax" not in transformed_repr
  50. def test_prim():
  51. inputs = Tensor(np.ones([42]), mindspore.float16)
  52. softmax_model = nn.Softmax()
  53. @register_pass(run_only_once=True)
  54. def softmax_relu_pass():
  55. x = Any()
  56. sigmoid_softmax_pattern = Prim([P.Sigmoid(), P.Softmax()])
  57. pattern = Call(sigmoid_softmax_pattern, [x])
  58. target = Call(P.ReLU(), [x])
  59. return pattern, target
  60. transformed_repr = get_func_graph(softmax_model, inputs).get_return().expanded_str(3)
  61. unregister_pass(softmax_relu_pass)
  62. assert "ReLU" in transformed_repr
  63. assert "Softmax" not in transformed_repr
  64. def test_softmax_relu_sigmoid():
  65. """
  66. Use python pass to transform from Softmax(x) to ReLU(Sigmoid(x)).
  67. NOTE:
  68. Sigmoid pattern only exists in the target.
  69. """
  70. inputs = Tensor(np.ones([42]), mindspore.float16)
  71. softmax_model = nn.Softmax()
  72. @register_pass(run_only_once=True)
  73. def softmax_relu_pass():
  74. x = Any()
  75. softmax_pattern = Prim(P.Softmax())
  76. pattern = Call(softmax_pattern, [x])
  77. sigmoid_pattern = Prim(P.Sigmoid())
  78. call_sigmoid = Call(sigmoid_pattern, [x])
  79. relu_pattern = Prim(P.ReLU())
  80. target = Call(relu_pattern, [call_sigmoid])
  81. return pattern, target
  82. transformed_repr = get_func_graph(softmax_model, inputs).get_return().expanded_str(3)
  83. unregister_pass(softmax_relu_pass)
  84. assert "ReLU" in transformed_repr
  85. assert "Sigmoid" in transformed_repr
  86. assert "Softmax" not in transformed_repr
  87. def test_isin_pattern_0():
  88. """
  89. Test IsIn pattern which expresses the IsIn/OneOf semantics.
  90. """
  91. inputs = Tensor(np.ones([42]), mindspore.float16)
  92. softmax_model = nn.Softmax()
  93. @register_pass(run_only_once=True)
  94. def softmax_relu_pass():
  95. x = Any()
  96. softmax_pattern = Prim(P.Softmax())
  97. call_softmax = Call(softmax_pattern, [x])
  98. relu_pattern = Prim(P.ReLU())
  99. call_relu = Call(relu_pattern, [x])
  100. pattern = OneOf([call_softmax, call_relu])
  101. relu6_pattern = Prim(P.ReLU6())
  102. target = Call(relu6_pattern, [x])
  103. return pattern, target
  104. transformed_repr = get_func_graph(softmax_model, inputs).get_return().expanded_str(2)
  105. unregister_pass(softmax_relu_pass)
  106. assert "ReLU6" in transformed_repr
  107. assert "Softmax" not in transformed_repr
  108. def test_isin_pattern_1():
  109. """
  110. Test IsIn. IsIn is used as nested inputs for the target in this case.
  111. """
  112. inputs = Tensor(np.ones([42]), mindspore.float16)
  113. softmax_model = nn.Softmax()
  114. @register_pass(run_only_once=True)
  115. def softmax_neg_pass():
  116. x = Any()
  117. softmax_pattern = Prim(P.Softmax())
  118. call_softmax = Call(softmax_pattern, [x])
  119. relu_pattern = Prim(P.ReLU())
  120. call_relu = Call(relu_pattern, [x])
  121. pattern = OneOf([call_softmax, call_relu])
  122. neg_ops = Prim(P.Neg())
  123. target = Call(neg_ops, [pattern])
  124. return pattern, target
  125. transformed_repr = get_func_graph(softmax_model, inputs).get_return().expanded_str(4)
  126. unregister_pass(softmax_neg_pass)
  127. assert "Neg" in transformed_repr
  128. assert "Softmax" in transformed_repr
  129. def test_isnot_pattern_0():
  130. """
  131. Test IsNot pattern which expresses the IsNot semantics.
  132. Case: IsNot pass failed to match
  133. """
  134. set_renorm(False)
  135. set_reopt(False)
  136. class ConvBN(nn.Cell):
  137. def __init__(self):
  138. super(ConvBN, self).__init__()
  139. self.conv = P.Conv2D(32, 3)
  140. self.conv_weight = Tensor(np.ones([32, 32, 3, 3]), mindspore.float32)
  141. self.scale = Tensor(np.ones([32]), mindspore.float32)
  142. self.bias = Tensor(np.ones([32]), mindspore.float32)
  143. self.mean = Tensor(np.ones([32]), mindspore.float32)
  144. self.variance = Tensor(np.ones([32]), mindspore.float32)
  145. self.bn = P.BatchNorm()
  146. def construct(self, x):
  147. x = self.conv(x, self.conv_weight)
  148. x = self.bn(x, self.scale, self.bias, self.mean, self.variance)
  149. return x
  150. inputs = Tensor(np.random.normal(0, 1, (10, 32, 32, 32)), mindspore.float32)
  151. conv_bn_model = ConvBN()
  152. @register_pass(requires_grad=False, run_only_once=True)
  153. def single_bn_pass():
  154. """
  155. Sub a BN which does NOT take Conv as inputs to ReLU6.
  156. """
  157. conv2d_prim = Prim("Conv2D")
  158. conv2d = Call(conv2d_prim)
  159. pattern_0 = NoneOf(conv2d)
  160. pattern = Call(P.BatchNorm(), [pattern_0])
  161. target = Call(P.ReLU6(), [pattern_0])
  162. return pattern, target
  163. @register_pass(requires_grad=False, run_only_once=True)
  164. def bn_pass():
  165. """
  166. Sub a BN to Softmax.
  167. """
  168. pattern = Call(P.BatchNorm())
  169. target = Call(P.Softmax())
  170. return pattern, target
  171. transformed_repr = get_func_graph(conv_bn_model, inputs).get_return().expanded_str(5)
  172. unregister_pass(single_bn_pass)
  173. unregister_pass(bn_pass)
  174. assert "ReLU6" not in transformed_repr
  175. assert "Softmax" in transformed_repr
  176. set_renorm(True)
  177. def test_isnot_pattern_1():
  178. """
  179. Test IsNot pattern which expresses the IsNot semantics.
  180. Case: IsNot pattern matches with the graph
  181. """
  182. inputs = Tensor(np.ones([42]), mindspore.float16)
  183. softmax_model = nn.Softmax()
  184. @register_pass(run_only_once=True)
  185. def single_bn_pass():
  186. """
  187. Sub a BN which does NOT take MatMul as inputs to ReLU6.
  188. """
  189. matmul = Prim("MatMul")
  190. pattern_0 = NoneOf(matmul)
  191. softmax = P.Softmax()
  192. pattern = Call(softmax, [pattern_0])
  193. relu6 = P.ReLU6()
  194. target = Call(relu6, [pattern_0])
  195. return pattern, target
  196. transformed_repr = get_func_graph(softmax_model, inputs).get_return().expanded_str(5)
  197. unregister_pass(single_bn_pass)
  198. assert "ReLU6" in transformed_repr
  199. assert "Softmax" not in transformed_repr
  200. def test_newtensor_pattern():
  201. """
  202. Test NewTensor pattern in the target
  203. """
  204. set_renorm(False)
  205. set_reopt(False)
  206. inputs = Tensor(np.ones([42]), mindspore.float16)
  207. softmax_model = nn.Softmax()
  208. @register_pass(requires_grad=False, run_only_once=True)
  209. def softmax_addn_pass():
  210. x = Any()
  211. pattern = Call(P.Softmax(), [x])
  212. weight_tensor = Tensor(np.zeros([42]), mindspore.float16)
  213. new_weight = NewTensor(weight_tensor)
  214. target = Call(P.AddN(), [x, new_weight])
  215. return pattern, target
  216. transformed_repr = get_func_graph(softmax_model, inputs).get_return().expanded_str(2)
  217. unregister_pass(softmax_addn_pass)
  218. assert "AddN" in transformed_repr
  219. assert "Softmax" not in transformed_repr
  220. set_renorm(True)
  221. def test_newparameter_pattern():
  222. """
  223. Test NewParameter pattern in the target
  224. """
  225. inputs = Tensor(np.ones([42]), mindspore.float16)
  226. softmax_model = nn.Softmax()
  227. set_renorm(False)
  228. set_reopt(False)
  229. @register_pass(requires_grad=False, run_only_once=True)
  230. def softmax_addn_pass():
  231. x = Any()
  232. pattern = Call(P.Softmax(), [x])
  233. default_tensor0 = Tensor(np.ones((4, 4)), mindspore.float32)
  234. default_tensor1 = Tensor(np.ones((4, 4)), mindspore.float32)
  235. new_para_0 = NewParameter("Merlin", default_tensor0)
  236. new_para_1 = NewParameter("Arthur", default_tensor1)
  237. target_0 = Call(P.MatMul(), [new_para_0, new_para_1])
  238. target = Call("MakeTuple", [target_0])
  239. return pattern, target
  240. transformed_repr = get_func_graph(softmax_model, inputs).get_return().expanded_str(5)
  241. unregister_pass(softmax_addn_pass)
  242. assert "MatMul" in transformed_repr
  243. assert "MakeTuple" in transformed_repr
  244. assert "Softmax" not in transformed_repr
  245. def test_imm_target():
  246. """
  247. Test NewParameter pattern in the target
  248. """
  249. inputs = Tensor(np.ones([42]), mindspore.float16)
  250. softmax_model = nn.Softmax()
  251. set_renorm(False)
  252. set_reopt(False)
  253. @register_pass(requires_grad=False, run_only_once=True)
  254. def softmax_pass():
  255. x = Any()
  256. pattern = Call(P.Softmax(), [x])
  257. imm = Imm(0)
  258. target_0 = Call("MakeTuple", [pattern])
  259. target = Call(Constants.kTupleGetItem, [target_0, imm])
  260. return pattern, target
  261. transformed_repr = get_func_graph(softmax_model, inputs).get_return().expanded_str(5)
  262. unregister_pass(softmax_pass)
  263. assert "MakeTuple" in transformed_repr
  264. assert Constants.kTupleGetItem in transformed_repr
  265. assert "Softmax" in transformed_repr
  266. def test_gen_new_parameter():
  267. """
  268. Test gen_new_parameter
  269. """
  270. inputs = Tensor(np.ones([42]), mindspore.float16)
  271. softmax_model = nn.Softmax()
  272. default_tensor = Tensor(np.ones((4, 4)), mindspore.float32)
  273. new_para = NewParameter("Merlin", default_tensor)
  274. set_renorm(False)
  275. set_reopt(False)
  276. gen_new_parameter(new_para)
  277. @register_pass(requires_grad=False, run_only_once=True)
  278. def softmax_make_tuple_pass():
  279. x = Any()
  280. softmax = P.Softmax()
  281. pattern = Call(softmax, [x])
  282. target = Call("MakeTuple", [pattern, new_para])
  283. return pattern, target
  284. transformed_repr = get_func_graph(softmax_model, inputs).get_return().expanded_str(5)
  285. assert "Merlin" in transformed_repr
  286. unregister_pass(softmax_make_tuple_pass)
  287. cancel_new_parameter(new_para)
  288. transformed_repr = get_func_graph(softmax_model, inputs).get_return().expanded_str(5)
  289. assert "Merlin" not in transformed_repr