main_tf_pruner.py 4.65 KB
Newer Older
1
2
3
4
5
6
from nni.compression.tensorflow import AGP_Pruner
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data


def weight_variable(shape):
7
8
    return tf.Variable(tf.truncated_normal(shape, stddev=0.1))

9
10

def bias_variable(shape):
11
12
    return tf.Variable(tf.constant(0.1, shape=shape))

13
14

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

17
18

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


class Mnist:
    def __init__(self):
25
26
        images = tf.placeholder(tf.float32, [None, 784], name='input_x')
        labels = tf.placeholder(tf.float32, [None, 10], name='input_y')
27
28
29
30
31
32
33
34
35
36
37
38
39
40
        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'):
41
            x_image = tf.reshape(images, [-1, 28, 28, 1])
42
        with tf.name_scope('conv1'):
43
            w_conv1 = weight_variable([5, 5, 1, 32])
44
            self.w1 = w_conv1
45
            b_conv1 = bias_variable([32])
46
47
48
49
50
            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'):
51
52
            w_conv2 = weight_variable([5, 5, 32, 64])
            b_conv2 = bias_variable([64])
53
54
55
56
            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'):
57
            w_fc1 = weight_variable([7 * 7 * 64, 1024])
58
            self.fcw1 = w_fc1
59
60
            b_fc1 = bias_variable([1024])
        h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
61
62
63
64
        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'):
65
66
            w_fc2 = weight_variable([1024, 10])
            b_fc2 = bias_variable([10])
67
68
            y_conv = tf.matmul(h_fc1_drop, w_fc2) + b_fc2
        with tf.name_scope('loss'):
69
            cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=y_conv))
70
71
72
73
74
75
76
77
78
79
80
            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))


def main():
    tf.set_random_seed(0)

81
    data = input_data.read_data_sets('data', one_hot=True)
82
83
84

    model = Mnist()

85
86
    '''you can change this to LevelPruner to implement it
    pruner = LevelPruner(configure_list)
87
88
    '''
    configure_list = [{
89
90
91
92
93
        'initial_sparsity': 0,
        'final_sparsity': 0.8,
        'start_epoch': 0,
        'end_epoch': 10,
        'frequency': 1,
chicm-ms's avatar
chicm-ms committed
94
        'op_types': ['default']
95
    }]
QuanluZhang's avatar
QuanluZhang committed
96
    pruner = AGP_Pruner(tf.get_default_graph(), configure_list)
97
98
99
100
101
    # if you want to load from yaml file
    # configure_file = nni.compressors.tf_compressor._nnimc_tf._tf_default_load_configure_file('configure_example.yaml','AGPruner')
    # configure_list = configure_file.get('config',[])
    # pruner.load_configure(configure_list)
    # you can also handle it yourself and input an configure list in json
QuanluZhang's avatar
QuanluZhang committed
102
    pruner.compress()
103

104
105
106
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        for batch_idx in range(2000):
107
108
            if batch_idx % 10 == 0:
                pruner.update_epoch(batch_idx / 10, sess)
109
            batch = data.train.next_batch(2000)
110
            model.train_step.run(feed_dict={
111
112
113
114
115
                model.images: batch[0],
                model.labels: batch[1],
                model.keep_prob: 0.5
            })
            if batch_idx % 10 == 0:
116
                test_acc = model.accuracy.eval(feed_dict={
117
118
119
120
121
                    model.images: data.test.images,
                    model.labels: data.test.labels,
                    model.keep_prob: 1.0
                })
                print('test accuracy', test_acc)
122
123

        test_acc = model.accuracy.eval(feed_dict={
124
125
126
127
128
129
            model.images: data.test.images,
            model.labels: data.test.labels,
            model.keep_prob: 1.0
        })
        print('final result is', test_acc)

130
131
132

if __name__ == '__main__':
    main()