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_hsja.py 5.7 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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 sys
  15. import os
  16. import numpy as np
  17. import pytest
  18. from mindspore import Tensor
  19. from mindspore import context
  20. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  21. from mindarmour.attacks.black.hop_skip_jump_attack import HopSkipJumpAttack
  22. from mindarmour.attacks.black.black_model import BlackModel
  23. from mindarmour.utils.logger import LogUtil
  24. sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)),
  25. "../../../../../"))
  26. from example.mnist_demo.lenet5_net import LeNet5
  27. context.set_context(mode=context.GRAPH_MODE)
  28. context.set_context(device_target="Ascend")
  29. LOGGER = LogUtil.get_instance()
  30. TAG = 'HopSkipJumpAttack'
  31. class ModelToBeAttacked(BlackModel):
  32. """model to be attack"""
  33. def __init__(self, network):
  34. super(ModelToBeAttacked, self).__init__()
  35. self._network = network
  36. def predict(self, inputs):
  37. """predict"""
  38. if len(inputs.shape) == 3:
  39. inputs = inputs[np.newaxis, :]
  40. result = self._network(Tensor(inputs.astype(np.float32)))
  41. return result.asnumpy()
  42. def random_target_labels(true_labels):
  43. target_labels = []
  44. for label in true_labels:
  45. while True:
  46. target_label = np.random.randint(0, 10)
  47. if target_label != label:
  48. target_labels.append(target_label)
  49. break
  50. return target_labels
  51. def create_target_images(dataset, data_labels, target_labels):
  52. res = []
  53. for label in target_labels:
  54. for i in range(len(data_labels)):
  55. if data_labels[i] == label:
  56. res.append(dataset[i])
  57. break
  58. return np.array(res)
  59. # public variable
  60. def get_model():
  61. # upload trained network
  62. current_dir = os.path.dirname(os.path.abspath(__file__))
  63. ckpt_name = os.path.join(current_dir,
  64. '../../test_data/trained_ckpt_file/checkpoint_lenet-10_1875.ckpt')
  65. net = LeNet5()
  66. load_dict = load_checkpoint(ckpt_name)
  67. load_param_into_net(net, load_dict)
  68. net.set_train(False)
  69. model = ModelToBeAttacked(net)
  70. return model
  71. @pytest.mark.level0
  72. @pytest.mark.platform_arm_ascend_training
  73. @pytest.mark.platform_x86_ascend_training
  74. @pytest.mark.env_card
  75. @pytest.mark.component_mindarmour
  76. def test_hsja_mnist_attack():
  77. """
  78. hsja-Attack test
  79. """
  80. current_dir = os.path.dirname(os.path.abspath(__file__))
  81. # get test data
  82. test_images_set = np.load(os.path.join(current_dir,
  83. '../../test_data/test_images.npy'))
  84. test_labels_set = np.load(os.path.join(current_dir,
  85. '../../test_data/test_labels.npy'))
  86. # prediction accuracy before attack
  87. model = get_model()
  88. batch_num = 1 # the number of batches of attacking samples
  89. predict_labels = []
  90. i = 0
  91. for img in test_images_set:
  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_set[:batch_num]
  99. accuracy = np.mean(np.equal(predict_labels, true_labels))
  100. LOGGER.info(TAG, "prediction accuracy before attacking is : %s",
  101. accuracy)
  102. test_images = test_images_set[:batch_num]
  103. # attacking
  104. norm = 'l2'
  105. search = 'grid_search'
  106. target = False
  107. attack = HopSkipJumpAttack(model, constraint=norm, stepsize_search=search)
  108. if target:
  109. target_labels = random_target_labels(true_labels)
  110. target_images = create_target_images(test_images_set, test_labels_set,
  111. target_labels)
  112. LOGGER.info(TAG, 'len target labels : %s', len(target_labels))
  113. LOGGER.info(TAG, 'len target_images : %s', len(target_images))
  114. LOGGER.info(TAG, 'len test_images : %s', len(test_images))
  115. attack.set_target_images(target_images)
  116. success_list, adv_data, _ = attack.generate(test_images, target_labels)
  117. else:
  118. success_list, adv_data, query_list = attack.generate(test_images, None)
  119. assert (adv_data != test_images).any()
  120. adv_datas = []
  121. gts = []
  122. for success, adv, gt in zip(success_list, adv_data, true_labels):
  123. if success:
  124. adv_datas.append(adv)
  125. gts.append(gt)
  126. if len(gts) > 0:
  127. adv_datas = np.concatenate(np.asarray(adv_datas), axis=0)
  128. gts = np.asarray(gts)
  129. pred_logits_adv = model.predict(adv_datas)
  130. pred_lables_adv = np.argmax(pred_logits_adv, axis=1)
  131. accuracy_adv = np.mean(np.equal(pred_lables_adv, gts))
  132. LOGGER.info(TAG, 'mis-classification rate of adversaries is : %s',
  133. accuracy_adv)
  134. @pytest.mark.level0
  135. @pytest.mark.platform_arm_ascend_training
  136. @pytest.mark.platform_x86_ascend_training
  137. @pytest.mark.env_card
  138. @pytest.mark.component_mindarmour
  139. def test_value_error():
  140. model = get_model()
  141. norm = 'l2'
  142. with pytest.raises(ValueError) as e:
  143. assert HopSkipJumpAttack(model, constraint=norm, stepsize_search='bad-search')

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