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_hook.py 6.1 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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 numpy as np
  16. import pytest
  17. import mindspore.nn as nn
  18. import mindspore.ops.operations as P
  19. from mindspore import context, Tensor, ParameterTuple
  20. from mindspore.common.initializer import TruncatedNormal
  21. from mindspore.nn import WithLossCell, Momentum
  22. from mindspore.ops import composite as C
  23. context.set_context(mode=context.PYNATIVE_MODE, device_target="GPU")
  24. cell_hook_done = False
  25. var_hook_done = False
  26. cell_bprop_done = False
  27. def conv(in_channels, out_channels, kernel_size, stride=1, padding=0):
  28. """weight initial for conv layer"""
  29. weight = weight_variable()
  30. return nn.Conv2d(in_channels, out_channels,
  31. kernel_size=kernel_size, stride=stride, padding=padding,
  32. weight_init=weight, has_bias=False, pad_mode="valid")
  33. def fc_with_initialize(input_channels, out_channels):
  34. """weight initial for fc layer"""
  35. weight = weight_variable()
  36. bias = weight_variable()
  37. return nn.Dense(input_channels, out_channels, weight, bias)
  38. def weight_variable():
  39. """weight initial"""
  40. return TruncatedNormal(0.02)
  41. def cell_hook_function(cell_id, grad_input, grad_output):
  42. print(cell_id)
  43. global cell_hook_done
  44. cell_hook_done = True
  45. assert (grad_output[0].asnumpy().shape == (32, 6, 14, 14))
  46. assert (grad_input[0].asnumpy().shape == (32, 16, 10, 10))
  47. def var_hook_function(grad_out):
  48. print("grad:", grad_out)
  49. global var_hook_done
  50. var_hook_done = True
  51. assert (grad_out[0].asnumpy().shape == (32, 120))
  52. class Block(nn.Cell):
  53. def __init__(self):
  54. super(Block, self).__init__()
  55. self.relu = nn.ReLU()
  56. def construct(self, x):
  57. x = self.relu(x)
  58. return x
  59. def bprop(self, x, out, dout):
  60. global cell_bprop_done
  61. cell_bprop_done = True
  62. grad = out.asnumpy() * dout.asnumpy()
  63. grad = Tensor(grad)
  64. return (grad,)
  65. class LeNet5(nn.Cell):
  66. """
  67. Lenet network
  68. Args:
  69. num_class (int): Num classes. Default: 10.
  70. Returns:
  71. Tensor, output tensor
  72. Examples:
  73. >>> LeNet(num_class=10)
  74. """
  75. def __init__(self, num_class=10):
  76. super(LeNet5, self).__init__()
  77. self.num_class = num_class
  78. self.batch_size = 32
  79. self.conv1 = conv(1, 6, 5)
  80. self.conv2 = conv(6, 16, 5)
  81. self.conv2.register_backward_hook(cell_hook_function)
  82. self.block = Block()
  83. self.fc1 = fc_with_initialize(16 * 5 * 5, 120)
  84. self.fc2 = fc_with_initialize(120, 84)
  85. self.fc3 = fc_with_initialize(84, self.num_class)
  86. self.relu = nn.ReLU()
  87. self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)
  88. self.reshape = P.Reshape()
  89. self.hook = P.HookBackward(var_hook_function)
  90. def construct(self, x):
  91. x = self.conv1(x)
  92. x = self.relu(x)
  93. x = self.max_pool2d(x)
  94. x = self.conv2(x)
  95. x = self.block(x)
  96. x = self.max_pool2d(x)
  97. x = self.reshape(x, (self.batch_size, -1))
  98. x = self.fc1(x)
  99. x = self.hook(x)
  100. x = self.relu(x)
  101. x = self.fc2(x)
  102. x = self.relu(x)
  103. x = self.fc3(x)
  104. return x
  105. class GradWrap(nn.Cell):
  106. """ GradWrap definition """
  107. def __init__(self, network):
  108. super(GradWrap, self).__init__(auto_prefix=False)
  109. self.network = network
  110. self.weights = ParameterTuple(filter(lambda x: x.requires_grad, network.get_parameters()))
  111. def construct(self, x, label):
  112. weights = self.weights
  113. return C.GradOperation('get_by_list', get_by_list=True)(self.network, weights)(x, label)
  114. def test_hook():
  115. net = LeNet5()
  116. optimizer = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), 0.1, 0.9)
  117. criterion = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=False)
  118. net_with_criterion = WithLossCell(net, criterion)
  119. train_network = GradWrap(net_with_criterion)
  120. train_network.set_train()
  121. input_data = Tensor(np.ones([net.batch_size, 1, 32, 32]).astype(np.float32) * 0.01)
  122. label = Tensor(np.ones([net.batch_size, net.num_class]).astype(np.float32))
  123. output = net(Tensor(input_data))
  124. loss_output = criterion(output, label)
  125. grads = train_network(input_data, label)
  126. success = optimizer(grads)
  127. assert cell_hook_done
  128. assert var_hook_done
  129. assert cell_bprop_done
  130. print(loss_output.asnumpy().shape)
  131. bprop_debug = False
  132. class MulAdd(nn.Cell):
  133. def __init__(self):
  134. super(MulAdd, self).__init__()
  135. def construct(self, x, y):
  136. return 2 * x * x + y * y
  137. def bprop(self, x, y, out, dout):
  138. global bprop_debug
  139. bprop_debug = True
  140. return dout, 2 * y
  141. def test_custom_bprop():
  142. mul_add = MulAdd()
  143. mul_add.bprop_debug = True
  144. x = Tensor(np.array([1, 2, 3]).astype(np.int32))
  145. y = Tensor(np.array([2, 3, 4]).astype(np.int32))
  146. C.grad_all(mul_add)(x, y)
  147. assert bprop_debug
  148. class Net(nn.Cell):
  149. def __init__(self):
  150. super(Net, self).__init__()
  151. def construct(self, x, y):
  152. return 2 * x * x + y * y
  153. def test_grad_all():
  154. net = Net()
  155. x = Tensor(np.array([1, 2, 3]).astype(np.int32))
  156. y = Tensor(np.array([2, 3, 4]).astype(np.int32))
  157. res = C.grad_all(net)(x, y)
  158. print(res)
  159. def test_check_input():
  160. net = Net()
  161. x = np.array([1, 2, 3])
  162. y = np.array([2, 3, 4])
  163. with pytest.raises(TypeError):
  164. net(x, y)