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

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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.diff_privacy import PrivacyMonitorFactory
  24. from mindarmour.utils.logger import LogUtil
  25. from test_network import LeNet5
  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 = LeNet5()
  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. ds1.set_dataset_size(batch_size * batches)
  60. model.train(epochs, ds1, callbacks=[rdp], dataset_sink_mode=False)
  61. @pytest.mark.level0
  62. @pytest.mark.platform_x86_gpu_inference
  63. @pytest.mark.env_card
  64. @pytest.mark.component_mindarmour
  65. def test_dp_monitor_gpu():
  66. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  67. batch_size = 16
  68. batches = 128
  69. epochs = 1
  70. rdp = PrivacyMonitorFactory.create(policy='rdp', num_samples=60000,
  71. batch_size=batch_size,
  72. initial_noise_multiplier=0.4,
  73. noise_decay_rate=6e-3)
  74. suggest_epoch = rdp.max_epoch_suggest()
  75. LOGGER.info(TAG, 'The recommended maximum training epochs is: %s',
  76. suggest_epoch)
  77. network = LeNet5()
  78. net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean")
  79. net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)
  80. model = Model(network, net_loss, net_opt)
  81. LOGGER.info(TAG, "============== Starting Training ==============")
  82. ds1 = ds.GeneratorDataset(dataset_generator(batch_size, batches),
  83. ["data", "label"])
  84. ds1.set_dataset_size(batch_size * batches)
  85. model.train(epochs, ds1, callbacks=[rdp], dataset_sink_mode=False)
  86. @pytest.mark.level0
  87. @pytest.mark.platform_x86_cpu
  88. @pytest.mark.env_card
  89. @pytest.mark.component_mindarmour
  90. def test_dp_monitor_cpu():
  91. context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
  92. batch_size = 16
  93. batches = 128
  94. epochs = 1
  95. rdp = PrivacyMonitorFactory.create(policy='rdp', num_samples=60000,
  96. batch_size=batch_size,
  97. initial_noise_multiplier=0.4,
  98. noise_decay_rate=6e-3)
  99. suggest_epoch = rdp.max_epoch_suggest()
  100. LOGGER.info(TAG, 'The recommended maximum training epochs is: %s',
  101. suggest_epoch)
  102. network = LeNet5()
  103. net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean")
  104. net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)
  105. model = Model(network, net_loss, net_opt)
  106. LOGGER.info(TAG, "============== Starting Training ==============")
  107. ds1 = ds.GeneratorDataset(dataset_generator(batch_size, batches),
  108. ["data", "label"])
  109. ds1.set_dataset_size(batch_size * batches)
  110. model.train(epochs, ds1, callbacks=[rdp], dataset_sink_mode=False)
  111. @pytest.mark.level0
  112. @pytest.mark.platform_arm_ascend_training
  113. @pytest.mark.platform_x86_ascend_training
  114. @pytest.mark.env_card
  115. @pytest.mark.component_mindarmour
  116. def test_dp_monitor_zcdp():
  117. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  118. batch_size = 16
  119. batches = 128
  120. epochs = 1
  121. zcdp = PrivacyMonitorFactory.create(policy='zcdp', num_samples=60000,
  122. batch_size=batch_size,
  123. initial_noise_multiplier=0.4,
  124. noise_decay_rate=6e-3)
  125. suggest_epoch = zcdp.max_epoch_suggest()
  126. LOGGER.info(TAG, 'The recommended maximum training epochs is: %s',
  127. suggest_epoch)
  128. network = LeNet5()
  129. net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean")
  130. net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)
  131. model = Model(network, net_loss, net_opt)
  132. LOGGER.info(TAG, "============== Starting Training ==============")
  133. ds1 = ds.GeneratorDataset(dataset_generator(batch_size, batches),
  134. ["data", "label"])
  135. ds1.set_dataset_size(batch_size * batches)
  136. model.train(epochs, ds1, callbacks=[zcdp], dataset_sink_mode=False)
  137. @pytest.mark.level0
  138. @pytest.mark.platform_x86_gpu_inference
  139. @pytest.mark.env_card
  140. @pytest.mark.component_mindarmour
  141. def test_dp_monitor_zcdp_gpu():
  142. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  143. batch_size = 16
  144. batches = 128
  145. epochs = 1
  146. zcdp = PrivacyMonitorFactory.create(policy='zcdp', num_samples=60000,
  147. batch_size=batch_size,
  148. initial_noise_multiplier=0.4,
  149. noise_decay_rate=6e-3)
  150. suggest_epoch = zcdp.max_epoch_suggest()
  151. LOGGER.info(TAG, 'The recommended maximum training epochs is: %s',
  152. suggest_epoch)
  153. network = LeNet5()
  154. net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean")
  155. net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)
  156. model = Model(network, net_loss, net_opt)
  157. LOGGER.info(TAG, "============== Starting Training ==============")
  158. ds1 = ds.GeneratorDataset(dataset_generator(batch_size, batches),
  159. ["data", "label"])
  160. ds1.set_dataset_size(batch_size * batches)
  161. model.train(epochs, ds1, callbacks=[zcdp], dataset_sink_mode=False)
  162. @pytest.mark.level0
  163. @pytest.mark.platform_x86_cpu
  164. @pytest.mark.env_card
  165. @pytest.mark.component_mindarmour
  166. def test_dp_monitor_zcdp_cpu():
  167. context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
  168. batch_size = 16
  169. batches = 128
  170. epochs = 1
  171. zcdp = PrivacyMonitorFactory.create(policy='zcdp', num_samples=60000,
  172. batch_size=batch_size,
  173. initial_noise_multiplier=0.4,
  174. noise_decay_rate=6e-3)
  175. suggest_epoch = zcdp.max_epoch_suggest()
  176. LOGGER.info(TAG, 'The recommended maximum training epochs is: %s',
  177. suggest_epoch)
  178. network = LeNet5()
  179. net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean")
  180. net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)
  181. model = Model(network, net_loss, net_opt)
  182. LOGGER.info(TAG, "============== Starting Training ==============")
  183. ds1 = ds.GeneratorDataset(dataset_generator(batch_size, batches),
  184. ["data", "label"])
  185. ds1.set_dataset_size(batch_size * batches)
  186. model.train(epochs, ds1, callbacks=[zcdp], dataset_sink_mode=False)

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