test_compressor.py 4.42 KB
Newer Older
1
from unittest import TestCase, main
2
import tensorflow as tf
3
4
import torch
import torch.nn.functional as F
5
6
import nni.compression.tensorflow as tf_compressor
import nni.compression.torch as torch_compressor
7

8

9
def weight_variable(shape):
10
11
    return tf.Variable(tf.truncated_normal(shape, stddev=0.1))

12
13

def bias_variable(shape):
14
15
    return tf.Variable(tf.constant(0.1, shape=shape))

16
17

def conv2d(x_input, w_matrix):
18
19
    return tf.nn.conv2d(x_input, w_matrix, strides=[1, 1, 1, 1], padding='SAME')

20
21

def max_pool(x_input, pool_size):
22
23
    size = [1, pool_size, pool_size, 1]
    return tf.nn.max_pool(x_input, ksize=size, strides=size, padding='SAME')
24
25
26
27


class TfMnist:
    def __init__(self):
28
29
        images = tf.placeholder(tf.float32, [None, 784], name='input_x')
        labels = tf.placeholder(tf.float32, [None, 10], name='input_y')
30
31
32
33
34
35
36
37
38
39
40
41
42
43
        keep_prob = tf.placeholder(tf.float32, name='keep_prob')

        self.images = images
        self.labels = labels
        self.keep_prob = keep_prob

        self.train_step = None
        self.accuracy = None

        self.w1 = None
        self.b1 = None
        self.fcw1 = None
        self.cross = None
        with tf.name_scope('reshape'):
44
            x_image = tf.reshape(images, [-1, 28, 28, 1])
45
        with tf.name_scope('conv1'):
46
            w_conv1 = weight_variable([5, 5, 1, 32])
47
            self.w1 = w_conv1
48
            b_conv1 = bias_variable([32])
49
50
51
52
53
            self.b1 = b_conv1
            h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)
        with tf.name_scope('pool1'):
            h_pool1 = max_pool(h_conv1, 2)
        with tf.name_scope('conv2'):
54
55
            w_conv2 = weight_variable([5, 5, 32, 64])
            b_conv2 = bias_variable([64])
56
57
58
59
            h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2)
        with tf.name_scope('pool2'):
            h_pool2 = max_pool(h_conv2, 2)
        with tf.name_scope('fc1'):
60
            w_fc1 = weight_variable([7 * 7 * 64, 1024])
61
            self.fcw1 = w_fc1
62
63
            b_fc1 = bias_variable([1024])
        h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
64
65
66
67
        h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, w_fc1) + b_fc1)
        with tf.name_scope('dropout'):
            h_fc1_drop = tf.nn.dropout(h_fc1, 0.5)
        with tf.name_scope('fc2'):
68
69
            w_fc2 = weight_variable([1024, 10])
            b_fc2 = bias_variable([10])
70
71
            y_conv = tf.matmul(h_fc1_drop, w_fc2) + b_fc2
        with tf.name_scope('loss'):
72
            cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=y_conv))
73
74
75
76
77
78
79
            self.cross = cross_entropy
        with tf.name_scope('adam_optimizer'):
            self.train_step = tf.train.AdamOptimizer(0.0001).minimize(cross_entropy)
        with tf.name_scope('accuracy'):
            correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(labels, 1))
            self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

80

81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
class TorchMnist(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = torch.nn.Conv2d(1, 20, 5, 1)
        self.conv2 = torch.nn.Conv2d(20, 50, 5, 1)
        self.fc1 = torch.nn.Linear(4 * 4 * 50, 500)
        self.fc2 = torch.nn.Linear(500, 10)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = F.max_pool2d(x, 2, 2)
        x = F.relu(self.conv2(x))
        x = F.max_pool2d(x, 2, 2)
        x = x.view(-1, 4 * 4 * 50)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
97
98
        return F.log_softmax(x, dim=1)

99
100
101
102

class CompressorTestCase(TestCase):
    def test_tf_pruner(self):
        model = TfMnist()
chicm-ms's avatar
chicm-ms committed
103
        configure_list = [{'sparsity': 0.8, 'op_types': ['default']}]
QuanluZhang's avatar
QuanluZhang committed
104
        tf_compressor.LevelPruner(tf.get_default_graph(), configure_list).compress()
105
106
107

    def test_tf_quantizer(self):
        model = TfMnist()
QuanluZhang's avatar
QuanluZhang committed
108
        tf_compressor.NaiveQuantizer(tf.get_default_graph(), [{'op_types': ['default']}]).compress()
109

110
111
    def test_torch_pruner(self):
        model = TorchMnist()
chicm-ms's avatar
chicm-ms committed
112
        configure_list = [{'sparsity': 0.8, 'op_types': ['default']}]
QuanluZhang's avatar
QuanluZhang committed
113
        torch_compressor.LevelPruner(model, configure_list).compress()
114

115
116
    def test_torch_quantizer(self):
        model = TorchMnist()
Cjkkkk's avatar
Cjkkkk committed
117
118
119
120
121
122
123
124
        configure_list = [{
            'quant_types': ['weight'],
            'quant_bits': {
                'weight': 8,
            },
            'op_types':['Conv2d', 'Linear']
        }]
        torch_compressor.NaiveQuantizer(model, configure_list).compress()
125
126
127
128


if __name__ == '__main__':
    main()