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_deep_fool.py 9.9 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. DeepFool-Attack test.
  16. """
  17. import numpy as np
  18. import pytest
  19. import mindspore.ops.operations as P
  20. from mindspore.nn import Cell
  21. from mindspore import context
  22. from mindspore import Tensor
  23. from mindarmour.adv_robustness.attacks import DeepFool
  24. # for user
  25. class Net(Cell):
  26. """
  27. Construct the network of target model.
  28. Examples:
  29. >>> net = Net()
  30. """
  31. def __init__(self):
  32. """
  33. Introduce the layers used for network construction.
  34. """
  35. super(Net, self).__init__()
  36. self._softmax = P.Softmax()
  37. def construct(self, inputs):
  38. """
  39. Construct network.
  40. Args:
  41. inputs (Tensor): Input data.
  42. """
  43. out = self._softmax(inputs)
  44. return out
  45. class Net2(Cell):
  46. """
  47. Construct the network of target model, specifically for detection model test case.
  48. Examples:
  49. >>> net = Net2()
  50. """
  51. def __init__(self):
  52. super(Net2, self).__init__()
  53. self._softmax = P.Softmax()
  54. def construct(self, inputs1, inputs2):
  55. out1 = self._softmax(inputs1)
  56. out2 = self._softmax(inputs2)
  57. return out2, out1
  58. @pytest.mark.level0
  59. @pytest.mark.platform_arm_ascend_training
  60. @pytest.mark.platform_x86_ascend_training
  61. @pytest.mark.env_card
  62. @pytest.mark.component_mindarmour
  63. def test_deepfool_attack_ascend():
  64. """
  65. Feature: Deepfool-Attack test for ascend
  66. Description: Given multiple images, we want to make sure the adversarial examples
  67. generated are different from the images
  68. Expectation: input_np != ms_adv_x
  69. """
  70. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  71. net = Net()
  72. input_shape = (1, 5)
  73. _, classes = input_shape
  74. input_np = np.array([[0.1, 0.2, 0.7, 0.5, 0.4]]).astype(np.float32)
  75. input_me = Tensor(input_np)
  76. true_labels = np.argmax(net(input_me).asnumpy(), axis=1)
  77. attack = DeepFool(net, classes, max_iters=10, norm_level=2,
  78. bounds=(0.0, 1.0))
  79. adv_data = attack.generate(input_np, true_labels)
  80. # expected adv value
  81. expect_value = np.asarray([[0.10300991, 0.20332647, 0.59308802, 0.59651263,
  82. 0.40406296]])
  83. assert np.allclose(adv_data, expect_value), 'mindspore deepfool_method' \
  84. ' implementation error, ms_adv_x != expect_value'
  85. @pytest.mark.level0
  86. @pytest.mark.platform_x86_cpu
  87. @pytest.mark.env_card
  88. @pytest.mark.component_mindarmour
  89. def test_deepfool_attack_cpu():
  90. """
  91. Feature: Deepfool-Attack test for cpu
  92. Description: Given multiple images, we want to make sure the adversarial examples
  93. generated are different from the images
  94. Expectation: input_np != ms_adv_x
  95. """
  96. context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
  97. net = Net()
  98. input_shape = (1, 5)
  99. _, classes = input_shape
  100. input_np = np.array([[0.1, 0.2, 0.7, 0.5, 0.4]]).astype(np.float32)
  101. input_me = Tensor(input_np)
  102. true_labels = np.argmax(net(input_me).asnumpy(), axis=1)
  103. attack = DeepFool(net, classes, max_iters=10, norm_level=2,
  104. bounds=(0.0, 1.0))
  105. adv_data = attack.generate(input_np, true_labels)
  106. # expected adv value
  107. expect_value = np.asarray([[0.10300991, 0.20332647, 0.59308802, 0.59651263,
  108. 0.40406296]])
  109. assert np.allclose(adv_data, expect_value), 'mindspore deepfool_method' \
  110. ' implementation error, ms_adv_x != expect_value'
  111. @pytest.mark.level0
  112. @pytest.mark.platform_arm_ascend_training
  113. @pytest.mark.platform_x86_ascend_training
  114. @pytest.mark.env_card
  115. @pytest.mark.component_mindarmour
  116. def test_deepfool_attack_detection_ascend():
  117. """
  118. Feature: Deepfool-Attack-Detection test for ascend
  119. Description: Given multiple images, we want to make sure the adversarial examples
  120. generated are different from the images
  121. Expectation: input_np != ms_adv_x
  122. """
  123. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  124. net = Net2()
  125. inputs1_np = np.random.random((2, 10, 10)).astype(np.float32)
  126. inputs2_np = np.random.random((2, 10, 5)).astype(np.float32)
  127. gt_boxes, gt_logits = net(Tensor(inputs1_np), Tensor(inputs2_np))
  128. gt_boxes, gt_logits = gt_boxes.asnumpy(), gt_logits.asnumpy()
  129. gt_labels = np.argmax(gt_logits, axis=2)
  130. num_classes = 10
  131. attack = DeepFool(net, num_classes, model_type='detection', reserve_ratio=0.3,
  132. bounds=(0.0, 1.0))
  133. adv_data = attack.generate((inputs1_np, inputs2_np), (gt_boxes, gt_labels))
  134. assert np.any(adv_data != inputs1_np)
  135. @pytest.mark.level0
  136. @pytest.mark.platform_x86_cpu
  137. @pytest.mark.env_card
  138. @pytest.mark.component_mindarmour
  139. def test_deepfool_attack_detection_cpu():
  140. """
  141. Feature: Deepfool-Attack-Detection test for cpu
  142. Description: Given multiple images, we want to make sure the adversarial examples
  143. generated are different from the images
  144. Expectation: input_np != ms_adv_x
  145. """
  146. context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
  147. net = Net2()
  148. inputs1_np = np.random.random((2, 10, 10)).astype(np.float32)
  149. inputs2_np = np.random.random((2, 10, 5)).astype(np.float32)
  150. gt_boxes, gt_logits = net(Tensor(inputs1_np), Tensor(inputs2_np))
  151. gt_boxes, gt_logits = gt_boxes.asnumpy(), gt_logits.asnumpy()
  152. gt_labels = np.argmax(gt_logits, axis=2)
  153. num_classes = 10
  154. attack = DeepFool(net, num_classes, model_type='detection', reserve_ratio=0.3,
  155. bounds=(0.0, 1.0))
  156. adv_data = attack.generate((inputs1_np, inputs2_np), (gt_boxes, gt_labels))
  157. assert np.any(adv_data != inputs1_np)
  158. @pytest.mark.level0
  159. @pytest.mark.platform_arm_ascend_training
  160. @pytest.mark.platform_x86_ascend_training
  161. @pytest.mark.env_card
  162. @pytest.mark.component_mindarmour
  163. def test_deepfool_attack_inf_ascend():
  164. """
  165. Feature: Deepfool-Attack with inf-norm test for ascend
  166. Description: Given multiple images, we want to make sure the adversarial examples
  167. generated are different from the images
  168. Expectation: input_np != ms_adv_x
  169. """
  170. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  171. net = Net()
  172. input_shape = (1, 5)
  173. _, classes = input_shape
  174. input_np = np.array([[0.1, 0.2, 0.7, 0.5, 0.4]]).astype(np.float32)
  175. input_me = Tensor(input_np)
  176. true_labels = np.argmax(net(input_me).asnumpy(), axis=1)
  177. attack = DeepFool(net, classes, max_iters=10, norm_level=np.inf,
  178. bounds=(0.0, 1.0))
  179. adv_data = attack.generate(input_np, true_labels)
  180. assert np.any(input_np != adv_data)
  181. @pytest.mark.level0
  182. @pytest.mark.platform_x86_cpu
  183. @pytest.mark.env_card
  184. @pytest.mark.component_mindarmour
  185. def test_deepfool_attack_inf_cpu():
  186. """
  187. Feature: Deepfool-Attack with inf-norm test for cpu
  188. Description: Given multiple images, we want to make sure the adversarial examples
  189. generated are different from the images
  190. Expectation: input_np != ms_adv_x
  191. """
  192. context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
  193. net = Net()
  194. input_shape = (1, 5)
  195. _, classes = input_shape
  196. input_np = np.array([[0.1, 0.2, 0.7, 0.5, 0.4]]).astype(np.float32)
  197. input_me = Tensor(input_np)
  198. true_labels = np.argmax(net(input_me).asnumpy(), axis=1)
  199. attack = DeepFool(net, classes, max_iters=10, norm_level=np.inf,
  200. bounds=(0.0, 1.0))
  201. adv_data = attack.generate(input_np, true_labels)
  202. assert np.any(input_np != adv_data)
  203. @pytest.mark.level0
  204. @pytest.mark.platform_arm_ascend_training
  205. @pytest.mark.platform_x86_ascend_training
  206. @pytest.mark.env_card
  207. @pytest.mark.component_mindarmour
  208. def test_value_error_ascend():
  209. """
  210. Feature: value error test for ascend
  211. Description: value error for deep fool
  212. Expectation: attack.generate works
  213. """
  214. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  215. net = Net()
  216. input_shape = (1, 5)
  217. _, classes = input_shape
  218. input_np = np.array([[0.1, 0.2, 0.7, 0.5, 0.4]]).astype(np.float32)
  219. input_me = Tensor(input_np)
  220. true_labels = np.argmax(net(input_me).asnumpy(), axis=1)
  221. with pytest.raises(NotImplementedError):
  222. # norm_level=0 is not available
  223. attack = DeepFool(net, classes, max_iters=10, norm_level=1,
  224. bounds=(0.0, 1.0))
  225. assert attack.generate(input_np, true_labels)
  226. @pytest.mark.level0
  227. @pytest.mark.platform_x86_cpu
  228. @pytest.mark.env_card
  229. @pytest.mark.component_mindarmour
  230. def test_value_error_cpu():
  231. """
  232. Feature: value error test for cpu
  233. Description: value error for deep fool
  234. Expectation: attack.generate works
  235. """
  236. context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
  237. net = Net()
  238. input_shape = (1, 5)
  239. _, classes = input_shape
  240. input_np = np.array([[0.1, 0.2, 0.7, 0.5, 0.4]]).astype(np.float32)
  241. input_me = Tensor(input_np)
  242. true_labels = np.argmax(net(input_me).asnumpy(), axis=1)
  243. with pytest.raises(NotImplementedError):
  244. # norm_level=0 is not available
  245. attack = DeepFool(net, classes, max_iters=10, norm_level=1,
  246. bounds=(0.0, 1.0))
  247. assert attack.generate(input_np, true_labels)

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