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_model_train.py 6.1 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. # Copyright 2020 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-Model test.
  16. """
  17. import pytest
  18. import numpy as np
  19. from mindspore import nn
  20. from mindspore import context
  21. import mindspore.dataset as ds
  22. from mindarmour.privacy.diff_privacy import DPModel
  23. from mindarmour.privacy.diff_privacy import NoiseMechanismsFactory
  24. from mindarmour.privacy.diff_privacy import ClipMechanismsFactory
  25. from mindarmour.privacy.diff_privacy import DPOptimizerClassFactory
  26. from ut.python.utils.mock_net import Net
  27. def dataset_generator():
  28. """mock training data."""
  29. batch_size = 32
  30. batches = 128
  31. data = np.random.random((batches*batch_size, 1, 32, 32)).astype(
  32. np.float32)
  33. label = np.random.randint(0, 10, batches*batch_size).astype(np.int32)
  34. for i in range(batches):
  35. yield data[i*batch_size:(i + 1)*batch_size],\
  36. label[i*batch_size:(i + 1)*batch_size]
  37. @pytest.mark.level0
  38. @pytest.mark.platform_arm_ascend_training
  39. @pytest.mark.platform_x86_ascend_training
  40. @pytest.mark.env_card
  41. @pytest.mark.component_mindarmour
  42. def test_dp_model_with_pynative_mode():
  43. context.set_context(mode=context.PYNATIVE_MODE, device_target="Ascend")
  44. norm_bound = 1.0
  45. initial_noise_multiplier = 0.01
  46. network = Net()
  47. epochs = 1
  48. micro_batches = 2
  49. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True)
  50. factory_opt = DPOptimizerClassFactory(micro_batches=micro_batches)
  51. factory_opt.set_mechanisms('Gaussian',
  52. norm_bound=norm_bound,
  53. initial_noise_multiplier=initial_noise_multiplier)
  54. net_opt = factory_opt.create('Momentum')(network.trainable_params(),
  55. learning_rate=0.1, momentum=0.9)
  56. clip_mech = ClipMechanismsFactory().create('Gaussian',
  57. decay_policy='Linear',
  58. learning_rate=0.01,
  59. target_unclipped_quantile=0.9,
  60. fraction_stddev=0.01)
  61. model = DPModel(micro_batches=micro_batches,
  62. norm_bound=norm_bound,
  63. clip_mech=clip_mech,
  64. noise_mech=None,
  65. network=network,
  66. loss_fn=loss,
  67. optimizer=net_opt,
  68. metrics=None)
  69. ms_ds = ds.GeneratorDataset(dataset_generator,
  70. ['data', 'label'])
  71. model.train(epochs, ms_ds, dataset_sink_mode=False)
  72. @pytest.mark.level0
  73. @pytest.mark.platform_arm_ascend_training
  74. @pytest.mark.platform_x86_ascend_training
  75. @pytest.mark.env_card
  76. @pytest.mark.component_mindarmour
  77. def test_dp_model_with_graph_mode():
  78. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  79. norm_bound = 1.0
  80. initial_noise_multiplier = 0.01
  81. network = Net()
  82. epochs = 1
  83. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True)
  84. noise_mech = NoiseMechanismsFactory().create('Gaussian',
  85. norm_bound=norm_bound,
  86. initial_noise_multiplier=initial_noise_multiplier)
  87. clip_mech = ClipMechanismsFactory().create('Gaussian',
  88. decay_policy='Linear',
  89. learning_rate=0.01,
  90. target_unclipped_quantile=0.9,
  91. fraction_stddev=0.01)
  92. net_opt = nn.Momentum(network.trainable_params(), learning_rate=0.1,
  93. momentum=0.9)
  94. model = DPModel(micro_batches=2,
  95. clip_mech=clip_mech,
  96. norm_bound=norm_bound,
  97. noise_mech=noise_mech,
  98. network=network,
  99. loss_fn=loss,
  100. optimizer=net_opt,
  101. metrics=None)
  102. ms_ds = ds.GeneratorDataset(dataset_generator,
  103. ['data', 'label'])
  104. model.train(epochs, ms_ds, dataset_sink_mode=False)
  105. @pytest.mark.level0
  106. @pytest.mark.platform_arm_ascend_training
  107. @pytest.mark.platform_x86_ascend_training
  108. @pytest.mark.env_card
  109. @pytest.mark.component_mindarmour
  110. def test_dp_model_with_graph_mode_ada_gaussian():
  111. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  112. norm_bound = 1.0
  113. initial_noise_multiplier = 0.01
  114. network = Net()
  115. epochs = 1
  116. alpha = 0.8
  117. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True)
  118. noise_mech = NoiseMechanismsFactory().create('AdaGaussian',
  119. norm_bound=norm_bound,
  120. initial_noise_multiplier=initial_noise_multiplier,
  121. noise_decay_rate=alpha,
  122. decay_policy='Exp')
  123. clip_mech = None
  124. net_opt = nn.Momentum(network.trainable_params(), learning_rate=0.1,
  125. momentum=0.9)
  126. model = DPModel(micro_batches=2,
  127. clip_mech=clip_mech,
  128. norm_bound=norm_bound,
  129. noise_mech=noise_mech,
  130. network=network,
  131. loss_fn=loss,
  132. optimizer=net_opt,
  133. metrics=None)
  134. ms_ds = ds.GeneratorDataset(dataset_generator,
  135. ['data', 'label'])
  136. model.train(epochs, ms_ds, dataset_sink_mode=False)

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