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_gradient_method.py 8.0 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. Gradient-Attack test.
  16. """
  17. import numpy as np
  18. import pytest
  19. import mindspore.nn as nn
  20. from mindspore.nn import Cell
  21. import mindspore.context as context
  22. from mindspore.nn import SoftmaxCrossEntropyWithLogits
  23. from mindarmour.attacks.gradient_method import FastGradientMethod
  24. from mindarmour.attacks.gradient_method import FastGradientSignMethod
  25. from mindarmour.attacks.gradient_method import LeastLikelyClassMethod
  26. from mindarmour.attacks.gradient_method import RandomFastGradientMethod
  27. from mindarmour.attacks.gradient_method import RandomFastGradientSignMethod
  28. from mindarmour.attacks.gradient_method import RandomLeastLikelyClassMethod
  29. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  30. # for user
  31. class Net(Cell):
  32. """
  33. Construct the network of target model.
  34. Examples:
  35. >>> net = Net()
  36. """
  37. def __init__(self):
  38. """
  39. Introduce the layers used for network construction.
  40. """
  41. super(Net, self).__init__()
  42. self._relu = nn.ReLU()
  43. def construct(self, inputs):
  44. """
  45. Construct network.
  46. Args:
  47. inputs (Tensor): Input data.
  48. """
  49. out = self._relu(inputs)
  50. return out
  51. @pytest.mark.level0
  52. @pytest.mark.platform_arm_ascend_training
  53. @pytest.mark.platform_x86_ascend_training
  54. @pytest.mark.env_card
  55. @pytest.mark.component_mindarmour
  56. def test_fast_gradient_method():
  57. """
  58. Fast gradient method unit test.
  59. """
  60. input_np = np.asarray([[0.1, 0.2, 0.7]], np.float32)
  61. label = np.asarray([2], np.int32)
  62. label = np.eye(3)[label].astype(np.float32)
  63. attack = FastGradientMethod(Net())
  64. ms_adv_x = attack.generate(input_np, label)
  65. assert np.any(ms_adv_x != input_np), 'Fast gradient method: generate value' \
  66. ' must not be equal to original value.'
  67. @pytest.mark.level0
  68. @pytest.mark.platform_x86_gpu_inference
  69. @pytest.mark.env_card
  70. @pytest.mark.component_mindarmour
  71. def test_fast_gradient_method_gpu():
  72. """
  73. Fast gradient method unit test.
  74. """
  75. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  76. input_np = np.asarray([[0.1, 0.2, 0.7]], np.float32)
  77. label = np.asarray([2], np.int32)
  78. label = np.eye(3)[label].astype(np.float32)
  79. attack = FastGradientMethod(Net())
  80. ms_adv_x = attack.generate(input_np, label)
  81. assert np.any(ms_adv_x != input_np), 'Fast gradient method: generate value' \
  82. ' must not be equal to original value.'
  83. @pytest.mark.level0
  84. @pytest.mark.platform_x86_cpu
  85. @pytest.mark.env_card
  86. @pytest.mark.component_mindarmour
  87. def test_fast_gradient_method_cpu():
  88. """
  89. Fast gradient method unit test.
  90. """
  91. context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
  92. input_np = np.asarray([[0.1, 0.2, 0.7]], np.float32)
  93. label = np.asarray([2], np.int32)
  94. loss = SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True)
  95. attack = FastGradientMethod(Net(), loss_fn=loss)
  96. ms_adv_x = attack.generate(input_np, label)
  97. assert np.any(ms_adv_x != input_np), 'Fast gradient method: generate value' \
  98. ' must not be equal to original value.'
  99. @pytest.mark.level0
  100. @pytest.mark.platform_arm_ascend_training
  101. @pytest.mark.platform_x86_ascend_training
  102. @pytest.mark.env_card
  103. @pytest.mark.component_mindarmour
  104. def test_random_fast_gradient_method():
  105. """
  106. Random fast gradient method unit test.
  107. """
  108. input_np = np.asarray([[0.1, 0.2, 0.7]], np.float32)
  109. label = np.asarray([2], np.int32)
  110. label = np.eye(3)[label].astype(np.float32)
  111. attack = RandomFastGradientMethod(Net())
  112. ms_adv_x = attack.generate(input_np, label)
  113. assert np.any(ms_adv_x != input_np), 'Random fast gradient method: ' \
  114. 'generate value must not be equal to' \
  115. ' original value.'
  116. @pytest.mark.level0
  117. @pytest.mark.platform_arm_ascend_training
  118. @pytest.mark.platform_x86_ascend_training
  119. @pytest.mark.env_card
  120. @pytest.mark.component_mindarmour
  121. def test_fast_gradient_sign_method():
  122. """
  123. Fast gradient sign method unit test.
  124. """
  125. input_np = np.asarray([[0.1, 0.2, 0.7]], np.float32)
  126. label = np.asarray([2], np.int32)
  127. label = np.eye(3)[label].astype(np.float32)
  128. attack = FastGradientSignMethod(Net())
  129. ms_adv_x = attack.generate(input_np, label)
  130. assert np.any(ms_adv_x != input_np), 'Fast gradient sign method: generate' \
  131. ' value must not be equal to' \
  132. ' original value.'
  133. @pytest.mark.level0
  134. @pytest.mark.platform_arm_ascend_training
  135. @pytest.mark.platform_x86_ascend_training
  136. @pytest.mark.env_card
  137. @pytest.mark.component_mindarmour
  138. def test_random_fast_gradient_sign_method():
  139. """
  140. Random fast gradient sign method unit test.
  141. """
  142. input_np = np.random.random((1, 28)).astype(np.float32)
  143. label = np.asarray([2], np.int32)
  144. label = np.eye(28)[label].astype(np.float32)
  145. attack = RandomFastGradientSignMethod(Net())
  146. ms_adv_x = attack.generate(input_np, label)
  147. assert np.any(ms_adv_x != input_np), 'Random fast gradient sign method: ' \
  148. 'generate value must not be equal to' \
  149. ' original value.'
  150. @pytest.mark.level0
  151. @pytest.mark.platform_arm_ascend_training
  152. @pytest.mark.platform_x86_ascend_training
  153. @pytest.mark.env_card
  154. @pytest.mark.component_mindarmour
  155. def test_least_likely_class_method():
  156. """
  157. Least likely class method unit test.
  158. """
  159. input_np = np.asarray([[0.1, 0.2, 0.7]], np.float32)
  160. label = np.asarray([2], np.int32)
  161. label = np.eye(3)[label].astype(np.float32)
  162. attack = LeastLikelyClassMethod(Net())
  163. ms_adv_x = attack.generate(input_np, label)
  164. assert np.any(ms_adv_x != input_np), 'Least likely class method: generate' \
  165. ' value must not be equal to' \
  166. ' original value.'
  167. @pytest.mark.level0
  168. @pytest.mark.platform_arm_ascend_training
  169. @pytest.mark.platform_x86_ascend_training
  170. @pytest.mark.env_card
  171. @pytest.mark.component_mindarmour
  172. def test_random_least_likely_class_method():
  173. """
  174. Random least likely class method unit test.
  175. """
  176. input_np = np.asarray([[0.1, 0.2, 0.7]], np.float32)
  177. label = np.asarray([2], np.int32)
  178. label = np.eye(3)[label].astype(np.float32)
  179. attack = RandomLeastLikelyClassMethod(Net(), eps=0.1, alpha=0.01)
  180. ms_adv_x = attack.generate(input_np, label)
  181. assert np.any(ms_adv_x != input_np), 'Random least likely class method: ' \
  182. 'generate value must not be equal to' \
  183. ' original value.'
  184. @pytest.mark.level0
  185. @pytest.mark.platform_arm_ascend_training
  186. @pytest.mark.platform_x86_ascend_training
  187. @pytest.mark.env_card
  188. @pytest.mark.component_mindarmour
  189. def test_assert_error():
  190. """
  191. Random least likely class method unit test.
  192. """
  193. input_np = np.asarray([[0.1, 0.2, 0.7]], np.float32)
  194. label = np.asarray([2], np.int32)
  195. label = np.eye(3)[label].astype(np.float32)
  196. with pytest.raises(ValueError) as e:
  197. assert RandomLeastLikelyClassMethod(Net(), eps=0.05, alpha=0.21)
  198. assert str(e.value) == 'eps must be larger than alpha!'

MindArmour关注AI的安全和隐私问题。致力于增强模型的安全可信、保护用户的数据隐私。主要包含3个模块:对抗样本鲁棒性模块、Fuzz Testing模块、隐私保护与评估模块。 对抗样本鲁棒性模块 对抗样本鲁棒性模块用于评估模型对于对抗样本的鲁棒性,并提供模型增强方法用于增强模型抗对抗样本攻击的能力,提升模型鲁棒性。对抗样本鲁棒性模块包含了4个子模块:对抗样本的生成、对抗样本的检测、模型防御、攻防评估。