lenet5_mnist_fuzzing.py 4.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# 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.
import sys

Z
zheng-huanhuan 已提交
16
import numpy as np
17 18 19 20 21
from mindspore import Model
from mindspore import context
from mindspore.train.serialization import load_checkpoint, load_param_into_net

from lenet5_net import LeNet5
Z
ZhidanLiu 已提交
22
from mindarmour.fuzzing.fuzzing import Fuzzer
Z
zheng-huanhuan 已提交
23 24
from mindarmour.fuzzing.model_coverage_metrics import ModelCoverageMetrics
from mindarmour.utils.logger import LogUtil
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

sys.path.append("..")
from data_processing import generate_mnist_dataset

LOGGER = LogUtil.get_instance()
TAG = 'Fuzz_test'
LOGGER.set_level('INFO')


def test_lenet_mnist_fuzzing():
    # upload trained network
    ckpt_name = './trained_ckpt_file/checkpoint_lenet-10_1875.ckpt'
    net = LeNet5()
    load_dict = load_checkpoint(ckpt_name)
    load_param_into_net(net, load_dict)
    model = Model(net)
Z
ZhidanLiu 已提交
41
    mutate_config = [{'method': 'Blur',
J
jin-xiulang 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
                      'params': {'auto_param': True}},
                     {'method': 'Contrast',
                      'params': {'auto_param': True}},
                     {'method': 'Translate',
                      'params': {'auto_param': True}},
                     {'method': 'Brightness',
                      'params': {'auto_param': True}},
                     {'method': 'Noise',
                      'params': {'auto_param': True}},
                     {'method': 'Scale',
                      'params': {'auto_param': True}},
                     {'method': 'Shear',
                      'params': {'auto_param': True}},
                     {'method': 'FGSM',
                      'params': {'eps': 0.3, 'alpha': 0.1}}
Z
ZhidanLiu 已提交
57
                    ]
58 59

    # get training data
60
    data_list = "./MNIST_unzip/train"
61
    batch_size = 32
Z
ZhidanLiu 已提交
62
    ds = generate_mnist_dataset(data_list, batch_size, sparse=False)
63 64 65 66 67 68 69
    train_images = []
    for data in ds.create_tuple_iterator():
        images = data[0].astype(np.float32)
        train_images.append(images)
    train_images = np.concatenate(train_images, axis=0)

    # initialize fuzz test with training dataset
Z
ZhidanLiu 已提交
70
    model_coverage_test = ModelCoverageMetrics(model, 10, 1000, train_images)
71 72 73

    # fuzz test with original test data
    # get test data
74
    data_list = "./MNIST_unzip/test"
75
    batch_size = 32
Z
ZhidanLiu 已提交
76
    ds = generate_mnist_dataset(data_list, batch_size, sparse=False)
77 78 79 80 81 82 83 84 85 86 87 88 89
    test_images = []
    test_labels = []
    for data in ds.create_tuple_iterator():
        images = data[0].astype(np.float32)
        labels = data[1]
        test_images.append(images)
        test_labels.append(labels)
    test_images = np.concatenate(test_images, axis=0)
    test_labels = np.concatenate(test_labels, axis=0)
    initial_seeds = []

    # make initial seeds
    for img, label in zip(test_images, test_labels):
J
jin-xiulang 已提交
90
        initial_seeds.append([img, label])
91 92

    initial_seeds = initial_seeds[:100]
Z
ZhidanLiu 已提交
93 94 95 96
    model_coverage_test.calculate_coverage(
        np.array(test_images[:100]).astype(np.float32))
    LOGGER.info(TAG, 'KMNC of this test is : %s',
                model_coverage_test.get_kmnc())
97

P
pkuliuliu 已提交
98
    model_fuzz_test = Fuzzer(model, train_images, 10, 1000)
Z
ZhidanLiu 已提交
99
    _, _, _, _, metrics = model_fuzz_test.fuzzing(mutate_config, initial_seeds,
P
pkuliuliu 已提交
100
                                                  eval_metrics='auto')
Z
ZhidanLiu 已提交
101 102 103
    if metrics:
        for key in metrics:
            LOGGER.info(TAG, key + ': %s', metrics[key])
104 105 106


if __name__ == '__main__':
107
    # device_target can be "CPU", "GPU" or "Ascend"
P
pkuliuliu 已提交
108
    context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
109
    test_lenet_mnist_fuzzing()