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_nes.py 6.8 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. import os
  15. import numpy as np
  16. import pytest
  17. from mindspore import Tensor
  18. from mindspore import context
  19. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  20. from mindarmour import BlackModel
  21. from mindarmour.adv_robustness.attacks import NES
  22. from mindarmour.utils.logger import LogUtil
  23. from tests.ut.python.utils.mock_net import Net
  24. context.set_context(mode=context.GRAPH_MODE)
  25. context.set_context(device_target="Ascend")
  26. LOGGER = LogUtil.get_instance()
  27. TAG = 'HopSkipJumpAttack'
  28. class ModelToBeAttacked(BlackModel):
  29. """model to be attack"""
  30. def __init__(self, network):
  31. super(ModelToBeAttacked, self).__init__()
  32. self._network = network
  33. def predict(self, inputs):
  34. """predict"""
  35. if len(inputs.shape) == 3:
  36. inputs = inputs[np.newaxis, :]
  37. result = self._network(Tensor(inputs.astype(np.float32)))
  38. return result.asnumpy()
  39. def random_target_labels(true_labels):
  40. target_labels = []
  41. for label in true_labels:
  42. while True:
  43. target_label = np.random.randint(0, 10)
  44. if target_label != label:
  45. target_labels.append(target_label)
  46. break
  47. return target_labels
  48. def _pseudorandom_target(index, total_indices, true_class):
  49. """ pseudo random_target """
  50. rng = np.random.RandomState(index)
  51. target = true_class
  52. while target == true_class:
  53. target = rng.randint(0, total_indices)
  54. return target
  55. def create_target_images(dataset, data_labels, target_labels):
  56. res = []
  57. for label in target_labels:
  58. for i, data_label in enumerate(data_labels):
  59. if data_label == label:
  60. res.append(dataset[i])
  61. break
  62. return np.array(res)
  63. def get_model(current_dir):
  64. ckpt_path = os.path.join(current_dir,
  65. '../../../dataset/trained_ckpt_file/checkpoint_lenet-10_1875.ckpt')
  66. net = Net()
  67. load_dict = load_checkpoint(ckpt_path)
  68. load_param_into_net(net, load_dict)
  69. net.set_train(False)
  70. model = ModelToBeAttacked(net)
  71. return model
  72. def get_dataset(current_dir):
  73. # upload trained network
  74. # get test data
  75. test_images = np.load(os.path.join(current_dir,
  76. '../../../dataset/test_images.npy'))
  77. test_labels = np.load(os.path.join(current_dir,
  78. '../../../dataset/test_labels.npy'))
  79. return test_images, test_labels
  80. def nes_mnist_attack(scene, top_k):
  81. """
  82. hsja-Attack test
  83. """
  84. current_dir = os.path.dirname(os.path.abspath(__file__))
  85. test_images, test_labels = get_dataset(current_dir)
  86. model = get_model(current_dir)
  87. # prediction accuracy before attack
  88. batch_num = 5 # the number of batches of attacking samples
  89. predict_labels = []
  90. i = 0
  91. for img in test_images:
  92. i += 1
  93. pred_labels = np.argmax(model.predict(img), axis=1)
  94. predict_labels.append(pred_labels)
  95. if i >= batch_num:
  96. break
  97. predict_labels = np.concatenate(predict_labels)
  98. true_labels = test_labels
  99. accuracy = np.mean(np.equal(predict_labels, true_labels[:batch_num]))
  100. LOGGER.info(TAG, "prediction accuracy before attacking is : %s",
  101. accuracy)
  102. test_images = test_images
  103. # attacking
  104. if scene == 'Query_Limit':
  105. top_k = -1
  106. elif scene == 'Partial_Info':
  107. top_k = top_k
  108. elif scene == 'Label_Only':
  109. top_k = top_k
  110. success = 0
  111. queries_num = 0
  112. nes_instance = NES(model, scene, top_k=top_k)
  113. test_length = 1
  114. advs = []
  115. for img_index in range(test_length):
  116. # INITIAL IMAGE AND CLASS SELECTION
  117. initial_img = test_images[img_index]
  118. orig_class = true_labels[img_index]
  119. initial_img = [initial_img]
  120. target_class = random_target_labels([orig_class])
  121. target_image = create_target_images(test_images, true_labels,
  122. target_class)
  123. nes_instance.set_target_images(target_image)
  124. tag, adv, queries = nes_instance.generate(np.array(initial_img), np.array(target_class))
  125. if tag[0]:
  126. success += 1
  127. queries_num += queries[0]
  128. advs.append(adv)
  129. advs = np.reshape(advs, (len(advs), 1, 32, 32))
  130. assert (advs != test_images[:batch_num]).any()
  131. adv_pred = np.argmax(model.predict(advs), axis=1)
  132. _ = np.mean(np.equal(adv_pred, true_labels[:test_length]))
  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_nes_query_limit():
  139. # scene is in ['Query_Limit', 'Partial_Info', 'Label_Only']
  140. scene = 'Query_Limit'
  141. nes_mnist_attack(scene, top_k=-1)
  142. @pytest.mark.level0
  143. @pytest.mark.platform_arm_ascend_training
  144. @pytest.mark.platform_x86_ascend_training
  145. @pytest.mark.env_card
  146. @pytest.mark.component_mindarmour
  147. def test_nes_partial_info():
  148. # scene is in ['Query_Limit', 'Partial_Info', 'Label_Only']
  149. scene = 'Partial_Info'
  150. nes_mnist_attack(scene, top_k=5)
  151. @pytest.mark.level0
  152. @pytest.mark.platform_arm_ascend_training
  153. @pytest.mark.platform_x86_ascend_training
  154. @pytest.mark.env_card
  155. @pytest.mark.component_mindarmour
  156. def test_nes_label_only():
  157. # scene is in ['Query_Limit', 'Partial_Info', 'Label_Only']
  158. scene = 'Label_Only'
  159. nes_mnist_attack(scene, top_k=5)
  160. @pytest.mark.level0
  161. @pytest.mark.platform_arm_ascend_training
  162. @pytest.mark.platform_x86_ascend_training
  163. @pytest.mark.env_card
  164. @pytest.mark.component_mindarmour
  165. def test_value_error():
  166. """test that exception is raised for invalid labels"""
  167. with pytest.raises(ValueError):
  168. assert nes_mnist_attack('Label_Only', -1)
  169. @pytest.mark.level0
  170. @pytest.mark.platform_arm_ascend_training
  171. @pytest.mark.platform_x86_ascend_training
  172. @pytest.mark.env_card
  173. @pytest.mark.component_mindarmour
  174. def test_none():
  175. current_dir = os.path.dirname(os.path.abspath(__file__))
  176. model = get_model(current_dir)
  177. test_images, test_labels = get_dataset(current_dir)
  178. nes = NES(model, 'Partial_Info')
  179. with pytest.raises(ValueError):
  180. assert nes.generate(test_images, test_labels)

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