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_monitor.py 8.4 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. DP-Monitor test.
  16. """
  17. import pytest
  18. import numpy as np
  19. import mindspore.nn as nn
  20. import mindspore.dataset as ds
  21. from mindspore.train import Model
  22. import mindspore.context as context
  23. from mindarmour.privacy.diff_privacy import PrivacyMonitorFactory
  24. from mindarmour.utils.logger import LogUtil
  25. from ut.python.utils.mock_net import Net
  26. LOGGER = LogUtil.get_instance()
  27. TAG = 'DP-Monitor Test'
  28. def dataset_generator(batch_size, batches):
  29. data = np.random.random((batches * batch_size, 1, 32, 32)).astype(
  30. np.float32)
  31. label = np.random.randint(0, 10, batches * batch_size).astype(np.int32)
  32. for i in range(batches):
  33. yield data[i * batch_size: (i + 1) * batch_size], \
  34. label[i * batch_size: (i + 1) * batch_size]
  35. @pytest.mark.level0
  36. @pytest.mark.platform_arm_ascend_training
  37. @pytest.mark.platform_x86_ascend_training
  38. @pytest.mark.env_card
  39. @pytest.mark.component_mindarmour
  40. def test_dp_monitor():
  41. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  42. batch_size = 16
  43. batches = 128
  44. epochs = 1
  45. rdp = PrivacyMonitorFactory.create(policy='rdp', num_samples=60000,
  46. batch_size=batch_size,
  47. initial_noise_multiplier=0.4,
  48. noise_decay_rate=6e-3)
  49. suggest_epoch = rdp.max_epoch_suggest()
  50. LOGGER.info(TAG, 'The recommended maximum training epochs is: %s',
  51. suggest_epoch)
  52. network = Net()
  53. net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean")
  54. net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)
  55. model = Model(network, net_loss, net_opt)
  56. LOGGER.info(TAG, "============== Starting Training ==============")
  57. ds1 = ds.GeneratorDataset(dataset_generator(batch_size, batches),
  58. ["data", "label"])
  59. model.train(epochs, ds1, callbacks=[rdp], dataset_sink_mode=False)
  60. @pytest.mark.level0
  61. @pytest.mark.platform_x86_gpu_inference
  62. @pytest.mark.env_card
  63. @pytest.mark.component_mindarmour
  64. def test_dp_monitor_gpu():
  65. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  66. batch_size = 16
  67. batches = 128
  68. epochs = 1
  69. rdp = PrivacyMonitorFactory.create(policy='rdp', num_samples=60000,
  70. batch_size=batch_size,
  71. initial_noise_multiplier=0.4,
  72. noise_decay_rate=6e-3)
  73. suggest_epoch = rdp.max_epoch_suggest()
  74. LOGGER.info(TAG, 'The recommended maximum training epochs is: %s',
  75. suggest_epoch)
  76. network = Net()
  77. net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean")
  78. net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)
  79. model = Model(network, net_loss, net_opt)
  80. LOGGER.info(TAG, "============== Starting Training ==============")
  81. ds1 = ds.GeneratorDataset(dataset_generator(batch_size, batches),
  82. ["data", "label"])
  83. model.train(epochs, ds1, callbacks=[rdp], dataset_sink_mode=False)
  84. @pytest.mark.level0
  85. @pytest.mark.platform_x86_cpu
  86. @pytest.mark.env_card
  87. @pytest.mark.component_mindarmour
  88. def test_dp_monitor_cpu():
  89. context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
  90. batch_size = 16
  91. batches = 128
  92. epochs = 1
  93. rdp = PrivacyMonitorFactory.create(policy='rdp', num_samples=60000,
  94. batch_size=batch_size,
  95. initial_noise_multiplier=0.4,
  96. noise_decay_rate=6e-3)
  97. suggest_epoch = rdp.max_epoch_suggest()
  98. LOGGER.info(TAG, 'The recommended maximum training epochs is: %s',
  99. suggest_epoch)
  100. network = Net()
  101. net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean")
  102. net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)
  103. model = Model(network, net_loss, net_opt)
  104. LOGGER.info(TAG, "============== Starting Training ==============")
  105. ds1 = ds.GeneratorDataset(dataset_generator(batch_size, batches),
  106. ["data", "label"])
  107. model.train(epochs, ds1, callbacks=[rdp], dataset_sink_mode=False)
  108. @pytest.mark.level0
  109. @pytest.mark.platform_arm_ascend_training
  110. @pytest.mark.platform_x86_ascend_training
  111. @pytest.mark.env_card
  112. @pytest.mark.component_mindarmour
  113. def test_dp_monitor_zcdp():
  114. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  115. batch_size = 16
  116. batches = 128
  117. epochs = 1
  118. zcdp = PrivacyMonitorFactory.create(policy='zcdp', num_samples=60000,
  119. batch_size=batch_size,
  120. initial_noise_multiplier=0.4,
  121. noise_decay_rate=6e-3)
  122. suggest_epoch = zcdp.max_epoch_suggest()
  123. LOGGER.info(TAG, 'The recommended maximum training epochs is: %s',
  124. suggest_epoch)
  125. network = Net()
  126. net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean")
  127. net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)
  128. model = Model(network, net_loss, net_opt)
  129. LOGGER.info(TAG, "============== Starting Training ==============")
  130. ds1 = ds.GeneratorDataset(dataset_generator(batch_size, batches),
  131. ["data", "label"])
  132. model.train(epochs, ds1, callbacks=[zcdp], dataset_sink_mode=False)
  133. @pytest.mark.level0
  134. @pytest.mark.platform_x86_gpu_inference
  135. @pytest.mark.env_card
  136. @pytest.mark.component_mindarmour
  137. def test_dp_monitor_zcdp_gpu():
  138. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  139. batch_size = 16
  140. batches = 128
  141. epochs = 1
  142. zcdp = PrivacyMonitorFactory.create(policy='zcdp', num_samples=60000,
  143. batch_size=batch_size,
  144. initial_noise_multiplier=0.4,
  145. noise_decay_rate=6e-3)
  146. suggest_epoch = zcdp.max_epoch_suggest()
  147. LOGGER.info(TAG, 'The recommended maximum training epochs is: %s',
  148. suggest_epoch)
  149. network = Net()
  150. net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean")
  151. net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)
  152. model = Model(network, net_loss, net_opt)
  153. LOGGER.info(TAG, "============== Starting Training ==============")
  154. ds1 = ds.GeneratorDataset(dataset_generator(batch_size, batches),
  155. ["data", "label"])
  156. model.train(epochs, ds1, callbacks=[zcdp], dataset_sink_mode=False)
  157. @pytest.mark.level0
  158. @pytest.mark.platform_x86_cpu
  159. @pytest.mark.env_card
  160. @pytest.mark.component_mindarmour
  161. def test_dp_monitor_zcdp_cpu():
  162. context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
  163. batch_size = 16
  164. batches = 128
  165. epochs = 1
  166. zcdp = PrivacyMonitorFactory.create(policy='zcdp', num_samples=60000,
  167. batch_size=batch_size,
  168. initial_noise_multiplier=0.4,
  169. noise_decay_rate=6e-3)
  170. suggest_epoch = zcdp.max_epoch_suggest()
  171. LOGGER.info(TAG, 'The recommended maximum training epochs is: %s',
  172. suggest_epoch)
  173. network = Net()
  174. net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean")
  175. net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)
  176. model = Model(network, net_loss, net_opt)
  177. LOGGER.info(TAG, "============== Starting Training ==============")
  178. ds1 = ds.GeneratorDataset(dataset_generator(batch_size, batches),
  179. ["data", "label"])
  180. model.train(epochs, ds1, callbacks=[zcdp], dataset_sink_mode=False)

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