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.0 kB

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

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