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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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. """
  16. This test is used to monitor some features of MindArmour.
  17. """
  18. import numpy as np
  19. import pytest
  20. import mindspore.nn as nn
  21. from mindspore import context, Tensor
  22. from mindspore.nn import Cell, WithLossCell, TrainOneStepCell
  23. from mindspore.nn.optim.momentum import Momentum
  24. from mindspore.common.initializer import TruncatedNormal
  25. from mindspore.ops.composite import GradOperation
  26. def weight_variable():
  27. """weight initial"""
  28. return TruncatedNormal(0.02)
  29. def conv(in_channels, out_channels, kernel_size, stride=1, padding=0):
  30. """weight initial for conv layer"""
  31. weight = weight_variable()
  32. return nn.Conv2d(in_channels, out_channels,
  33. kernel_size=kernel_size, stride=stride, padding=padding,
  34. weight_init=weight, has_bias=False, pad_mode="valid")
  35. def fc_with_initialize(input_channels, out_channels):
  36. """weight initial for fc layer"""
  37. weight = weight_variable()
  38. bias = weight_variable()
  39. return nn.Dense(input_channels, out_channels, weight, bias)
  40. class LeNet(nn.Cell):
  41. """
  42. Lenet network
  43. Args:
  44. num_class (int): Num classes, Default: 10.
  45. Returns:
  46. Tensor, output tensor
  47. Examples:
  48. >>> LeNet(num_class=10)
  49. """
  50. def __init__(self, num_class=10):
  51. super(LeNet, self).__init__()
  52. self.conv1 = conv(1, 6, 5)
  53. self.conv2 = conv(6, 16, 5)
  54. self.fc1 = fc_with_initialize(16 * 5 * 5, 120)
  55. self.fc2 = fc_with_initialize(120, 84)
  56. self.fc3 = fc_with_initialize(84, 10)
  57. self.relu = nn.ReLU()
  58. self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)
  59. self.flatten = nn.Flatten()
  60. def construct(self, x):
  61. x = self.conv1(x)
  62. x = self.relu(x)
  63. x = self.max_pool2d(x)
  64. x = self.conv2(x)
  65. x = self.relu(x)
  66. x = self.max_pool2d(x)
  67. x = self.flatten(x)
  68. x = self.fc1(x)
  69. x = self.relu(x)
  70. x = self.fc2(x)
  71. x = self.relu(x)
  72. x = self.fc3(x)
  73. return x
  74. class GradWithSens(Cell):
  75. def __init__(self, network):
  76. super(GradWithSens, self).__init__()
  77. self.grad = GradOperation(get_all=False,
  78. sens_param=True)
  79. self.network = network
  80. def construct(self, inputs, weight):
  81. gout = self.grad(self.network)(inputs, weight)
  82. return gout
  83. class GradWrapWithLoss(Cell):
  84. def __init__(self, network):
  85. super(GradWrapWithLoss, self).__init__()
  86. self._grad_all = GradOperation(get_all=True,
  87. sens_param=False)
  88. self._network = network
  89. def construct(self, inputs, labels):
  90. gout = self._grad_all(self._network)(inputs, labels)
  91. return gout[0]
  92. @pytest.mark.level0
  93. @pytest.mark.platform_arm_ascend_training
  94. @pytest.mark.platform_x86_ascend_training
  95. @pytest.mark.env_onecard
  96. def test_grad_values_and_infer_shape():
  97. context.set_context(mode=context.PYNATIVE_MODE, device_target="Ascend")
  98. inputs_np = np.random.rand(32, 1, 32, 32).astype(np.float32)
  99. sens = np.ones((inputs_np.shape[0], 10)).astype(np.float32)
  100. inputs_np_2 = np.random.rand(64, 1, 32, 32).astype(np.float32)
  101. net = LeNet()
  102. grad_all = GradWithSens(net)
  103. grad_out = grad_all(Tensor(inputs_np), Tensor(sens)).asnumpy()
  104. out_shape = net(Tensor(inputs_np_2)).asnumpy().shape
  105. assert np.any(grad_out != 0), 'grad result can not be all zeros'
  106. assert out_shape == (64, 10), 'output shape should be (64, 10)'
  107. @pytest.mark.level0
  108. @pytest.mark.platform_arm_ascend_training
  109. @pytest.mark.platform_x86_ascend_training
  110. @pytest.mark.env_onecard
  111. def test_multi_grads():
  112. context.set_context(mode=context.PYNATIVE_MODE, device_target="Ascend")
  113. sparse = False
  114. inputs_np = np.random.rand(32, 1, 32, 32).astype(np.float32)
  115. labels_np = np.random.randint(10, size=32).astype(np.int32)
  116. inputs_np_2 = np.random.rand(64, 1, 32, 32).astype(np.float32)
  117. labels_np_2 = np.random.randint(10, size=64).astype(np.int32)
  118. if not sparse:
  119. labels_np = np.eye(10)[labels_np].astype(np.float32)
  120. labels_np_2 = np.eye(10)[labels_np_2].astype(np.float32)
  121. net = LeNet()
  122. # grad operation
  123. loss_fn = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=sparse)
  124. with_loss_cell = WithLossCell(net, loss_fn)
  125. grad_all = GradWrapWithLoss(with_loss_cell)
  126. grad_out = grad_all(Tensor(inputs_np), Tensor(labels_np)).asnumpy()
  127. assert np.any(grad_out != 0), 'grad result can not be all zeros'
  128. # train-one-step operation
  129. loss_fn = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=sparse)
  130. optimizer = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()),
  131. 0.01, 0.9)
  132. loss_net = WithLossCell(net, loss_fn)
  133. train_net = TrainOneStepCell(loss_net, optimizer)
  134. train_net.set_train()
  135. train_net(Tensor(inputs_np_2), Tensor(labels_np_2))