test_model_train.py 4.9 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
25 26
from mindarmour.diff_privacy import MechanismsFactory
from mindarmour.diff_privacy import DPOptimizerClassFactory
27

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

30 31

def dataset_generator(batch_size, batches):
32
    """mock training data."""
33 34 35 36 37 38 39 40 41 42 43
    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)
    for i in range(batches):
        yield data[i * batch_size:(i + 1) * batch_size], label[i * batch_size:(i + 1) * batch_size]


@pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_card
@pytest.mark.component_mindarmour
44
def test_dp_model_with_pynative_mode():
45
    context.set_context(mode=context.PYNATIVE_MODE, device_target="Ascend")
46
    norm_clip = 1.0
47
    initial_noise_multiplier = 0.01
48
    network = LeNet5()
49 50 51
    batch_size = 32
    batches = 128
    epochs = 1
52 53 54 55
    micro_batches = 2
    loss = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True)
    factory_opt = DPOptimizerClassFactory(micro_batches=micro_batches)
    factory_opt.set_mechanisms('Gaussian',
56
                               norm_bound=norm_clip,
57 58 59
                               initial_noise_multiplier=initial_noise_multiplier)
    net_opt = factory_opt.create('Momentum')(network.trainable_params(), learning_rate=0.1, momentum=0.9)
    model = DPModel(micro_batches=micro_batches,
60
                    norm_clip=norm_clip,
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
                    mech=None,
                    network=network,
                    loss_fn=loss,
                    optimizer=net_opt,
                    metrics=None)
    ms_ds = ds.GeneratorDataset(dataset_generator(batch_size, batches), ['data', 'label'])
    ms_ds.set_dataset_size(batch_size * batches)
    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")
78
    norm_clip = 1.0
79 80 81 82 83
    initial_noise_multiplier = 0.01
    network = LeNet5()
    batch_size = 32
    batches = 128
    epochs = 1
84
    loss = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True)
85
    mech = MechanismsFactory().create('Gaussian',
86
                                      norm_bound=norm_clip,
87 88
                                      initial_noise_multiplier=initial_noise_multiplier)
    net_opt = nn.Momentum(network.trainable_params(), learning_rate=0.1, momentum=0.9)
89
    model = DPModel(micro_batches=2,
90
                    norm_clip=norm_clip,
91
                    mech=mech,
92
                    network=network,
93
                    loss_fn=loss,
94
                    optimizer=net_opt,
95 96 97
                    metrics=None)
    ms_ds = ds.GeneratorDataset(dataset_generator(batch_size, batches), ['data', 'label'])
    ms_ds.set_dataset_size(batch_size * batches)
98
    model.train(epochs, ms_ds, dataset_sink_mode=False)
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128


@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")
    norm_clip = 1.0
    initial_noise_multiplier = 0.01
    network = LeNet5()
    batch_size = 32
    batches = 128
    epochs = 1
    loss = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True)
    mech = MechanismsFactory().create('AdaGaussian',
                                      norm_bound=norm_clip,
                                      initial_noise_multiplier=initial_noise_multiplier)
    net_opt = nn.Momentum(network.trainable_params(), learning_rate=0.1, momentum=0.9)
    model = DPModel(micro_batches=2,
                    norm_clip=norm_clip,
                    mech=mech,
                    network=network,
                    loss_fn=loss,
                    optimizer=net_opt,
                    metrics=None)
    ms_ds = ds.GeneratorDataset(dataset_generator(batch_size, batches), ['data', 'label'])
    ms_ds.set_dataset_size(batch_size * batches)
    model.train(epochs, ms_ds, dataset_sink_mode=False)