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 9.0 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
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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 gc
  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 import BlackModel
  22. from mindarmour.adv_robustness.attacks import HopSkipJumpAttack
  23. from mindarmour.utils.logger import LogUtil
  24. from tests.ut.python.utils.mock_net import Net
  25. context.set_context(mode=context.GRAPH_MODE)
  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 create_target_images(dataset, data_labels, target_labels):
  49. res = []
  50. for label in target_labels:
  51. for i, data_label in enumerate(data_labels):
  52. if data_label == label:
  53. res.append(dataset[i])
  54. break
  55. return np.array(res)
  56. # public variable
  57. def get_model():
  58. # upload trained network
  59. current_dir = os.path.dirname(os.path.abspath(__file__))
  60. ckpt_path = os.path.join(current_dir,
  61. '../../../dataset/trained_ckpt_file/checkpoint_lenet-10_1875.ckpt')
  62. net = Net()
  63. load_dict = load_checkpoint(ckpt_path)
  64. load_param_into_net(net, load_dict)
  65. net.set_train(False)
  66. model = ModelToBeAttacked(net)
  67. return model
  68. @pytest.mark.level0
  69. @pytest.mark.platform_arm_ascend_training
  70. @pytest.mark.platform_x86_ascend_training
  71. @pytest.mark.env_card
  72. @pytest.mark.component_mindarmour
  73. def test_hsja_mnist_attack_ascend():
  74. """
  75. Feature: test HSJA attack for ascend
  76. Description: make sure the HSJA attack works properly
  77. Expectation: predict without any bugs
  78. """
  79. context.set_context(device_target="Ascend")
  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. '../../../dataset/test_images.npy'))
  84. test_labels_set = np.load(os.path.join(current_dir,
  85. '../../../dataset/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, _ = 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 gts:
  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. del pred_labels, adv_data, predict_labels, true_labels
  135. gc.collect()
  136. @pytest.mark.level0
  137. @pytest.mark.platform_x86_cpu
  138. @pytest.mark.env_card
  139. @pytest.mark.component_mindarmour
  140. def test_hsja_mnist_attack_cpu():
  141. """
  142. Feature: test HSJA attack for cpu
  143. Description: make sure the HSJA attack works properly
  144. Expectation: predict without any bugs
  145. """
  146. context.set_context(device_target="CPU")
  147. current_dir = os.path.dirname(os.path.abspath(__file__))
  148. # get test data
  149. test_images_set = np.load(os.path.join(current_dir,
  150. '../../../dataset/test_images.npy'))
  151. test_labels_set = np.load(os.path.join(current_dir,
  152. '../../../dataset/test_labels.npy'))
  153. # prediction accuracy before attack
  154. model = get_model()
  155. batch_num = 1 # the number of batches of attacking samples
  156. predict_labels = []
  157. i = 0
  158. for img in test_images_set:
  159. i += 1
  160. pred_labels = np.argmax(model.predict(img), axis=1)
  161. predict_labels.append(pred_labels)
  162. if i >= batch_num:
  163. break
  164. predict_labels = np.concatenate(predict_labels)
  165. true_labels = test_labels_set[:batch_num]
  166. accuracy = np.mean(np.equal(predict_labels, true_labels))
  167. LOGGER.info(TAG, "prediction accuracy before attacking is : %s",
  168. accuracy)
  169. test_images = test_images_set[:batch_num]
  170. # attacking
  171. norm = 'l2'
  172. search = 'grid_search'
  173. target = False
  174. attack = HopSkipJumpAttack(model, constraint=norm, stepsize_search=search)
  175. if target:
  176. target_labels = random_target_labels(true_labels)
  177. target_images = create_target_images(test_images_set, test_labels_set,
  178. target_labels)
  179. LOGGER.info(TAG, 'len target labels : %s', len(target_labels))
  180. LOGGER.info(TAG, 'len target_images : %s', len(target_images))
  181. LOGGER.info(TAG, 'len test_images : %s', len(test_images))
  182. attack.set_target_images(target_images)
  183. success_list, adv_data, _ = attack.generate(test_images, target_labels)
  184. else:
  185. success_list, adv_data, _ = attack.generate(test_images, None)
  186. assert (adv_data != test_images).any()
  187. adv_datas = []
  188. gts = []
  189. for success, adv, gt in zip(success_list, adv_data, true_labels):
  190. if success:
  191. adv_datas.append(adv)
  192. gts.append(gt)
  193. if gts:
  194. adv_datas = np.concatenate(np.asarray(adv_datas), axis=0)
  195. gts = np.asarray(gts)
  196. pred_logits_adv = model.predict(adv_datas)
  197. pred_lables_adv = np.argmax(pred_logits_adv, axis=1)
  198. accuracy_adv = np.mean(np.equal(pred_lables_adv, gts))
  199. LOGGER.info(TAG, 'mis-classification rate of adversaries is : %s',
  200. accuracy_adv)
  201. del pred_labels, adv_data, predict_labels, true_labels
  202. gc.collect()
  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. context.set_context(device_target="Ascend")
  210. model = get_model()
  211. norm = 'l2'
  212. with pytest.raises(ValueError):
  213. assert HopSkipJumpAttack(model, constraint=norm, stepsize_search='bad-search')
  214. @pytest.mark.level0
  215. @pytest.mark.platform_x86_cpu
  216. @pytest.mark.env_card
  217. @pytest.mark.component_mindarmour
  218. def test_value_error_cpu():
  219. context.set_context(device_target="CPU")
  220. model = get_model()
  221. norm = 'l2'
  222. with pytest.raises(ValueError):
  223. assert HopSkipJumpAttack(model, constraint=norm, stepsize_search='bad-search')

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