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_net_simple.py 5.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. # Copyright 2022 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. from mindspore import Tensor, nn
  18. from mindspore.rewrite import SymbolTree, ScopedValue, ValueType, Node
  19. from mindspore.common.initializer import Normal
  20. from mindspore.common.api import _cell_graph_executor
  21. class SimpleNet(nn.Cell):
  22. def __init__(self, num_class=10, num_channel=1):
  23. super(SimpleNet, self).__init__()
  24. self.conv1 = nn.Conv2d(num_channel, 6, 5, pad_mode='valid')
  25. self.conv2 = nn.Conv2d(6, 16, 5, pad_mode='valid')
  26. self.relu = nn.ReLU()
  27. self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)
  28. self.flatten = nn.Flatten()
  29. self.fc1 = nn.Dense(16 * 5 * 5, 120, weight_init=Normal(0.02))
  30. self.fc2 = nn.Dense(120, 84, weight_init=Normal(0.02))
  31. self.fc3 = nn.Dense(84, num_class, weight_init=Normal(0.02))
  32. self.var = 10
  33. def construct(self, x):
  34. x = self.conv1(x)
  35. x = x
  36. y = self.var
  37. y = y * 5
  38. y = y and True
  39. x = self.relu(x)
  40. x = self.max_pool2d(x)
  41. x = self.conv2(x)
  42. x = self.relu(x)
  43. x = self.max_pool2d(x)
  44. x = self.flatten(x)
  45. x = self.relu(self.fc1(x))
  46. x = self.relu(self.fc2(x))
  47. x = self.fc3(x)
  48. return x
  49. class MyCell(nn.Cell):
  50. def __init__(self):
  51. super().__init__()
  52. self.conv = nn.Dense(5, 16)
  53. def construct(self, x, y):
  54. x = self.conv(x)
  55. x = mindspore.ops.Add()(x, y)
  56. return x
  57. def add_conv_before_flatten(stree: SymbolTree):
  58. new_conv_node = None
  59. for node in stree.nodes():
  60. if node.get_instance_type() == mindspore.nn.Flatten:
  61. position = stree.before(node)
  62. new_conv = nn.Conv2d(16, 16, 3)
  63. new_conv_node = Node.create_call_cell(new_conv, targets=['x_1'], name='new_conv',
  64. args=[ScopedValue.create_naming_value('self_max_po')])
  65. stree.insert(position, new_conv_node)
  66. break
  67. if new_conv_node is not None:
  68. for node in stree.nodes():
  69. if node.get_instance_type() == mindspore.nn.Flatten:
  70. inputs = node.get_inputs()
  71. assert len(inputs) == 1
  72. new_conv_node.set_arg_by_node(0, inputs[0])
  73. def add_my_cell_after_x_12(stree: SymbolTree):
  74. for node in stree.nodes():
  75. targets = node.get_targets()
  76. if targets is None:
  77. continue
  78. assert targets[0].type == ValueType.NamingValue
  79. target = str(targets[0])
  80. if target == "x_12":
  81. position = stree.after(node)
  82. custom_cell = MyCell()
  83. bias = Tensor(1, mindspore.int32)
  84. new_custom_node = Node.create_call_cell(custom_cell, targets=['nx2'],
  85. args=[ScopedValue.create_naming_value('nx3'),
  86. ScopedValue.create_variable_value(bias)], name='my_cell')
  87. stree.insert(position, new_custom_node)
  88. new_custom_node.set_arg(0, "x_12")
  89. break
  90. def erase_node_x_11(stree: SymbolTree):
  91. return_node = None
  92. for node in stree.nodes():
  93. if node.get_targets() is None:
  94. return_node = node
  95. break
  96. assert return_node is not None
  97. for node in stree.nodes():
  98. targets = node.get_targets()
  99. if targets is None:
  100. continue
  101. assert targets[0].type == ValueType.NamingValue
  102. target = str(targets[0])
  103. if target == "x_11":
  104. stree.set_output(0, "x_10")
  105. stree.erase_node(node)
  106. break
  107. def transform(stree: SymbolTree):
  108. add_conv_before_flatten(stree)
  109. add_my_cell_after_x_12(stree)
  110. erase_node_x_11(stree)
  111. def test_simple_net():
  112. """
  113. Feature: Module rewrite.
  114. Description: Resolve a simple network by rewrite and do some transform on it.
  115. Expectation: Result of rewrite can be compiled.
  116. """
  117. net = SimpleNet(10)
  118. stree = SymbolTree.create(net)
  119. transform(stree)
  120. print("------------------------------------ keys of global_vars: ", stree.get_handler().get_global_vars().keys())
  121. net_opt = stree.get_network()
  122. data_in = Tensor(np.ones([1, 1, 32, 32]), mindspore.float32)
  123. _cell_graph_executor.compile(net_opt, data_in)