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