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_fuzzer.py 6.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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. Model-fuzzer test.
  16. """
  17. import numpy as np
  18. import pytest
  19. from mindspore import context
  20. from mindspore import nn
  21. from mindspore.common.initializer import TruncatedNormal
  22. from mindspore.ops import operations as P
  23. from mindspore.train import Model
  24. from mindspore.ops import TensorSummary
  25. from mindarmour.fuzz_testing import Fuzzer
  26. from mindarmour.fuzz_testing import KMultisectionNeuronCoverage
  27. from mindarmour.utils.logger import LogUtil
  28. LOGGER = LogUtil.get_instance()
  29. TAG = 'Fuzzing test'
  30. LOGGER.set_level('INFO')
  31. def conv(in_channels, out_channels, kernel_size, stride=1, padding=0):
  32. weight = weight_variable()
  33. return nn.Conv2d(in_channels, out_channels,
  34. kernel_size=kernel_size, stride=stride, padding=padding,
  35. weight_init=weight, has_bias=False, pad_mode="valid")
  36. def fc_with_initialize(input_channels, out_channels):
  37. weight = weight_variable()
  38. bias = weight_variable()
  39. return nn.Dense(input_channels, out_channels, weight, bias)
  40. def weight_variable():
  41. return TruncatedNormal(0.02)
  42. class Net(nn.Cell):
  43. """
  44. Lenet network
  45. """
  46. def __init__(self):
  47. super(Net, self).__init__()
  48. self.conv1 = conv(1, 6, 5)
  49. self.conv2 = conv(6, 16, 5)
  50. self.fc1 = fc_with_initialize(16 * 5 * 5, 120)
  51. self.fc2 = fc_with_initialize(120, 84)
  52. self.fc3 = fc_with_initialize(84, 10)
  53. self.relu = nn.ReLU()
  54. self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)
  55. self.reshape = P.Reshape()
  56. self.summary = TensorSummary()
  57. def construct(self, x):
  58. x = self.conv1(x)
  59. x = self.relu(x)
  60. self.summary('conv1', x)
  61. x = self.max_pool2d(x)
  62. x = self.conv2(x)
  63. x = self.relu(x)
  64. self.summary('conv2', x)
  65. x = self.max_pool2d(x)
  66. x = self.reshape(x, (-1, 16 * 5 * 5))
  67. x = self.fc1(x)
  68. x = self.relu(x)
  69. self.summary('fc1', x)
  70. x = self.fc2(x)
  71. x = self.relu(x)
  72. self.summary('fc2', x)
  73. x = self.fc3(x)
  74. self.summary('fc3', x)
  75. return x
  76. @pytest.mark.level0
  77. @pytest.mark.platform_x86_ascend_training
  78. @pytest.mark.platform_arm_ascend_training
  79. @pytest.mark.env_onecard
  80. @pytest.mark.component_mindarmour
  81. def test_fuzzing_ascend():
  82. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  83. # load network
  84. net = Net()
  85. model = Model(net)
  86. batch_size = 8
  87. num_classe = 10
  88. mutate_config = [{'method': 'GaussianBlur',
  89. 'params': {'ksize': [1, 2, 3, 5],
  90. 'auto_param': [True, False]}},
  91. {'method': 'UniformNoise',
  92. 'params': {'factor': [0.1, 0.2, 0.3], 'auto_param': [False, True]}},
  93. {'method': 'Contrast',
  94. 'params': {'alpha': [0.5, 1, 1.5], 'beta': [-10, 0, 10], 'auto_param': [False, True]}},
  95. {'method': 'Rotate',
  96. 'params': {'angle': [20, 90], 'auto_param': [False, True]}},
  97. {'method': 'FGSM',
  98. 'params': {'eps': [0.3, 0.2, 0.4], 'alpha': [0.1], 'bounds': [(0, 1)]}}]
  99. train_images = np.random.rand(32, 1, 32, 32).astype(np.float32)
  100. # fuzz test with original test data
  101. # get test data
  102. test_images = np.random.rand(batch_size, 1, 32, 32).astype(np.float32)
  103. test_labels = np.random.randint(num_classe, size=batch_size).astype(np.int32)
  104. test_labels = (np.eye(num_classe)[test_labels]).astype(np.float32)
  105. initial_seeds = []
  106. # make initial seeds
  107. for img, label in zip(test_images, test_labels):
  108. initial_seeds.append([img, label])
  109. initial_seeds = initial_seeds[:100]
  110. nc = KMultisectionNeuronCoverage(model, train_images, segmented_num=100)
  111. cn_metrics = nc.get_metrics(test_images[:100])
  112. print('neuron coverage of initial seeds is: ', cn_metrics)
  113. model_fuzz_test = Fuzzer(model)
  114. _, _, _, _, metrics = model_fuzz_test.fuzzing(mutate_config, initial_seeds, nc, max_iters=100)
  115. print(metrics)
  116. @pytest.mark.level0
  117. @pytest.mark.platform_x86_cpu
  118. @pytest.mark.env_onecard
  119. @pytest.mark.component_mindarmour
  120. def test_fuzzing_cpu():
  121. context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
  122. # load network
  123. net = Net()
  124. model = Model(net)
  125. batch_size = 8
  126. num_classe = 10
  127. mutate_config = [{'method': 'GaussianBlur',
  128. 'params': {'ksize': [1, 2, 3, 5],
  129. 'auto_param': [True, False]}},
  130. {'method': 'UniformNoise',
  131. 'params': {'factor': [0.1, 0.2, 0.3], 'auto_param': [False, True]}},
  132. {'method': 'Contrast',
  133. 'params': {'alpha': [0.5, 1, 1.5], 'beta': [-10, 0, 10], 'auto_param': [False, True]}},
  134. {'method': 'Rotate',
  135. 'params': {'angle': [20, 90], 'auto_param': [False, True]}},
  136. {'method': 'FGSM',
  137. 'params': {'eps': [0.3, 0.2, 0.4], 'alpha': [0.1], 'bounds': [(0, 1)]}}]
  138. # initialize fuzz test with training dataset
  139. train_images = np.random.rand(32, 1, 32, 32).astype(np.float32)
  140. # fuzz test with original test data
  141. # get test data
  142. test_images = np.random.rand(batch_size, 1, 32, 32).astype(np.float32)
  143. test_labels = np.random.randint(num_classe, size=batch_size).astype(np.int32)
  144. test_labels = (np.eye(num_classe)[test_labels]).astype(np.float32)
  145. initial_seeds = []
  146. # make initial seeds
  147. for img, label in zip(test_images, test_labels):
  148. initial_seeds.append([img, label])
  149. initial_seeds = initial_seeds[:100]
  150. nc = KMultisectionNeuronCoverage(model, train_images, segmented_num=100)
  151. tknc_metrics = nc.get_metrics(test_images[:100])
  152. print('neuron coverage of initial seeds is: ', tknc_metrics)
  153. model_fuzz_test = Fuzzer(model)
  154. _, _, _, _, metrics = model_fuzz_test.fuzzing(mutate_config, initial_seeds, nc, max_iters=100)
  155. print(metrics)

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