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.5 kB

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