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 2.3 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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.common.python_pass_register import registe_pass, PyPassManager
  22. from mindspore.common.api import _generate_pip_args
  23. from mindspore._c_expression import generate_key, Executor_
  24. context.set_context(mode=context.GRAPH_MODE)
  25. def get_func_graph(obj, *args, phase="predict"):
  26. args_names, args_list = _generate_pip_args(obj, *args)
  27. dic = dict(zip(args_names, args_list))
  28. key = generate_key(phase, dic)
  29. phase_prefix = str(key[1])
  30. if phase == 'export':
  31. phase = phase + '.' + phase_prefix + '.' + str(obj.create_time)
  32. else:
  33. phase = phase_prefix + phase + '.' + str(obj.create_time)
  34. _executor = Executor_.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. @registe_pass(run_only_once=True)
  44. def softmax_relu_pass():
  45. softmax = P.Softmax()
  46. relu = P.ReLU()
  47. def pattern(x):
  48. x = softmax(x)
  49. return x
  50. def target(x):
  51. x = relu(x)
  52. return x
  53. return pattern, target
  54. transformed_repr = get_func_graph(softmax_model, inputs).get_return().expanded_str(2)
  55. ppm = PyPassManager()
  56. ppm.unregiste(softmax_relu_pass)
  57. assert "ReLU" in transformed_repr
  58. assert "Softmax" not in transformed_repr