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.

fuzz_testing_and_model_enhense.py 7.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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. """
  15. An example of fuzz testing and then enhance non-robustness model.
  16. """
  17. import random
  18. import numpy as np
  19. import mindspore
  20. from mindspore import Model
  21. from mindspore import context
  22. from mindspore import Tensor
  23. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  24. from mindspore.nn import SoftmaxCrossEntropyWithLogits
  25. from mindspore.nn.optim.momentum import Momentum
  26. from mindarmour.adv_robustness.defenses import AdversarialDefense
  27. from mindarmour.fuzz_testing import Fuzzer
  28. from mindarmour.fuzz_testing import ModelCoverageMetrics
  29. from mindarmour.utils.logger import LogUtil
  30. from examples.common.dataset.data_processing import generate_mnist_dataset
  31. from examples.common.networks.lenet5.lenet5_net_for_fuzzing import LeNet5
  32. LOGGER = LogUtil.get_instance()
  33. TAG = 'Fuzz_testing and enhance model'
  34. LOGGER.set_level('INFO')
  35. def example_lenet_mnist_fuzzing():
  36. """
  37. An example of fuzz testing and then enhance the non-robustness model.
  38. """
  39. # upload trained network
  40. ckpt_path = '../common/networks/lenet5/trained_ckpt_file/lenet_m1-10_1250.ckpt'
  41. net = LeNet5()
  42. load_dict = load_checkpoint(ckpt_path)
  43. load_param_into_net(net, load_dict)
  44. model = Model(net)
  45. mutate_config = [{'method': 'Blur',
  46. 'params': {'auto_param': [True]}},
  47. {'method': 'Contrast',
  48. 'params': {'auto_param': [True]}},
  49. {'method': 'Translate',
  50. 'params': {'auto_param': [True]}},
  51. {'method': 'Brightness',
  52. 'params': {'auto_param': [True]}},
  53. {'method': 'Noise',
  54. 'params': {'auto_param': [True]}},
  55. {'method': 'Scale',
  56. 'params': {'auto_param': [True]}},
  57. {'method': 'Shear',
  58. 'params': {'auto_param': [True]}},
  59. {'method': 'FGSM',
  60. 'params': {'eps': [0.3, 0.2, 0.4], 'alpha': [0.1]}}
  61. ]
  62. # get training data
  63. data_list = "../common/dataset/MNIST/train"
  64. batch_size = 32
  65. ds = generate_mnist_dataset(data_list, batch_size, sparse=False)
  66. train_images = []
  67. for data in ds.create_tuple_iterator(output_numpy=True):
  68. images = data[0].astype(np.float32)
  69. train_images.append(images)
  70. train_images = np.concatenate(train_images, axis=0)
  71. neuron_num = 10
  72. segmented_num = 1000
  73. # initialize fuzz test with training dataset
  74. model_coverage_test = ModelCoverageMetrics(model, neuron_num, segmented_num, train_images)
  75. # fuzz test with original test data
  76. # get test data
  77. data_list = "../common/dataset/MNIST/test"
  78. batch_size = 32
  79. init_samples = 5000
  80. max_iters = 50000
  81. mutate_num_per_seed = 10
  82. ds = generate_mnist_dataset(data_list, batch_size, num_samples=init_samples,
  83. sparse=False)
  84. test_images = []
  85. test_labels = []
  86. for data in ds.create_tuple_iterator(output_numpy=True):
  87. images = data[0].astype(np.float32)
  88. labels = data[1]
  89. test_images.append(images)
  90. test_labels.append(labels)
  91. test_images = np.concatenate(test_images, axis=0)
  92. test_labels = np.concatenate(test_labels, axis=0)
  93. initial_seeds = []
  94. # make initial seeds
  95. for img, label in zip(test_images, test_labels):
  96. initial_seeds.append([img, label])
  97. model_coverage_test.calculate_coverage(
  98. np.array(test_images[:100]).astype(np.float32))
  99. LOGGER.info(TAG, 'KMNC of test dataset before fuzzing is : %s',
  100. model_coverage_test.get_kmnc())
  101. LOGGER.info(TAG, 'NBC of test dataset before fuzzing is : %s',
  102. model_coverage_test.get_nbc())
  103. LOGGER.info(TAG, 'SNAC of test dataset before fuzzing is : %s',
  104. model_coverage_test.get_snac())
  105. model_fuzz_test = Fuzzer(model, train_images, 10, 1000)
  106. gen_samples, gt, _, _, metrics = model_fuzz_test.fuzzing(mutate_config,
  107. initial_seeds,
  108. eval_metrics='auto',
  109. max_iters=max_iters,
  110. mutate_num_per_seed=mutate_num_per_seed)
  111. if metrics:
  112. for key in metrics:
  113. LOGGER.info(TAG, key + ': %s', metrics[key])
  114. def split_dataset(image, label, proportion):
  115. """
  116. Split the generated fuzz data into train and test set.
  117. """
  118. indices = np.arange(len(image))
  119. random.shuffle(indices)
  120. train_length = int(len(image) * proportion)
  121. train_image = [image[i] for i in indices[:train_length]]
  122. train_label = [label[i] for i in indices[:train_length]]
  123. test_image = [image[i] for i in indices[:train_length]]
  124. test_label = [label[i] for i in indices[:train_length]]
  125. return train_image, train_label, test_image, test_label
  126. train_image, train_label, test_image, test_label = split_dataset(
  127. gen_samples, gt, 0.7)
  128. # load model B and test it on the test set
  129. ckpt_path = '../common/networks/lenet5/trained_ckpt_file/lenet_m2-10_1250.ckpt'
  130. net = LeNet5()
  131. load_dict = load_checkpoint(ckpt_path)
  132. load_param_into_net(net, load_dict)
  133. model_b = Model(net)
  134. pred_b = model_b.predict(Tensor(test_image, dtype=mindspore.float32)).asnumpy()
  135. acc_b = np.sum(np.argmax(pred_b, axis=1) == np.argmax(test_label, axis=1)) / len(test_label)
  136. print('Accuracy of model B on test set is ', acc_b)
  137. # enhense model robustness
  138. lr = 0.001
  139. momentum = 0.9
  140. loss_fn = SoftmaxCrossEntropyWithLogits(Sparse=True)
  141. optimizer = Momentum(net.trainable_params(), lr, momentum)
  142. adv_defense = AdversarialDefense(net, loss_fn, optimizer)
  143. adv_defense.batch_defense(np.array(train_image).astype(np.float32),
  144. np.argmax(train_label, axis=1).astype(np.int32))
  145. preds_en = net(Tensor(test_image, dtype=mindspore.float32)).asnumpy()
  146. acc_en = np.sum(np.argmax(preds_en, axis=1) == np.argmax(test_label, axis=1)) / len(test_label)
  147. print('Accuracy of enhensed model on test set is ', acc_en)
  148. if __name__ == '__main__':
  149. # device_target can be "CPU", "GPU" or "Ascend"
  150. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  151. example_lenet_mnist_fuzzing()

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