-
Notifications
You must be signed in to change notification settings - Fork 320
/
clustering_registry_test.py
521 lines (444 loc) · 18.5 KB
/
clustering_registry_test.py
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
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Tests for keras clustering registry API."""
import numpy as np
import tensorflow as tf
from absl.testing import parameterized
from tensorflow_model_optimization.python.core.clustering.keras import clusterable_layer
from tensorflow_model_optimization.python.core.clustering.keras import clustering_registry
keras = tf.keras
k = keras.backend
layers = keras.layers
errors_impl = tf.errors
test = tf.test
ClusterRegistry = clustering_registry.ClusteringRegistry
ClusteringLookupRegistry = clustering_registry.ClusteringLookupRegistry
class ClusteringAlgorithmTest(parameterized.TestCase):
"""Unit tests for clustering lookup algorithms"""
def _pull_values(self, ca, pulling_indices, expected_output):
pulling_indices_np = np.array(pulling_indices)
res_tf = ca.get_clustered_weight(pulling_indices_np)
res_np = k.batch_get_value([res_tf])[0]
res_np_list = res_np.tolist()
self.assertSequenceEqual(res_np_list, expected_output)
def _check_gradients(self, ca, weight, pulling_indices, expected_output):
pulling_indices_tf = tf.convert_to_tensor(pulling_indices)
weight_tf = tf.convert_to_tensor(weight)
with tf.GradientTape(persistent=True) as t:
t.watch(pulling_indices_tf)
t.watch(weight_tf)
cls_weights_tf = tf.reshape(
ca.get_clustered_weight(pulling_indices_tf), shape=(-1,))
t.watch(cls_weights_tf)
out_forward = ca.add_custom_gradients(cls_weights_tf, weight_tf)
grad_cls_weight = t.gradient(out_forward, cls_weights_tf)
grad_weight = t.gradient(out_forward, weight_tf)
chk_output = tf.math.equal(grad_cls_weight, grad_weight)
chk_output_np = k.batch_get_value(chk_output)
self.assertSequenceEqual(chk_output_np, expected_output)
@parameterized.parameters(
([-0.800450444, 0.864694357],
[[0.220442653, 0.854694366, 0.0328432359, 0.506857157],
[0.0527950861, -0.659555554, -0.849919915, -0.54047],
[-0.305815876, 0.0865516588, 0.659202456, -0.355699599],
[-0.348868281, -0.662001, 0.6171574, -0.296582848]],
[[1, 1, 1, 1],
[1, 0, 0, 0],
[0, 1, 1, 0],
[0, 0, 1, 0]],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
)
)
def testDenseWeightsCAGrad(self,
clustering_centroids,
weight,
pulling_indices,
expected_output):
"""
Verifies that the gradients of DenseWeightsCA work as expected.
"""
ca = clustering_registry.DenseWeightsCA(clustering_centroids)
self._check_gradients(ca, weight, pulling_indices, expected_output)
@parameterized.parameters(
([-1, 1], [[0, 0, 1], [1, 1, 1]], [[-1, -1, 1], [1, 1, 1]]),
([-1, 0, 1], [[1, 1, 1], [1, 1, 1]], [[0, 0, 0], [0, 0, 0]]),
)
def testDenseWeightsCA(self,
clustering_centroids,
pulling_indices,
expected_output):
"""
Verifies that DenseWeightsCA works as expected.
"""
ca = clustering_registry.DenseWeightsCA(clustering_centroids)
self._pull_values(ca, pulling_indices, expected_output)
@parameterized.parameters(
([-1, 1], [0, 0, 0, 0, 1], [-1, -1, -1, -1, 1]),
([0, 1, 2, 3], [0, 1, 2, 3, 0, 1, 2, 3], [0, 1, 2, 3, 0, 1, 2, 3]),
)
def testBiasWeightsCA(self,
clustering_centroids,
pulling_indices,
expected_output):
"""
Verifies that BiasWeightsCA works as expected.
"""
ca = clustering_registry.BiasWeightsCA(clustering_centroids)
self._pull_values(ca, pulling_indices, expected_output)
@parameterized.parameters(
([0.0, 3.0],
[[0.1, 0.1, 0.1],
[3.0, 3.0, 3.0],
[0.2, 0.2, 0.2]],
[[0, 0, 0],
[1, 1, 1],
[0, 0, 0]],
[1, 1, 1, 1, 1, 1, 1, 1, 1]
)
)
def testConvolutionalWeightsCAGrad(self,
clustering_centroids,
weight,
pulling_indices,
expected_output):
"""
Verifies that the gradients of ConvolutionalWeightsCA work as expected.
"""
ca = clustering_registry.DenseWeightsCA(clustering_centroids)
self._check_gradients(ca, weight, pulling_indices, expected_output)
@parameterized.parameters(
([0, 3], [[[[0, 0, 0], [1, 1, 1], [0, 0, 0]]]],
[[[[0, 0, 0], [3, 3, 3], [0, 0, 0]]]]),
([0, 3, 5], [[[[0, 1, 2], [1, 1, 1], [2, 1, 0]]]],
[[[[0, 3, 5], [3, 3, 3], [5, 3, 0]]]]),
)
def testConvolutionalWeightsCA(self,
clustering_centroids,
pulling_indices,
expected_output):
"""
Verifies that ConvolutionalWeightsCA works as expected.
"""
ca = clustering_registry.ConvolutionalWeightsCA(clustering_centroids)
self._pull_values(ca, pulling_indices, expected_output)
class CustomLayer(layers.Layer):
"""A custom non-clusterable layer class."""
def __init__(self, units=10):
super(CustomLayer, self).__init__()
self.add_weight(shape=(1, units),
initializer='uniform',
name='kernel')
def call(self, inputs):
return tf.matmul(inputs, self.weights)
class ClusteringLookupRegistryTest(test.TestCase, parameterized.TestCase):
"""Unit tests for the ClusteringLookupRegistry class."""
def testLookupHasEverythingFromRegistry(self):
"""
Verifies that every layer that has non-empty ClusteringRegistry records is
also presented in the ClusteringLookup.
"""
for layer, clustering_record in ClusterRegistry._LAYERS_WEIGHTS_MAP.items():
if clustering_record == []:
continue
self.assertIn(layer, ClusteringLookupRegistry._LAYERS_RESHAPE_MAP)
for cr in clustering_record:
self.assertIn(cr, ClusteringLookupRegistry._LAYERS_RESHAPE_MAP[layer])
def testGetClusteringImplFailsWithUnknonwClassUnknownWeight(self):
"""
Verifies that get_clustering_impl() raises an error when invoked with an
unsupported layer class and an unsupported weight name.
"""
with self.assertRaises(ValueError):
ClusteringLookupRegistry.get_clustering_impl(CustomLayer(),
'no_such_weight')
def testGetClusteringImplFailsWithKnonwClassUnknownWeight(self):
"""
Verifies that get_clustering_impl() raises an error when invoked with a
supported layer class and an unsupported weight name.
"""
with self.assertRaises(ValueError):
ClusteringLookupRegistry.get_clustering_impl(layers.Dense(10),
'no_such_weight')
@parameterized.parameters(
(layers.Conv2D, 'kernel', clustering_registry.ConvolutionalWeightsCA),
(layers.Conv1D, 'kernel', clustering_registry.ConvolutionalWeightsCA),
(layers.Conv3D, 'kernel', clustering_registry.ConvolutionalWeights3DCA),
)
def testReturnsResultsForKnownTypeKnownWeights(self,
layer_type,
weight,
expected):
"""
Verifies that get_clustering_impl() returns the expected clustering lookup
algorithm for the inputs provided.
"""
# layer_type is a class, thus constructing an object here
self.assertTrue(ClusteringLookupRegistry.get_clustering_impl(
layer_type(32, 3), weight) is expected)
def testRegisterNewImplWorks(self):
"""
Verifies that registering a custom clustering lookup algorithm works as
expected.
"""
class NewKernelCA(clustering_registry.AbstractClusteringAlgorithm):
def get_pulling_indices(self, weight):
return 1, 2, 3
new_impl = {
CustomLayer: {
'new_kernel': NewKernelCA
}
}
ClusteringLookupRegistry.register_new_implementation(new_impl)
self.assertTrue(ClusteringLookupRegistry.get_clustering_impl(
CustomLayer(), 'new_kernel') is NewKernelCA)
def testFailsIfNotADictIsGivenAsInput(self):
"""
Verifies that registering a custom clustering lookup algorithm fails if the
input provided is not a dict.
"""
with self.assertRaises(TypeError):
ClusteringLookupRegistry.register_new_implementation([1, 2, 3, 4])
def testFailsIfNotADictIsGivenAsConcreteImplementation(self):
"""
Verifies that registering a custom clustering lookup algorithm fails if the
input provided for the concrete implementation is not a dict.
"""
with self.assertRaises(TypeError):
ClusteringLookupRegistry.register_new_implementation({
ClusteringLookupRegistry: [('new_kernel', lambda x: x)]
})
class ClusterRegistryTest(test.TestCase):
"""Unit tests for the ClusteringRegistry class."""
class CustomLayerFromClusterableLayer(layers.Dense):
"""A custom layer class derived from a built-in clusterable layer."""
pass
class CustomLayerFromClusterableLayerNoWeights(layers.Reshape):
"""A custom layer class derived from a built-in clusterable layer,
that does not have any weights."""
pass
class MinimalRNNCell(keras.layers.Layer):
"""A minimal RNN cell implementation."""
def __init__(self, units, **kwargs):
self.units = units
self.state_size = units
super(ClusterRegistryTest.MinimalRNNCell, self).__init__(**kwargs)
def build(self, input_shape):
self.kernel = self.add_weight(shape=(input_shape[-1], self.units),
initializer='uniform',
name='kernel')
self.recurrent_kernel = self.add_weight(
shape=(self.units, self.units),
initializer='uniform',
name='recurrent_kernel')
self.built = True
def call(self, inputs, states):
prev_output = states[0]
h = k.dot(inputs, self.kernel)
output = h + k.dot(prev_output, self.recurrent_kernel)
return output, [output]
class MinimalRNNCellClusterable(MinimalRNNCell,
clusterable_layer.ClusterableLayer):
"""A clusterable minimal RNN cell implementation."""
def get_clusterable_weights(self):
return [
('kernel', self.kernel),
('recurrent_kernel', self.recurrent_kernel)
]
def testSupportsKerasClusterableLayer(self):
"""
Verifies that ClusterRegistry supports a built-in clusterable layer.
"""
self.assertTrue(ClusterRegistry.supports(layers.Dense(10)))
def testSupportsKerasClusterableLayerAlias(self):
"""
Verifies that ClusterRegistry supports a built-in clusterable layer alias.
"""
# layers.Conv2D maps to layers.convolutional.Conv2D
self.assertTrue(ClusterRegistry.supports(layers.Conv2D(10, 5)))
def testSupportsKerasNonClusterableLayer(self):
"""
Verifies that ClusterRegistry supports a built-in non-clusterable layer.
"""
# Dropout is a layer known to not be clusterable.
self.assertTrue(ClusterRegistry.supports(layers.Dropout(0.5)))
def testDoesNotSupportKerasUnsupportedLayer(self):
"""
Verifies that ClusterRegistry does not support an unknown built-in layer.
"""
# ConvLSTM2D is a built-in keras layer but not supported.
l = layers.ConvLSTM2D(2, (5, 5))
# We need to build weights
l.build(input_shape = (10, 10))
self.assertFalse(ClusterRegistry.supports(l))
def testSupportsKerasRNNLayers(self):
"""
Verifies that ClusterRegistry supports the expected built-in RNN layers.
"""
self.assertTrue(ClusterRegistry.supports(layers.LSTM(10)))
self.assertTrue(ClusterRegistry.supports(layers.GRU(10)))
self.assertTrue(ClusterRegistry.supports(layers.SimpleRNN(10)))
def testDoesNotSupportKerasRNNLayerUnknownCell(self):
"""
Verifies that ClusterRegistry does not support a custom non-clusterable RNN
cell.
"""
l = keras.layers.RNN(ClusterRegistryTest.MinimalRNNCell(32))
# We need to build it to have weights
l.build((10,1))
self.assertFalse(ClusterRegistry.supports(l))
def testSupportsKerasRNNLayerClusterableCell(self):
"""
Verifies that ClusterRegistry supports a custom clusterable RNN cell.
"""
self.assertTrue(ClusterRegistry.supports(
keras.layers.RNN(ClusterRegistryTest.MinimalRNNCellClusterable(32))))
def testDoesNotSupportCustomLayer(self):
"""
Verifies that ClusterRegistry does not support a custom non-clusterable
layer.
"""
self.assertFalse(ClusterRegistry.supports(CustomLayer(10)))
def testDoesNotSupportCustomLayerInheritedFromClusterableLayer(self):
"""
Verifies that ClusterRegistry does not support a custom layer derived from
a clusterable layer if there are trainable weights.
"""
custom_layer = ClusterRegistryTest.CustomLayerFromClusterableLayer(10)
custom_layer.build(input_shape=(10, 10))
self.assertFalse(ClusterRegistry.supports(custom_layer))
def testSupportsCustomLayerInheritedFromClusterableLayerNoWeights(self):
"""
Verifies that ClusterRegistry supports a custom layer derived from
a clusterable layer that does not have trainable weights.
"""
custom_layer = ClusterRegistryTest.\
CustomLayerFromClusterableLayerNoWeights((7, 1))
custom_layer.build(input_shape=(3, 4))
self.assertTrue(ClusterRegistry.supports(custom_layer))
def testMakeClusterableRaisesErrorForKerasUnsupportedLayer(self):
"""
Verifies that an unsupported built-in layer cannot be made clusterable by
calling make_clusterable().
"""
l = layers.ConvLSTM2D(2, (5, 5))
l.build(input_shape = (10, 10))
with self.assertRaises(ValueError):
ClusterRegistry.make_clusterable(l)
def testMakeClusterableRaisesErrorForCustomLayer(self):
"""
Verifies that a custom non-clusterable layer cannot be made clusterable by
calling make_clusterable().
"""
with self.assertRaises(ValueError):
ClusterRegistry.make_clusterable(CustomLayer(10))
def testMakeClusterableRaisesErrorForCustomLayerInheritedFromClusterableLayer(
self):
"""
Verifies that a non-clusterable layer derived from a clusterable layer
cannot be made clusterable by calling make_clusterable().
"""
l = ClusterRegistryTest.CustomLayerFromClusterableLayer(10)
l.build(input_shape = (10, 10))
with self.assertRaises(ValueError):
ClusterRegistry.make_clusterable(l)
def testMakeClusterableWorksOnKerasClusterableLayer(self):
"""
Verifies that make_clusterable() works as expected on a built-in
clusterable layer.
"""
layer = layers.Dense(10)
with self.assertRaises(AttributeError):
layer.get_clusterable_weights()
ClusterRegistry.make_clusterable(layer)
# Required since build method sets up the layer weights.
keras.Sequential([layer]).build(input_shape=(10, 1))
self.assertEqual([('kernel', layer.kernel)],
layer.get_clusterable_weights())
def testMakeClusterableWorksOnKerasNonClusterableLayer(self):
"""
Verifies that make_clusterable() works as expected on a built-in
non-clusterable layer.
"""
layer = layers.Dropout(0.5)
with self.assertRaises(AttributeError):
layer.get_clusterable_weights()
ClusterRegistry.make_clusterable(layer)
self.assertEqual([], layer.get_clusterable_weights())
def testMakeClusterableWorksOnKerasRNNLayer(self):
"""
Verifies that make_clusterable() works as expected on a built-in
RNN layer.
"""
layer = layers.LSTM(10)
with self.assertRaises(AttributeError):
layer.get_clusterable_weights()
ClusterRegistry.make_clusterable(layer)
keras.Sequential([layer]).build(input_shape=(2, 3, 4))
expected_weights = [
('kernel', layer.cell.kernel),
('recurrent_kernel', layer.cell.recurrent_kernel)
]
self.assertEqual(expected_weights, layer.get_clusterable_weights())
def testMakeClusterableWorksOnKerasRNNLayerWithRNNCellsParams(self):
"""
Verifies that make_clusterable() works as expected on a built-in
RNN layer with built-in RNN cells.
"""
cell1 = layers.LSTMCell(10)
cell2 = layers.GRUCell(5)
layer = layers.RNN([cell1, cell2])
with self.assertRaises(AttributeError):
layer.get_clusterable_weights()
ClusterRegistry.make_clusterable(layer)
keras.Sequential([layer]).build(input_shape=(2, 3, 4))
expected_weights = [
('kernel', cell1.kernel),
('recurrent_kernel', cell1.recurrent_kernel),
('kernel', cell2.kernel),
('recurrent_kernel', cell2.recurrent_kernel)
]
self.assertEqual(expected_weights, layer.get_clusterable_weights())
def testMakeClusterableWorksOnKerasRNNLayerWithClusterableCell(self):
"""
Verifies that make_clusterable() works as expected on a built-in
RNN layer with a custom clusterable RNN cell.
"""
cell1 = layers.LSTMCell(10)
cell2 = ClusterRegistryTest.MinimalRNNCellClusterable(5)
layer = layers.RNN([cell1, cell2])
with self.assertRaises(AttributeError):
layer.get_clusterable_weights()
ClusterRegistry.make_clusterable(layer)
keras.Sequential([layer]).build(input_shape=(2, 3, 4))
expected_weights = [
('kernel', cell1.kernel),
('recurrent_kernel', cell1.recurrent_kernel),
('kernel', cell2.kernel),
('recurrent_kernel', cell2.recurrent_kernel)
]
self.assertEqual(expected_weights, layer.get_clusterable_weights())
def testMakeClusterableRaisesErrorOnRNNLayersUnsupportedCell(self):
"""
Verifies that make_clusterable() raises an exception when invoked with a
built-in RNN layer that contains a non-clusterable custom RNN cell.
"""
l = ClusterRegistryTest.MinimalRNNCell(5)
# we need to build weights
l.build(input_shape = (10, 1))
with self.assertRaises(ValueError):
ClusterRegistry.make_clusterable(layers.RNN(
[layers.LSTMCell(10), l]))
if __name__ == '__main__':
test.main()