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 10 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
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. 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 _pseudorandom_target(index, total_indices, true_class):
  48. """ pseudo random_target """
  49. rng = np.random.RandomState(index)
  50. target = true_class
  51. while target == true_class:
  52. target = rng.randint(0, total_indices)
  53. return target
  54. def create_target_images(dataset, data_labels, target_labels):
  55. res = []
  56. for label in target_labels:
  57. for i, data_label in enumerate(data_labels):
  58. if data_label == label:
  59. res.append(dataset[i])
  60. break
  61. return np.array(res)
  62. def get_model(current_dir):
  63. ckpt_path = os.path.join(current_dir,
  64. '../../../dataset/trained_ckpt_file/checkpoint_lenet-10_1875.ckpt')
  65. net = Net()
  66. load_dict = load_checkpoint(ckpt_path)
  67. load_param_into_net(net, load_dict)
  68. net.set_train(False)
  69. model = ModelToBeAttacked(net)
  70. return model
  71. def get_dataset(current_dir):
  72. # upload trained network
  73. # get test data
  74. test_images = np.load(os.path.join(current_dir,
  75. '../../../dataset/test_images.npy'))
  76. test_labels = np.load(os.path.join(current_dir,
  77. '../../../dataset/test_labels.npy'))
  78. return test_images, test_labels
  79. def nes_mnist_attack(scene, top_k):
  80. """
  81. hsja-Attack test
  82. """
  83. current_dir = os.path.dirname(os.path.abspath(__file__))
  84. test_images, test_labels = get_dataset(current_dir)
  85. model = get_model(current_dir)
  86. # prediction accuracy before attack
  87. batch_num = 5 # the number of batches of attacking samples
  88. predict_labels = []
  89. i = 0
  90. for img in test_images:
  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
  98. accuracy = np.mean(np.equal(predict_labels, true_labels[:batch_num]))
  99. LOGGER.info(TAG, "prediction accuracy before attacking is : %s",
  100. accuracy)
  101. test_images = test_images
  102. # attacking
  103. if scene == 'Query_Limit':
  104. top_k = -1
  105. elif scene == 'Partial_Info':
  106. top_k = top_k
  107. elif scene == 'Label_Only':
  108. top_k = top_k
  109. success = 0
  110. queries_num = 0
  111. nes_instance = NES(model, scene, top_k=top_k)
  112. test_length = 1
  113. advs = []
  114. for img_index in range(test_length):
  115. # INITIAL IMAGE AND CLASS SELECTION
  116. initial_img = test_images[img_index]
  117. orig_class = true_labels[img_index]
  118. initial_img = [initial_img]
  119. target_class = random_target_labels([orig_class])
  120. target_image = create_target_images(test_images, true_labels,
  121. target_class)
  122. nes_instance.set_target_images(target_image)
  123. tag, adv, queries = nes_instance.generate(np.array(initial_img), np.array(target_class))
  124. if tag[0]:
  125. success += 1
  126. queries_num += queries[0]
  127. advs.append(adv)
  128. advs = np.reshape(advs, (len(advs), 1, 32, 32))
  129. assert (advs != test_images[:batch_num]).any()
  130. adv_pred = np.argmax(model.predict(advs), axis=1)
  131. _ = np.mean(np.equal(adv_pred, true_labels[:test_length]))
  132. @pytest.mark.level0
  133. @pytest.mark.platform_arm_ascend_training
  134. @pytest.mark.platform_x86_ascend_training
  135. @pytest.mark.env_card
  136. @pytest.mark.component_mindarmour
  137. def test_nes_query_limit_ascend():
  138. """
  139. Feature: nes query limited for ascend
  140. Description: make sure the attck in query limit scene works properly
  141. Expectation: attack without any bugs
  142. """
  143. # scene is in ['Query_Limit', 'Partial_Info', 'Label_Only']
  144. context.set_context(device_target="Ascend")
  145. scene = 'Query_Limit'
  146. nes_mnist_attack(scene, top_k=-1)
  147. @pytest.mark.level0
  148. @pytest.mark.platform_x86_cpu
  149. @pytest.mark.env_card
  150. @pytest.mark.component_mindarmour
  151. def test_nes_query_limit_cpu():
  152. """
  153. Feature: nes query limited for cpu
  154. Description: make sure the attck in query limit scene works properly
  155. Expectation: attack without any bugs
  156. """
  157. # scene is in ['Query_Limit', 'Partial_Info', 'Label_Only']
  158. context.set_context(device_target="CPU")
  159. scene = 'Query_Limit'
  160. nes_mnist_attack(scene, top_k=-1)
  161. @pytest.mark.level0
  162. @pytest.mark.platform_arm_ascend_training
  163. @pytest.mark.platform_x86_ascend_training
  164. @pytest.mark.env_card
  165. @pytest.mark.component_mindarmour
  166. def test_nes_partial_info_ascend():
  167. """
  168. Feature: nes partial info for ascend
  169. Description: make sure the attck in partial info scene works properly
  170. Expectation: attack without any bugs
  171. """
  172. # scene is in ['Query_Limit', 'Partial_Info', 'Label_Only']
  173. context.set_context(device_target="Ascend")
  174. scene = 'Partial_Info'
  175. nes_mnist_attack(scene, top_k=5)
  176. @pytest.mark.level0
  177. @pytest.mark.platform_x86_cpu
  178. @pytest.mark.env_card
  179. @pytest.mark.component_mindarmour
  180. def test_nes_partial_info_cpu():
  181. """
  182. Feature: nes partial info for cpu
  183. Description: make sure the attck in partial info scene works properly
  184. Expectation: attack without any bugs
  185. """
  186. # scene is in ['Query_Limit', 'Partial_Info', 'Label_Only']
  187. context.set_context(device_target="CPU")
  188. scene = 'Partial_Info'
  189. nes_mnist_attack(scene, top_k=5)
  190. @pytest.mark.level0
  191. @pytest.mark.platform_arm_ascend_training
  192. @pytest.mark.platform_x86_ascend_training
  193. @pytest.mark.env_card
  194. @pytest.mark.component_mindarmour
  195. def test_nes_label_only_ascend():
  196. """
  197. Feature: nes label only for ascend
  198. Description: make sure the attck in label only scene works properly
  199. Expectation: attack without any bugs
  200. """
  201. # scene is in ['Query_Limit', 'Partial_Info', 'Label_Only']
  202. context.set_context(device_target="Ascend")
  203. scene = 'Label_Only'
  204. nes_mnist_attack(scene, top_k=5)
  205. @pytest.mark.level0
  206. @pytest.mark.platform_x86_cpu
  207. @pytest.mark.env_card
  208. @pytest.mark.component_mindarmour
  209. def test_nes_label_only_cpu():
  210. """
  211. Feature: nes label only for cpu
  212. Description: make sure the attck in label only scene works properly
  213. Expectation: attack without any bugs
  214. """
  215. # scene is in ['Query_Limit', 'Partial_Info', 'Label_Only']
  216. context.set_context(device_target="CPU")
  217. scene = 'Label_Only'
  218. nes_mnist_attack(scene, top_k=5)
  219. @pytest.mark.level0
  220. @pytest.mark.platform_arm_ascend_training
  221. @pytest.mark.platform_x86_ascend_training
  222. @pytest.mark.env_card
  223. @pytest.mark.component_mindarmour
  224. def test_value_error_ascend():
  225. """test that exception is raised for invalid labels"""
  226. context.set_context(device_target="Ascend")
  227. with pytest.raises(ValueError):
  228. assert nes_mnist_attack('Label_Only', -1)
  229. @pytest.mark.level0
  230. @pytest.mark.platform_x86_cpu
  231. @pytest.mark.env_card
  232. @pytest.mark.component_mindarmour
  233. def test_value_error_cpu():
  234. """test that exception is raised for invalid labels"""
  235. context.set_context(device_target="CPU")
  236. with pytest.raises(ValueError):
  237. assert nes_mnist_attack('Label_Only', -1)
  238. @pytest.mark.level0
  239. @pytest.mark.platform_arm_ascend_training
  240. @pytest.mark.platform_x86_ascend_training
  241. @pytest.mark.env_card
  242. @pytest.mark.component_mindarmour
  243. def test_none_ascend():
  244. """
  245. Feature: nes none for ascend
  246. Description: detect error or works properly
  247. Expectation: detect error or works properly
  248. """
  249. context.set_context(device_target="Ascend")
  250. current_dir = os.path.dirname(os.path.abspath(__file__))
  251. model = get_model(current_dir)
  252. test_images, test_labels = get_dataset(current_dir)
  253. nes = NES(model, 'Partial_Info')
  254. with pytest.raises(ValueError):
  255. assert nes.generate(test_images, test_labels)
  256. @pytest.mark.level0
  257. @pytest.mark.platform_x86_cpu
  258. @pytest.mark.env_card
  259. @pytest.mark.component_mindarmour
  260. def test_none_cpu():
  261. """
  262. Feature: nes none for cpu
  263. Description: detect error or works properly
  264. Expectation: detect error or works properly
  265. """
  266. context.set_context(device_target="CPU")
  267. current_dir = os.path.dirname(os.path.abspath(__file__))
  268. model = get_model(current_dir)
  269. test_images, test_labels = get_dataset(current_dir)
  270. nes = NES(model, 'Partial_Info')
  271. with pytest.raises(ValueError):
  272. assert nes.generate(test_images, test_labels)

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