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 8.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
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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 HopSkipJumpAttack
  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. LOGGER = LogUtil.get_instance()
  26. TAG = 'HopSkipJumpAttack'
  27. class ModelToBeAttacked(BlackModel):
  28. """model to be attack"""
  29. def __init__(self, network):
  30. super(ModelToBeAttacked, self).__init__()
  31. self._network = network
  32. def predict(self, inputs):
  33. """predict"""
  34. if len(inputs.shape) == 3:
  35. inputs = inputs[np.newaxis, :]
  36. result = self._network(Tensor(inputs.astype(np.float32)))
  37. return result.asnumpy()
  38. def random_target_labels(true_labels):
  39. target_labels = []
  40. for label in true_labels:
  41. while True:
  42. target_label = np.random.randint(0, 10)
  43. if target_label != label:
  44. target_labels.append(target_label)
  45. break
  46. return target_labels
  47. def create_target_images(dataset, data_labels, target_labels):
  48. res = []
  49. for label in target_labels:
  50. for i, data_label in enumerate(data_labels):
  51. if data_label == label:
  52. res.append(dataset[i])
  53. break
  54. return np.array(res)
  55. # public variable
  56. def get_model():
  57. # upload trained network
  58. current_dir = os.path.dirname(os.path.abspath(__file__))
  59. ckpt_path = os.path.join(current_dir,
  60. '../../../dataset/trained_ckpt_file/checkpoint_lenet-10_1875.ckpt')
  61. net = Net()
  62. load_dict = load_checkpoint(ckpt_path)
  63. load_param_into_net(net, load_dict)
  64. net.set_train(False)
  65. model = ModelToBeAttacked(net)
  66. return model
  67. @pytest.mark.level0
  68. @pytest.mark.platform_arm_ascend_training
  69. @pytest.mark.platform_x86_ascend_training
  70. @pytest.mark.env_card
  71. @pytest.mark.component_mindarmour
  72. def test_hsja_mnist_attack_ascend():
  73. """
  74. Feature: test HSJA attack for ascend
  75. Description: make sure the HSJA attack works properly
  76. Expectation: predict without any bugs
  77. """
  78. context.set_context(device_target="Ascend")
  79. current_dir = os.path.dirname(os.path.abspath(__file__))
  80. # get test data
  81. test_images_set = np.load(os.path.join(current_dir,
  82. '../../../dataset/test_images.npy'))
  83. test_labels_set = np.load(os.path.join(current_dir,
  84. '../../../dataset/test_labels.npy'))
  85. # prediction accuracy before attack
  86. model = get_model()
  87. batch_num = 1 # the number of batches of attacking samples
  88. predict_labels = []
  89. i = 0
  90. for img in test_images_set:
  91. i += 1
  92. pred_labels = np.argmax(model.predict(img), axis=1)
  93. predict_labels.append(pred_labels)
  94. if i >= batch_num:
  95. break
  96. predict_labels = np.concatenate(predict_labels)
  97. true_labels = test_labels_set[:batch_num]
  98. accuracy = np.mean(np.equal(predict_labels, true_labels))
  99. LOGGER.info(TAG, "prediction accuracy before attacking is : %s",
  100. accuracy)
  101. test_images = test_images_set[:batch_num]
  102. # attacking
  103. norm = 'l2'
  104. search = 'grid_search'
  105. target = False
  106. attack = HopSkipJumpAttack(model, constraint=norm, stepsize_search=search)
  107. if target:
  108. target_labels = random_target_labels(true_labels)
  109. target_images = create_target_images(test_images_set, test_labels_set,
  110. target_labels)
  111. LOGGER.info(TAG, 'len target labels : %s', len(target_labels))
  112. LOGGER.info(TAG, 'len target_images : %s', len(target_images))
  113. LOGGER.info(TAG, 'len test_images : %s', len(test_images))
  114. attack.set_target_images(target_images)
  115. success_list, adv_data, _ = attack.generate(test_images, target_labels)
  116. else:
  117. success_list, adv_data, _ = attack.generate(test_images, None)
  118. assert (adv_data != test_images).any()
  119. adv_datas = []
  120. gts = []
  121. for success, adv, gt in zip(success_list, adv_data, true_labels):
  122. if success:
  123. adv_datas.append(adv)
  124. gts.append(gt)
  125. if gts:
  126. adv_datas = np.concatenate(np.asarray(adv_datas), axis=0)
  127. gts = np.asarray(gts)
  128. pred_logits_adv = model.predict(adv_datas)
  129. pred_lables_adv = np.argmax(pred_logits_adv, axis=1)
  130. accuracy_adv = np.mean(np.equal(pred_lables_adv, gts))
  131. LOGGER.info(TAG, 'mis-classification rate of adversaries is : %s',
  132. accuracy_adv)
  133. @pytest.mark.level0
  134. @pytest.mark.platform_x86_cpu
  135. @pytest.mark.env_card
  136. @pytest.mark.component_mindarmour
  137. def test_hsja_mnist_attack_cpu():
  138. """
  139. Feature: test HSJA attack for cpu
  140. Description: make sure the HSJA attack works properly
  141. Expectation: predict without any bugs
  142. """
  143. context.set_context(device_target="CPU")
  144. current_dir = os.path.dirname(os.path.abspath(__file__))
  145. # get test data
  146. test_images_set = np.load(os.path.join(current_dir,
  147. '../../../dataset/test_images.npy'))
  148. test_labels_set = np.load(os.path.join(current_dir,
  149. '../../../dataset/test_labels.npy'))
  150. # prediction accuracy before attack
  151. model = get_model()
  152. batch_num = 1 # the number of batches of attacking samples
  153. predict_labels = []
  154. i = 0
  155. for img in test_images_set:
  156. i += 1
  157. pred_labels = np.argmax(model.predict(img), axis=1)
  158. predict_labels.append(pred_labels)
  159. if i >= batch_num:
  160. break
  161. predict_labels = np.concatenate(predict_labels)
  162. true_labels = test_labels_set[:batch_num]
  163. accuracy = np.mean(np.equal(predict_labels, true_labels))
  164. LOGGER.info(TAG, "prediction accuracy before attacking is : %s",
  165. accuracy)
  166. test_images = test_images_set[:batch_num]
  167. # attacking
  168. norm = 'l2'
  169. search = 'grid_search'
  170. target = False
  171. attack = HopSkipJumpAttack(model, constraint=norm, stepsize_search=search)
  172. if target:
  173. target_labels = random_target_labels(true_labels)
  174. target_images = create_target_images(test_images_set, test_labels_set,
  175. target_labels)
  176. LOGGER.info(TAG, 'len target labels : %s', len(target_labels))
  177. LOGGER.info(TAG, 'len target_images : %s', len(target_images))
  178. LOGGER.info(TAG, 'len test_images : %s', len(test_images))
  179. attack.set_target_images(target_images)
  180. success_list, adv_data, _ = attack.generate(test_images, target_labels)
  181. else:
  182. success_list, adv_data, _ = attack.generate(test_images, None)
  183. assert (adv_data != test_images).any()
  184. adv_datas = []
  185. gts = []
  186. for success, adv, gt in zip(success_list, adv_data, true_labels):
  187. if success:
  188. adv_datas.append(adv)
  189. gts.append(gt)
  190. if gts:
  191. adv_datas = np.concatenate(np.asarray(adv_datas), axis=0)
  192. gts = np.asarray(gts)
  193. pred_logits_adv = model.predict(adv_datas)
  194. pred_lables_adv = np.argmax(pred_logits_adv, axis=1)
  195. accuracy_adv = np.mean(np.equal(pred_lables_adv, gts))
  196. LOGGER.info(TAG, 'mis-classification rate of adversaries is : %s',
  197. accuracy_adv)
  198. @pytest.mark.level0
  199. @pytest.mark.platform_arm_ascend_training
  200. @pytest.mark.platform_x86_ascend_training
  201. @pytest.mark.env_card
  202. @pytest.mark.component_mindarmour
  203. def test_value_error_ascend():
  204. context.set_context(device_target="Ascend")
  205. model = get_model()
  206. norm = 'l2'
  207. with pytest.raises(ValueError):
  208. assert HopSkipJumpAttack(model, constraint=norm, stepsize_search='bad-search')
  209. @pytest.mark.level0
  210. @pytest.mark.platform_x86_cpu
  211. @pytest.mark.env_card
  212. @pytest.mark.component_mindarmour
  213. def test_value_error_cpu():
  214. context.set_context(device_target="CPU")
  215. model = get_model()
  216. norm = 'l2'
  217. with pytest.raises(ValueError):
  218. assert HopSkipJumpAttack(model, constraint=norm, stepsize_search='bad-search')

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