To receive notifications about scheduled maintenance, please subscribe to the mailing-list gitlab-operations@sympa.ethz.ch. You can subscribe to the mailing-list at https://sympa.ethz.ch

INQ_layers.py 26.5 KB
Newer Older
matthmey's avatar
matthmey committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
56
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
86
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
"""
Copyright (c) 2019, Swiss Federal Institute of Technology (ETH Zurich)
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""


from __future__ import print_function

import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Reshape, Activation
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras import backend as K
from keras.engine import InputSpec
import numpy as np




class INQ_Conv2D(Conv2D):
    '''
    this is a copy of the Conv2D with masks enabled...
    TODO: proper function explanaition
    '''

    def partition_weights(self, step, strategy, seed):
        '''Does the book-keeping of the accumulated portions of weights to quantize.
        Also, an additional kernel variable, called kernel_for_quantization is updated, of which the actual quantization
        function (below) needs the value before chaning the mask, i.e. its value right after re-training in the last
        step.'''
        if strategy == 'random':
            # Kernel stuff
            ################################################################################################################
            self.kernel_for_quantization = K.eval(self.kernel)  # the values in the kernel that need to be quantized in the current step
                                                                # must be fetched NOW as after updating the mask the kernel won't hold the weights
                                                                # that were just re-trained, anymore, because the new mask will neutralize them.
            temp = self.mask_np > 0
            temp_int = K.eval(temp)
            temp_int = temp_int.astype(int)

            # determine indices which are not quantized yet
            mm, nn, kk, ll = np.where(temp_int > 0)

            # determine the number of items to quantize in the current iteration
            no_total = np.size(temp_int)                                # The total amount of elements (quantized and non-quantized)
            no_due = np.floor(no_total*step)                            # This amount of elements must be quantized in the next call of the quantize()-function
            no_so_far = np.floor(no_total*K.eval(self.previous_step))   # Amount of weights that were already quantized
            self.delta = int(no_due - no_so_far)                        # Amount of NEW elements that must be quantized. Saved globally for efficiency
                                                                        # reasons during quantization.

            if self.delta > 0:  # it's better to not do this check via the step variable in INQ_model.py because for
                                # very tiny steps the delta might be zero although the step itself is non-zero!

                # among all non-quantized elements choose delta items after shuffling them
                indices = np.arange(np.size(mm))
                if seed is not None:
                    np.random.seed(seed=seed)
                np.random.shuffle(indices)  # in-place
                indices = indices[0:self.delta]  # from all selectable indices only choose the necessary amount
                mm = mm[indices]
                nn = nn[indices]
                kk = kk[indices]
                ll = ll[indices]

                # update the mask
                temp_int[mm, nn, kk, ll] = 0    # in-place
                K.set_value(self.mask_np, temp_int)
            else:
                print('self.delta was zero during partitioning. --> No changes in self.mask_np')

            # Bias stuff analog to kernel stuff
            ################################################################################################################
            if self.use_bias:
                self.bias_for_quantization = K.eval(self.bias)

                temp = self.mask_bias > 0
                temp_int = K.eval(temp)
                temp_int = temp_int.astype(int)

                mm = np.where(temp_int > 0)[0]

                no_total = np.size(temp_int)
                no_due = np.floor(no_total*step)
                no_so_far = np.floor(no_total*K.eval(self.previous_step))
                self.delta_bias = int(no_due - no_so_far)

                if self.delta_bias > 0:
                    indices = np.arange(np.size(mm))
                    np.random.shuffle(indices)
                    indices = indices[0:self.delta_bias]
                    mm = mm[indices]

                    temp_int[mm] = 0
                    K.set_value(self.mask_bias, temp_int)
                else:
                    print('self.delta_bias was zero during partitioning. --> No changes in self.mask_bias')
            else:
                print('Biases are disabled for this layer.')


        # needed in the next call of this fn
        K.set_value(self.previous_step, step)









    def quantize(self, bits):
        # Kernel stuff
        ################################################################################################################
        if self.delta > 0:
            # determine the new set A^(1) (step 4 in the algorithm according to the INQ-paper)
            inv_mask_np = -self.mask_np + 1
            set_a1 = self.kernel_for_quantization * K.eval(inv_mask_np)   # extracting the already quantized values plus the
                                                                        # ones that are to be quantized in this step

            # determine the new set P_l (step 5)
            s = np.max(np.abs(set_a1))
            if s > 0:
                n1 = np.floor(np.log2(4*s/3))
                n2 = n1 + 1 - np.power(2, (bits - 1))/2
                p_set = [0]
                for ii in range(int(n1 - n2) + 1):
                    exponent = n2 + ii
                    elem = np.power(2, exponent)
                    #if ii < range(int(n1 - n2) + 1)[-1] and K.eval(self.previous_step) < 0.9:
                    #    elem = 0
                    p_set.append(elem)
                p_set.sort()   # in-place

                # quantize the weights in A^(1) (step 6)
                for elem in np.nditer(set_a1, op_flags=['readwrite']):
                    if elem != 0:
                        temp = 0
                        for ii in range(np.size(p_set) - 1):
                            alpha = p_set[ii]
                            beta = p_set[ii + 1]
                            if np.less(np.abs(elem), 3*beta/2) and np.greater_equal(np.abs(elem), (alpha + beta)/2):
                                temp = beta*np.sign(elem)
                                break

                        elem[...] = temp

                K.set_value(self.kernel_nontrainable, set_a1)   # update the (quantized) kernel_nontrainable variable
            else:
                print('The "s" parameter was zero during quantization! Does the model really have an all-zero kernel?')
        else:
            print('self.delta was zero. --> Hence, the masks were not changed and thus the kernel wont be changed either.')

        # Bias stuff analog to kernel stuff
        ################################################################################################################
        if self.use_bias:
            if self.delta_bias > 0:
                inv_mask_bias = -self.mask_bias + 1
                set_a1_bias = self.bias_for_quantization * K.eval(inv_mask_bias)

                s = np.max(np.abs(set_a1_bias))
                if s > 0:
                    n1 = np.floor(np.log2(4*s/3))
                    n2 = n1 + 1 - np.power(2, (bits - 1))/2
                    p_set = [0]
                    for ii in range(int(n1 - n2) + 1):
                        exponent = n2 + ii
                        elem = np.power(2, exponent)
                        p_set.append(elem)
                    p_set.sort()

                    for elem in np.nditer(set_a1_bias, op_flags=['readwrite']):
                        if elem != 0:
                            temp = 0
                            for ii in range(np.size(p_set) - 1):
                                alpha = p_set[ii]
                                beta = p_set[ii + 1]
                                if np.less(np.abs(elem), 3 * beta / 2) and np.greater_equal(np.abs(elem), (alpha + beta)/2):
                                    temp = beta * np.sign(elem)
                                    break

                            elem[...] = temp

                    K.set_value(self.bias_nontrainable, set_a1_bias)
                else:
                    print('There were zero elements to quantize. Does the model really have all-zero biases?')
            else:
                print('self.delta was zero. --> The masks were hence not changed and thus the kernel is wont be changed either.')
        else:
            print('Biases are disabled for this layer.')




    def set_inq_flag(self):
        K.set_value(self.is_inq_layer, 1)



    # Only for verification after loading a saved INQ-model
    def save_initial_weights(self, weights):
        self.initial_weights = weights




    # called when layer added to model
    # This is where you define your weights. NOTE: only weights are saved when calling model.save(), so for re-training
    # or to allow continuing a disrupted INQ-process, you need to store all relevant information as (non-trainable)
    # weights!
    # This method must set self.built = True.
    def build(self, input_shape):

        # This part is copied from the original "_Conv" layer. The custom stuff is below this part.
        ################################################################################################################
        if self.data_format == 'channels_first':
            channel_axis = 1
        else:
            channel_axis = -1
        if input_shape[channel_axis] is None:
            raise ValueError('The channel dimension of the inputs '
                             'should be defined. Found `None`.')
        input_dim = input_shape[channel_axis]
        self.kernel_shape = self.kernel_size + (input_dim, self.filters)


        # Now the custom stuff
        ################################################################################################################
        print('mybuild: INQ_Conv2D')

        self.kernel_trainable = self.add_weight(shape=self.kernel_shape,    # This kernel is updated during back-prop, using the calculated gradients.
                                                initializer='zeros',
                                                name='kernel_trainable',
                                                regularizer=self.kernel_regularizer,
                                                constraint=self.kernel_constraint, trainable=True)

        if self.use_bias:
            self.bias_trainable = self.add_weight(shape=(self.filters,),
                                                  initializer='zeros',
                                                  name='bias_trainable',
                                                  regularizer=self.bias_regularizer,
                                                  constraint=self.bias_constraint, trainable=True)
        else:
            self.bias = None


        # Kernel stuff
        ################################################################################################################
        if hasattr(self, 'initial_weights'):
            K.set_value(self.kernel_trainable, self.initial_weights[0])     # Set initial weights to the pre-trained values if they exist

        # Initialize a second kernel, used to store the quantized values.
        # This kernel is updated in the quantize function (above) and only contains quantized weights and zeros.
        self.kernel_nontrainable = self.add_weight(shape=self.kernel_shape,
                                                   initializer='zeros',
                                                   name='kernel_nontrainable',
                                                   trainable=False)
        # initialize mask
        self.mask_np = self.add_weight(shape=self.kernel_shape,
                                       initializer='ones',
                                       name='mask_np',
                                       trainable=False)

        # Create the kernel that is used for forward computation and back-propagation
        # Note that it is not trainable itself but is the sum of a trainable and a non-trainable tensor.
        # During back-propagation only the trainable tensor is updated. Among these updates the ones
        # that coincide with a zero in the mask_np variable are ignored and instead the corresponding values
        # from (the quantized) kernel_nontrainable variable are used.
        inv_mask_np = -self.mask_np + 1
        self.kernel = self.kernel_trainable * self.mask_np + self.kernel_nontrainable * inv_mask_np

        # Bias stuff analog to kernel stuff from above
        ################################################################################################################
        if self.use_bias:
            if hasattr(self, 'initial_weights'):
                K.set_value(self.bias_trainable, self.initial_weights[1])

            self.bias_nontrainable = self.add_weight(shape=(self.filters,),
                                                     initializer='zeros',
                                                     name='bias_nontrainable',
                                                     trainable=False)

            self.mask_bias = self.add_weight(shape=(self.filters,),
                                             initializer='ones',
                                             name='mask_bias',
                                             trainable=False)

            inv_mask_bias = -self.mask_bias + 1
            self.bias = self.bias_trainable * self.mask_bias + self.bias_nontrainable * inv_mask_bias


        # General stuff
        ################################################################################################################
        self.is_inq_layer = self.add_weight(shape=(),
                                            initializer='zeros',
                                            name='is_inq', trainable=False)

        self.previous_step = self.add_weight(shape=(),
                                             initializer='zeros',
                                             name='previous_step', trainable=False)

        # Again stuff of the base class
        ################################################################################################################

        # Set input spec.
        self.input_spec = InputSpec(ndim=self.rank + 2, axes={channel_axis: input_dim})
        self.built = True


















class INQ_Dense(Dense):
    '''
    this is a copy of the Dense with masks enabled...
    TODO: proper function explanaition
    '''

    # because this operation is done only a few times (after every training epoch) I use numpy for the implementation
    def partition_weights(self, step, strategy, seed):
        if strategy == 'random':
            # Kernel stuff
            ############################################################################################################
            self.kernel_for_quantization = K.eval(self.kernel)

            temp = self.mask_np > 0
            temp_int = K.eval(temp)
            temp_int = temp_int.astype(int)

            mm, nn = np.where(temp_int > 0)

            no_total = np.size(temp_int)
            no_due = np.floor(no_total * step)
            no_so_far = np.floor(no_total * K.eval(self.previous_step))
            self.delta = int(no_due - no_so_far)

            if self.delta > 0:
                indices = np.arange(np.size(mm))
                if seed is not None:
                    np.random.seed(seed=seed)
                np.random.shuffle(indices)
                indices = indices[0:self.delta]  # from all selectable indices only choose the necessary amount
                mm = mm[indices]
                nn = nn[indices]

                temp_int[mm, nn] = 0
                K.set_value(self.mask_np, temp_int)
            else:
                print('self.delta was zero during partitioning. --> No changes in self.mask_np')

            # Bias stuff analog to kernel stuff
            ################################################################################################################
            if self.use_bias:
                self.bias_for_quantization = K.eval(self.bias)

                temp = self.mask_bias > 0
                temp_int = K.eval(temp)
                temp_int = temp_int.astype(int)

                mm = np.where(temp_int > 0)[0]

                no_total = np.size(temp_int)
                no_due = np.floor(no_total * step)
                no_so_far = np.floor(no_total * K.eval(self.previous_step))
                self.delta_bias = int(no_due - no_so_far)

                if self.delta_bias > 0:
                    indices = np.arange(np.size(mm))
                    np.random.shuffle(indices)
                    indices = indices[0:self.delta_bias]
                    mm = mm[indices]

                    temp_int[mm] = 0
                    K.set_value(self.mask_bias, temp_int)
                else:
                    print('self.delta_bias was zero during partitioning. --> No changes in self.mask_bias')
            else:
                print('Biases are disabled for this layer.')


        # needed in the next call of this fn
        K.set_value(self.previous_step, step)



    def quantize(self, bits):
        # Kernel stuff
        ################################################################################################################
        if self.delta > 0:
            inv_mask_np = -self.mask_np + 1
            set_a1 = self.kernel_for_quantization * K.eval(inv_mask_np)

            s = np.max(np.abs(set_a1))
            if s > 0:
                n1 = np.floor(np.log2(4 * s / 3))
                n2 = n1 + 1 - np.power(2, (bits - 1)) / 2
                p_set = [0]
                for ii in range(int(n1 - n2) + 1):
                    exponent = n2 + ii
                    elem = np.power(2, exponent)
                    #if ii < range(int(n1 - n2) + 1)[-1] and K.eval(self.previous_step) < 0.9:
                    #    elem = 0
                    p_set.append(elem)
                p_set.sort()

                for elem in np.nditer(set_a1, op_flags=['readwrite']):
                    if elem != 0:
                        temp = 0
                        for ii in range(np.size(p_set) - 1):
                            alpha = p_set[ii]
                            beta = p_set[ii + 1]
                            if np.less(np.abs(elem), 3 * beta / 2) and np.greater_equal(np.abs(elem), (alpha + beta) / 2):
                                temp = beta * np.sign(elem)
                                break

                        elem[...] = temp

                K.set_value(self.kernel_nontrainable, set_a1)  # update the (quantized) kernel_nontrainable variable
            else:
                print('The "s" parameter was zero during quantization! Does the model really have an all-zero kernel?')
        else:
            print(
                'self.delta was zero. --> Hence, the masks were not changed and thus the kernel wont be changed either.')

        # Bias stuff analog to kernel stuff
        ################################################################################################################
        if self.use_bias:
            if self.delta_bias > 0:
                inv_mask_bias = -self.mask_bias + 1
                set_a1_bias = self.bias_for_quantization * K.eval(inv_mask_bias)

                s = np.max(np.abs(set_a1_bias))
                if s > 0:
                    n1 = np.floor(np.log2(4 * s / 3))
                    n2 = n1 + 1 - np.power(2, (bits - 1)) / 2
                    p_set = [0]
                    for ii in range(int(n1 - n2) + 1):
                        exponent = n2 + ii
                        elem = np.power(2, exponent)
                        p_set.append(elem)
                    p_set.sort()

                    for elem in np.nditer(set_a1_bias, op_flags=['readwrite']):
                        if elem != 0:
                            temp = 0
                            for ii in range(np.size(p_set) - 1):
                                alpha = p_set[ii]
                                beta = p_set[ii + 1]
                                if np.less(np.abs(elem), 3 * beta / 2) and np.greater_equal(np.abs(elem), (alpha + beta) / 2):
                                    temp = beta * np.sign(elem)
                                    break

                            elem[...] = temp

                    K.set_value(self.bias_nontrainable, set_a1_bias)
                else:
                    print('There were zero elements to quantize. Does the model really have all-zero biases?')
            else:
                print(
                    'self.delta was zero. --> The masks were hence not changed and thus the kernel is wont be changed either.')
        else:
            print('Biases are disabled for this layer.')



    def set_inq_flag(self):
        K.set_value(self.is_inq_layer, 1)



    def save_initial_weights(self, weights):
        self.initial_weights = weights




    def build(self, input_shape):

        assert len(input_shape) >= 2
        input_dim = input_shape[-1]

        # Now the custom stuff
        ################################################################################################################
        print('mybuild: INQ_Dense')

        self.kernel_trainable = self.add_weight(shape=(input_dim, self.units),
                                                initializer='zeros',
                                                name='kernel_trainable',
                                                regularizer=self.kernel_regularizer,
                                                constraint=self.kernel_constraint,
                                                trainable=True)

        if self.use_bias:
            self.bias_trainable = self.add_weight(shape=(self.units,),
                                                  initializer='zeros',
                                                  name='bias_trainable',
                                                  regularizer=self.bias_regularizer,
                                                  constraint=self.bias_constraint,
                                                  trainable=True)
        else:
            self.bias = None


        # Kernel stuff
        ################################################################################################################
        if hasattr(self, 'initial_weights'):
            K.set_value(self.kernel_trainable,
                        self.initial_weights[0])

        self.kernel_nontrainable = self.add_weight(shape=(input_dim, self.units),
                                                   initializer='zeros',
                                                   name='kernel_nontrainable',
                                                   trainable=False)

        self.mask_np = self.add_weight(shape=(input_dim, self.units),
                                       initializer='ones',
                                       name='mask_np',
                                       trainable=False)

        inv_mask_np = -self.mask_np + 1
        self.kernel = self.kernel_trainable * self.mask_np + self.kernel_nontrainable * inv_mask_np


        # Bias stuff analog to kernel stuff from above
        ################################################################################################################
        if self.use_bias:
            if hasattr(self, 'initial_weights'):
                K.set_value(self.bias_trainable, self.initial_weights[1])

            self.bias_nontrainable = self.add_weight(shape=(self.units,),
                                                     initializer='zeros',
                                                     name='bias_nontrainable',
                                                     trainable=False)

            self.mask_bias = self.add_weight(shape=(self.units,),
                                             initializer='ones',
                                             name='mask_bias',
                                             trainable=False)

            inv_mask_bias = -self.mask_bias + 1
            self.bias = self.bias_trainable * self.mask_bias + self.bias_nontrainable * inv_mask_bias


        # General stuff
        ################################################################################################################
        self.is_inq_layer = self.add_weight(shape=(),
                                            initializer='zeros',
                                            name='is_inq', trainable=False)

        self.previous_step = self.add_weight(shape=(),
                                             initializer='zeros',
                                             name='previous_step', trainable=False)


        # Again stuff of the base class
        ################################################################################################################

        # Set input spec.
        self.input_spec = InputSpec(min_ndim=2, axes={-1: input_dim})
        self.built = True