test_monitor.py 8.8 KB
Newer Older
J
jin-xiulang 已提交
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 2019 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-Monitor test.
"""
import pytest
import numpy as np

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

25
from mindarmour.diff_privacy import PrivacyMonitorFactory
J
jin-xiulang 已提交
26 27
from mindarmour.utils.logger import LogUtil

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

J
jin-xiulang 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
LOGGER = LogUtil.get_instance()
TAG = 'DP-Monitor Test'


def dataset_generator(batch_size, batches):
    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
def test_dp_monitor():
    context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
    batch_size = 16
    batches = 128
    epochs = 1
    rdp = PrivacyMonitorFactory.create(policy='rdp', num_samples=60000,
                                       batch_size=batch_size,
                                       initial_noise_multiplier=0.4,
56
                                       noise_decay_rate=6e-3)
J
jin-xiulang 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
    suggest_epoch = rdp.max_epoch_suggest()
    LOGGER.info(TAG, 'The recommended maximum training epochs is: %s',
                suggest_epoch)
    network = LeNet5()
    net_loss = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True,
                                                reduction="mean")
    net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)

    model = Model(network, net_loss, net_opt)

    LOGGER.info(TAG, "============== Starting Training ==============")
    ds1 = ds.GeneratorDataset(dataset_generator(batch_size, batches),
                              ["data", "label"])
    ds1.set_dataset_size(batch_size * batches)
    model.train(epochs, ds1, callbacks=[rdp], dataset_sink_mode=False)


@pytest.mark.level0
@pytest.mark.platform_x86_gpu_inference
@pytest.mark.env_card
@pytest.mark.component_mindarmour
def test_dp_monitor_gpu():
    context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
    batch_size = 16
    batches = 128
    epochs = 1
    rdp = PrivacyMonitorFactory.create(policy='rdp', num_samples=60000,
                                       batch_size=batch_size,
                                       initial_noise_multiplier=0.4,
86
                                       noise_decay_rate=6e-3)
J
jin-xiulang 已提交
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
    suggest_epoch = rdp.max_epoch_suggest()
    LOGGER.info(TAG, 'The recommended maximum training epochs is: %s',
                suggest_epoch)
    network = LeNet5()
    net_loss = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True,
                                                reduction="mean")
    net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)

    model = Model(network, net_loss, net_opt)

    LOGGER.info(TAG, "============== Starting Training ==============")
    ds1 = ds.GeneratorDataset(dataset_generator(batch_size, batches),
                              ["data", "label"])
    ds1.set_dataset_size(batch_size * batches)
    model.train(epochs, ds1, callbacks=[rdp], dataset_sink_mode=False)


@pytest.mark.level0
@pytest.mark.platform_x86_cpu
@pytest.mark.env_card
@pytest.mark.component_mindarmour
def test_dp_monitor_cpu():
    context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
    batch_size = 16
    batches = 128
    epochs = 1
    rdp = PrivacyMonitorFactory.create(policy='rdp', num_samples=60000,
                                       batch_size=batch_size,
                                       initial_noise_multiplier=0.4,
116
                                       noise_decay_rate=6e-3)
J
jin-xiulang 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    suggest_epoch = rdp.max_epoch_suggest()
    LOGGER.info(TAG, 'The recommended maximum training epochs is: %s',
                suggest_epoch)
    network = LeNet5()
    net_loss = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True,
                                                reduction="mean")
    net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)

    model = Model(network, net_loss, net_opt)

    LOGGER.info(TAG, "============== Starting Training ==============")
    ds1 = ds.GeneratorDataset(dataset_generator(batch_size, batches),
                              ["data", "label"])
    ds1.set_dataset_size(batch_size * batches)
    model.train(epochs, ds1, callbacks=[rdp], dataset_sink_mode=False)
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222


@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_monitor_zcdp():
    context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
    batch_size = 16
    batches = 128
    epochs = 1
    zcdp = PrivacyMonitorFactory.create(policy='zcdp', num_samples=60000,
                                        batch_size=batch_size,
                                        initial_noise_multiplier=0.4,
                                        noise_decay_rate=6e-3)
    suggest_epoch = zcdp.max_epoch_suggest()
    LOGGER.info(TAG, 'The recommended maximum training epochs is: %s',
                suggest_epoch)
    network = LeNet5()
    net_loss = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True,
                                                reduction="mean")
    net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)

    model = Model(network, net_loss, net_opt)

    LOGGER.info(TAG, "============== Starting Training ==============")
    ds1 = ds.GeneratorDataset(dataset_generator(batch_size, batches),
                              ["data", "label"])
    ds1.set_dataset_size(batch_size * batches)
    model.train(epochs, ds1, callbacks=[zcdp], dataset_sink_mode=False)


@pytest.mark.level0
@pytest.mark.platform_x86_gpu_inference
@pytest.mark.env_card
@pytest.mark.component_mindarmour
def test_dp_monitor_zcdp_gpu():
    context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
    batch_size = 16
    batches = 128
    epochs = 1
    zcdp = PrivacyMonitorFactory.create(policy='zcdp', num_samples=60000,
                                        batch_size=batch_size,
                                        initial_noise_multiplier=0.4,
                                        noise_decay_rate=6e-3)
    suggest_epoch = zcdp.max_epoch_suggest()
    LOGGER.info(TAG, 'The recommended maximum training epochs is: %s',
                suggest_epoch)
    network = LeNet5()
    net_loss = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True,
                                                reduction="mean")
    net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)

    model = Model(network, net_loss, net_opt)

    LOGGER.info(TAG, "============== Starting Training ==============")
    ds1 = ds.GeneratorDataset(dataset_generator(batch_size, batches),
                              ["data", "label"])
    ds1.set_dataset_size(batch_size * batches)
    model.train(epochs, ds1, callbacks=[zcdp], dataset_sink_mode=False)


@pytest.mark.level0
@pytest.mark.platform_x86_cpu
@pytest.mark.env_card
@pytest.mark.component_mindarmour
def test_dp_monitor_zcdp_cpu():
    context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
    batch_size = 16
    batches = 128
    epochs = 1
    zcdp = PrivacyMonitorFactory.create(policy='zcdp', num_samples=60000,
                                        batch_size=batch_size,
                                        initial_noise_multiplier=0.4,
                                        noise_decay_rate=6e-3)
    suggest_epoch = zcdp.max_epoch_suggest()
    LOGGER.info(TAG, 'The recommended maximum training epochs is: %s',
                suggest_epoch)
    network = LeNet5()
    net_loss = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True,
                                                reduction="mean")
    net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)

    model = Model(network, net_loss, net_opt)

    LOGGER.info(TAG, "============== Starting Training ==============")
    ds1 = ds.GeneratorDataset(dataset_generator(batch_size, batches),
                              ["data", "label"])
    ds1.set_dataset_size(batch_size * batches)
    model.train(epochs, ds1, callbacks=[zcdp], dataset_sink_mode=False)