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_conv_bn1_fusion.py 5.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. # Copyright 2019 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.nn as nn
  17. from mindspore.ops import operations as P
  18. from mindspore.common.initializer import initializer
  19. from mindspore import Tensor, Parameter, Model
  20. from mindspore.nn.loss import SoftmaxCrossEntropyWithLogits
  21. from mindspore.nn.optim import Momentum
  22. from mindspore.common.api import ms_function
  23. import mindspore.nn as wrap
  24. import mindspore.context as context
  25. context.set_context(device_target="Ascend", enable_task_sink=True)
  26. input_channel = 2048
  27. output_channel = 512
  28. num_class = 10
  29. batch_size = 32
  30. class MsWrapper(nn.Cell):
  31. def __init__(self, network):
  32. super(MsWrapper, self).__init__(auto_prefix=False)
  33. self._network = network
  34. @ms_function
  35. def construct(self, *args):
  36. return self._network(*args)
  37. def me_train_tensor(net, input_np, label_np, epoch_size=2):
  38. loss = SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True)
  39. opt = nn.Momentum(Tensor(np.array([0.1])), Tensor(np.array([0.9])), filter(lambda x: x.requires_grad, net.get_parameters()))
  40. context.set_context(mode=context.GRAPH_MODE)
  41. Model(net, loss, opt)
  42. _network = wrap.WithLossCell(net, loss)
  43. _train_net = MsWrapper(wrap.TrainOneStepCell(_network, opt))
  44. _train_net.set_train()
  45. for epoch in range(0, epoch_size):
  46. print(f"epoch %d"%(epoch))
  47. output = _train_net(Tensor(input_np), Tensor(label_np))
  48. print("********output***********")
  49. print(output.asnumpy())
  50. def test_conv_bn_add_relu_fusion():
  51. class Net(nn.Cell):
  52. def __init__(self):
  53. super(Net, self).__init__()
  54. self.conv = nn.Conv2d(input_channel, output_channel,
  55. kernel_size=1, stride=1, padding=0, has_bias=False, pad_mode="same")
  56. self.conv1 = nn.Conv2d(input_channel, output_channel,
  57. kernel_size=1, stride=1, padding=0, has_bias=False, pad_mode="same")
  58. self.bn = nn.BatchNorm2d(output_channel, momentum=0.1, eps=0.0001)
  59. self.add = P.TensorAdd()
  60. self.relu = P.ReLU()
  61. self.mean = P.ReduceMean(keep_dims=True)
  62. self.reshape = P.Reshape()
  63. self.dense = nn.Dense(output_channel, num_class)
  64. def construct(self, input_x):
  65. output = self.conv(input_x)
  66. output = self.bn(output)
  67. output = self.add(output, self.conv1(input_x))
  68. output = self.relu(output)
  69. output = self.mean(output, (-2, -1))
  70. output = self.reshape(output, (batch_size, output_channel))
  71. output = self.dense(output)
  72. return output
  73. net = Net()
  74. input_np = np.ones([batch_size, input_channel, 7, 7]).astype(np.float32) * 0.01
  75. label_np = np.ones([batch_size]).astype(np.int32)
  76. me_train_tensor(net, input_np, label_np)
  77. def test_conv_bn_relu_fusion():
  78. class Net(nn.Cell):
  79. def __init__(self):
  80. super(Net, self).__init__()
  81. self.conv = nn.Conv2d(input_channel, output_channel,
  82. kernel_size=1, stride=1, padding=0, has_bias=False, pad_mode="same")
  83. self.bn = nn.BatchNorm2d(output_channel, momentum=0.1, eps=0.0001)
  84. self.relu = P.ReLU()
  85. self.mean = P.ReduceMean(keep_dims=True)
  86. self.reshape = P.Reshape()
  87. self.dense = nn.Dense(output_channel, num_class)
  88. def construct(self, input_x):
  89. output = self.conv(input_x)
  90. output = self.bn(output)
  91. output = self.relu(output)
  92. output = self.mean(output, (-2, -1))
  93. output = self.reshape(output, (batch_size, output_channel))
  94. output = self.dense(output)
  95. return output
  96. net = Net()
  97. input_np = np.ones([batch_size, input_channel, 7, 7]).astype(np.float32) * 0.01
  98. label_np = np.ones([batch_size]).astype(np.int32)
  99. me_train_tensor(net, input_np, label_np)
  100. def test_conv_bn_fusion():
  101. class Net(nn.Cell):
  102. def __init__(self):
  103. super(Net, self).__init__()
  104. self.conv = nn.Conv2d(input_channel, output_channel,
  105. kernel_size=1, stride=1, padding=0, has_bias=False, pad_mode="same")
  106. self.bn = nn.BatchNorm2d(output_channel, momentum=0.1, eps=0.0001)
  107. self.mean = P.ReduceMean(keep_dims=True)
  108. self.reshape = P.Reshape()
  109. self.dense = nn.Dense(output_channel, num_class)
  110. def construct(self, input_x):
  111. output = self.conv(input_x)
  112. output = self.bn(output)
  113. output = self.mean(output, (-2, -1))
  114. output = self.reshape(output, (batch_size, output_channel))
  115. output = self.dense(output)
  116. return output
  117. net = Net()
  118. input_np = np.ones([batch_size, input_channel, 7, 7]).astype(np.float32) * 0.01
  119. label_np = np.ones([batch_size]).astype(np.int32)
  120. me_train_tensor(net, input_np, label_np)