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_pynative_hook.py 6.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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 pytest
  16. import numpy as np
  17. import mindspore.nn as nn
  18. import mindspore.common.dtype as mstype
  19. from mindspore import Tensor
  20. from mindspore import context
  21. from mindspore import ParameterTuple
  22. from mindspore.nn import Momentum
  23. from mindspore.nn import WithLossCell
  24. from mindspore.ops import composite as C
  25. from mindspore.ops import operations as P
  26. from mindspore.common.initializer import TruncatedNormal
  27. context.set_context(mode=context.PYNATIVE_MODE, device_target="Ascend")
  28. grad_all = C.GradOperation(get_all=True)
  29. def weight_variable():
  30. """weight initial"""
  31. return TruncatedNormal(0.02)
  32. def conv(in_channels, out_channels, kernel_size, stride=1, padding=0):
  33. """weight initial for conv layer"""
  34. weight = weight_variable()
  35. return nn.Conv2d(in_channels, out_channels,
  36. kernel_size=kernel_size, stride=stride, padding=padding,
  37. weight_init=weight, has_bias=False, pad_mode="valid")
  38. def fc_with_initialize(input_channels, out_channels):
  39. """weight initial for fc layer"""
  40. weight = weight_variable()
  41. bias = weight_variable()
  42. return nn.Dense(input_channels, out_channels, weight, bias)
  43. class test_custom_hook_function_base():
  44. def __init__(self):
  45. pass
  46. def test_custom_hook_function(self, hook_function, cell_hook_function):
  47. return hook_function, cell_hook_function
  48. def cell_hook_function_print_grad(cell_id, grad_input, grad_output):
  49. assert grad_output[0].asnumpy().shape == (32, 6, 14, 14)
  50. assert grad_input[0].asnumpy().shape == (32, 16, 10, 10)
  51. def custom_hook_function_print_and_save_grad(grad_out):
  52. assert grad_out[0].asnumpy().shape == (32, 6, 28, 28)
  53. class LeNet5(nn.Cell):
  54. def __init__(self, hook_function, cell_hook_function, num_class=10):
  55. super(LeNet5, self).__init__()
  56. self.num_class = num_class
  57. self.batch_size = 32
  58. self.conv1 = conv(1, 6, 5)
  59. self.conv2 = conv(6, 16, 5)
  60. self.conv1.register_backward_hook(cell_hook_function)
  61. self.fc1 = fc_with_initialize(16 * 5 * 5, 120)
  62. self.fc2 = fc_with_initialize(120, 84)
  63. self.fc3 = fc_with_initialize(84, self.num_class)
  64. self.relu = nn.ReLU()
  65. self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)
  66. self.reshape = P.Reshape()
  67. self.hook = P.HookBackward(hook_function)
  68. def construct(self, x):
  69. x = self.conv1(x)
  70. x = self.relu(x)
  71. x = self.hook(x)
  72. x = self.max_pool2d(x)
  73. x = self.conv2(x)
  74. x = self.relu(x)
  75. x = self.max_pool2d(x)
  76. x = self.reshape(x, (self.batch_size, -1))
  77. x = self.fc1(x)
  78. x = self.relu(x)
  79. x = self.fc2(x)
  80. x = self.relu(x)
  81. x = self.fc3(x)
  82. return x
  83. class GradWrap(nn.Cell):
  84. """ GradWrap definition """
  85. def __init__(self, network):
  86. super(GradWrap, self).__init__(auto_prefix=False)
  87. self.network = network
  88. self.weights = ParameterTuple(filter(lambda x: x.requires_grad, network.get_parameters()))
  89. def construct(self, x, label):
  90. weights = self.weights
  91. return C.GradOperation(get_by_list=True)(self.network, weights)(x, label)
  92. class test_custom_cell_base():
  93. def __init__(self):
  94. pass
  95. def test_custom_cell_function(self, cell):
  96. return cell
  97. class MulAdd(nn.Cell):
  98. def construct(self, x, y):
  99. return 2 * x + y
  100. def bprop(self, x, y, out, dout):
  101. assert x.asnumpy() == 1.0
  102. assert y.asnumpy() == 2.0
  103. assert out.asnumpy() == 4.0
  104. assert dout.asnumpy() == 1.0
  105. return dout, y
  106. class Ms_Cell(nn.Cell):
  107. def __init__(self):
  108. super(Ms_Cell, self).__init__()
  109. self.relu = P.ReLU()
  110. def construct(self, x):
  111. return self.relu(x)
  112. def bprop(self, x, out, dout):
  113. dout = Tensor(np.ones([5, 5]).astype(np.float32))
  114. assert dout.shape == (5, 5)
  115. return dout
  116. @pytest.mark.level0
  117. @pytest.mark.platform_arm_ascend_training
  118. @pytest.mark.platform_x86_ascend_training
  119. @pytest.mark.env_onecard
  120. def test_pynative_lenet_train_hook_function_print_and_save_grad():
  121. hook = test_custom_hook_function_base()
  122. function = hook.test_custom_hook_function(custom_hook_function_print_and_save_grad,
  123. cell_hook_function_print_grad)
  124. net = LeNet5(hook_function=function[0], cell_hook_function=function[1])
  125. optimizer = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), 0.1, 0.9)
  126. criterion = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=False)
  127. net_with_criterion = WithLossCell(net, criterion)
  128. train_network = GradWrap(net_with_criterion)
  129. train_network.set_train()
  130. input_data = Tensor(np.ones([net.batch_size, 1, 32, 32]).astype(np.float32) * 0.01)
  131. label = Tensor(np.ones([net.batch_size, net.num_class]).astype(np.float32))
  132. output = net(Tensor(input_data))
  133. criterion(output, label)
  134. grads = train_network(input_data, label)
  135. success = optimizer(grads)
  136. assert success
  137. @pytest.mark.level0
  138. @pytest.mark.platform_arm_ascend_training
  139. @pytest.mark.platform_x86_ascend_training
  140. @pytest.mark.env_onecard
  141. def test_pynative_custom_bprop_and_Cell_MulAdd():
  142. custom_cell = test_custom_cell_base()
  143. mul_add = custom_cell.test_custom_cell_function(MulAdd())
  144. mul_add.bprop_debug = True
  145. grad_all(mul_add)(Tensor(1, mstype.float32), Tensor(2, mstype.float32))
  146. assert grad_all(mul_add)(Tensor(1, mstype.float32), Tensor(2, mstype.float32)) == \
  147. (Tensor(1.0, mstype.float32), Tensor(2.0, mstype.float32))
  148. @pytest.mark.level0
  149. @pytest.mark.platform_arm_ascend_training
  150. @pytest.mark.platform_x86_ascend_training
  151. @pytest.mark.env_onecard
  152. def test_pynative_custom_bprop_and_Cell_Ms_Cell():
  153. custom_cell = test_custom_cell_base()
  154. ms_Cell = custom_cell.test_custom_cell_function(Ms_Cell())
  155. ms_Cell.bprop_debug = True
  156. assert grad_all(ms_Cell)(Tensor(1, mstype.float32)) == (Tensor(1.0, mstype.float32),)