test_model_train.py 6.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
DP-Model test.
"""
import pytest
import numpy as np

from mindspore import nn
from mindspore import context
import mindspore.dataset as ds

from mindarmour.diff_privacy import DPModel
Z
ZhidanLiu 已提交
25 26
from mindarmour.diff_privacy import NoiseMechanismsFactory
from mindarmour.diff_privacy import ClipMechanismsFactory
27
from mindarmour.diff_privacy import DPOptimizerClassFactory
28

J
jin-xiulang 已提交
29 30
from test_network import LeNet5

31 32

def dataset_generator(batch_size, batches):
33
    """mock training data."""
Z
ZhidanLiu 已提交
34 35 36
    data = np.random.random((batches*batch_size, 1, 32, 32)).astype(
        np.float32)
    label = np.random.randint(0, 10, batches*batch_size).astype(np.int32)
37
    for i in range(batches):
Z
ZhidanLiu 已提交
38 39
        yield data[i*batch_size:(i + 1)*batch_size],\
              label[i*batch_size:(i + 1)*batch_size]
40 41 42 43 44 45 46


@pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_card
@pytest.mark.component_mindarmour
47
def test_dp_model_with_pynative_mode():
48
    context.set_context(mode=context.PYNATIVE_MODE, device_target="Ascend")
49
    norm_bound = 1.0
50
    initial_noise_multiplier = 0.01
51
    network = LeNet5()
52 53 54
    batch_size = 32
    batches = 128
    epochs = 1
55
    micro_batches = 2
56
    loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True)
57 58
    factory_opt = DPOptimizerClassFactory(micro_batches=micro_batches)
    factory_opt.set_mechanisms('Gaussian',
59
                               norm_bound=norm_bound,
60
                               initial_noise_multiplier=initial_noise_multiplier)
Z
ZhidanLiu 已提交
61 62 63 64 65 66 67
    net_opt = factory_opt.create('Momentum')(network.trainable_params(),
                                             learning_rate=0.1, momentum=0.9)
    clip_mech = ClipMechanismsFactory().create('Gaussian',
                                               decay_policy='Linear',
                                               learning_rate=0.01,
                                               target_unclipped_quantile=0.9,
                                               fraction_stddev=0.01)
68
    model = DPModel(micro_batches=micro_batches,
69
                    norm_bound=norm_bound,
Z
ZhidanLiu 已提交
70 71
                    clip_mech=clip_mech,
                    noise_mech=None,
72 73 74 75
                    network=network,
                    loss_fn=loss,
                    optimizer=net_opt,
                    metrics=None)
Z
ZhidanLiu 已提交
76 77 78
    ms_ds = ds.GeneratorDataset(dataset_generator(batch_size, batches),
                                ['data', 'label'])
    ms_ds.set_dataset_size(batch_size*batches)
79 80 81 82 83 84 85 86 87 88
    model.train(epochs, ms_ds, dataset_sink_mode=False)


@pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_card
@pytest.mark.component_mindarmour
def test_dp_model_with_graph_mode():
    context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
89
    norm_bound = 1.0
90 91 92 93 94
    initial_noise_multiplier = 0.01
    network = LeNet5()
    batch_size = 32
    batches = 128
    epochs = 1
95
    loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True)
Z
ZhidanLiu 已提交
96
    noise_mech = NoiseMechanismsFactory().create('Gaussian',
97
                                                 norm_bound=norm_bound,
Z
ZhidanLiu 已提交
98 99 100 101 102 103 104 105
                                                 initial_noise_multiplier=initial_noise_multiplier)
    clip_mech = ClipMechanismsFactory().create('Gaussian',
                                               decay_policy='Linear',
                                               learning_rate=0.01,
                                               target_unclipped_quantile=0.9,
                                               fraction_stddev=0.01)
    net_opt = nn.Momentum(network.trainable_params(), learning_rate=0.1,
                          momentum=0.9)
106
    model = DPModel(micro_batches=2,
Z
ZhidanLiu 已提交
107
                    clip_mech=clip_mech,
108
                    norm_bound=norm_bound,
Z
ZhidanLiu 已提交
109
                    noise_mech=noise_mech,
110
                    network=network,
111
                    loss_fn=loss,
112
                    optimizer=net_opt,
113
                    metrics=None)
Z
ZhidanLiu 已提交
114 115 116
    ms_ds = ds.GeneratorDataset(dataset_generator(batch_size, batches),
                                ['data', 'label'])
    ms_ds.set_dataset_size(batch_size*batches)
117
    model.train(epochs, ms_ds, dataset_sink_mode=False)
118 119 120 121 122 123 124 125 126


@pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_card
@pytest.mark.component_mindarmour
def test_dp_model_with_graph_mode_ada_gaussian():
    context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
127
    norm_bound = 1.0
128 129 130 131 132
    initial_noise_multiplier = 0.01
    network = LeNet5()
    batch_size = 32
    batches = 128
    epochs = 1
133
    alpha = 0.8
134
    loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True)
Z
ZhidanLiu 已提交
135
    noise_mech = NoiseMechanismsFactory().create('AdaGaussian',
136 137 138
                                                 norm_bound=norm_bound,
                                                 initial_noise_multiplier=initial_noise_multiplier,
                                                 noise_decay_rate=alpha,
139
                                                 decay_policy='Exp')
140
    clip_mech = None
Z
ZhidanLiu 已提交
141 142
    net_opt = nn.Momentum(network.trainable_params(), learning_rate=0.1,
                          momentum=0.9)
143
    model = DPModel(micro_batches=2,
Z
ZhidanLiu 已提交
144
                    clip_mech=clip_mech,
145
                    norm_bound=norm_bound,
Z
ZhidanLiu 已提交
146
                    noise_mech=noise_mech,
147 148 149 150
                    network=network,
                    loss_fn=loss,
                    optimizer=net_opt,
                    metrics=None)
Z
ZhidanLiu 已提交
151 152 153
    ms_ds = ds.GeneratorDataset(dataset_generator(batch_size, batches),
                                ['data', 'label'])
    ms_ds.set_dataset_size(batch_size*batches)
154
    model.train(epochs, ms_ds, dataset_sink_mode=False)