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

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