|
| 1 | +# Copyright 2021 The TensorFlow Authors. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +# ============================================================================== |
| 15 | +"""Tests for a simple convnet with clusterable layer on the MNIST dataset. """ |
| 16 | + |
| 17 | +import tensorflow as tf |
| 18 | + |
| 19 | +from tensorflow_model_optimization.python.core.clustering.keras import cluster |
| 20 | +from tensorflow_model_optimization.python.core.clustering.keras import cluster_config |
| 21 | +from tensorflow_model_optimization.python.core.clustering.keras import clusterable_layer |
| 22 | +from tensorflow_model_optimization.python.core.clustering.keras import clustering_registry |
| 23 | + |
| 24 | +tf.random.set_seed(42) |
| 25 | + |
| 26 | +keras = tf.keras |
| 27 | + |
| 28 | +EPOCHS = 7 |
| 29 | +EPOCHS_FINE_TUNING = 4 |
| 30 | +NUMBER_OF_CLUSTERS = 8 |
| 31 | + |
| 32 | +def _build_model(): |
| 33 | + """ |
| 34 | + Builds simple CNN model. |
| 35 | + """ |
| 36 | + i = tf.keras.layers.Input(shape=(28, 28), name='input') |
| 37 | + x = tf.keras.layers.Reshape((28, 28, 1))(i) |
| 38 | + x = tf.keras.layers.Conv2D( |
| 39 | + filters=12, kernel_size=(3, 3), activation='relu', name='conv1')( |
| 40 | + x) |
| 41 | + x = tf.keras.layers.MaxPool2D(2, 2)(x) |
| 42 | + x = tf.keras.layers.Flatten()(x) |
| 43 | + output = tf.keras.layers.Dense(units=10)(x) |
| 44 | + |
| 45 | + model = tf.keras.Model(inputs=[i], outputs=[output]) |
| 46 | + return model |
| 47 | + |
| 48 | +def _get_dataset(): |
| 49 | + mnist = tf.keras.datasets.mnist |
| 50 | + (x_train, y_train), (x_test, y_test) = mnist.load_data() |
| 51 | + x_train, x_test = x_train / 255.0, x_test / 255.0 |
| 52 | + # Use subset of 60000 examples to keep unit test speed fast. |
| 53 | + x_train = x_train[0:1000] |
| 54 | + y_train = y_train[0:1000] |
| 55 | + return (x_train, y_train), (x_test, y_test) |
| 56 | + |
| 57 | + |
| 58 | +def _train_model(model): |
| 59 | + loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) |
| 60 | + |
| 61 | + model.compile(optimizer='adam', loss=loss_fn, metrics=['accuracy']) |
| 62 | + |
| 63 | + (x_train, y_train), _ = _get_dataset() |
| 64 | + |
| 65 | + model.fit(x_train, y_train, epochs=EPOCHS) |
| 66 | + |
| 67 | +def _cluster_model(model, number_of_clusters): |
| 68 | + |
| 69 | + (x_train, y_train), _ = _get_dataset() |
| 70 | + |
| 71 | + clustering_params = { |
| 72 | + 'number_of_clusters': NUMBER_OF_CLUSTERS, |
| 73 | + 'cluster_centroids_init': cluster_config.CentroidInitialization.KMEANS_PLUS_PLUS |
| 74 | + } |
| 75 | + |
| 76 | + # Cluster model |
| 77 | + clustered_model = cluster.cluster_weights(model, **clustering_params) |
| 78 | + |
| 79 | + # Use smaller learning rate for fine-tuning |
| 80 | + # clustered model |
| 81 | + opt = tf.keras.optimizers.Adam(learning_rate=1e-5) |
| 82 | + |
| 83 | + clustered_model.compile( |
| 84 | + loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), |
| 85 | + optimizer=opt, |
| 86 | + metrics=['accuracy']) |
| 87 | + |
| 88 | + # Fine-tune clustered model |
| 89 | + clustered_model.fit( |
| 90 | + x_train, |
| 91 | + y_train, |
| 92 | + epochs=EPOCHS_FINE_TUNING) |
| 93 | + |
| 94 | + stripped_model = cluster.strip_clustering(clustered_model) |
| 95 | + stripped_model.compile( |
| 96 | + loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), |
| 97 | + optimizer=opt, |
| 98 | + metrics=['accuracy']) |
| 99 | + |
| 100 | + return stripped_model |
| 101 | + |
| 102 | +def _get_number_of_unique_weights(stripped_model, layer_nr, weights_nr): |
| 103 | + weights_as_list = stripped_model.layers[layer_nr].get_weights()[weights_nr].reshape(-1,).tolist() |
| 104 | + nr_of_unique_weights = len(set(weights_as_list)) |
| 105 | + |
| 106 | + return nr_of_unique_weights |
| 107 | + |
| 108 | +class FunctionalTest(tf.test.TestCase): |
| 109 | + |
| 110 | + def testMnist(self): |
| 111 | + """ In this test we test that 'kernel' weights |
| 112 | + are clustered. |
| 113 | + """ |
| 114 | + model = _build_model() |
| 115 | + _train_model(model) |
| 116 | + |
| 117 | + # Checks that number of original weights('kernel') is greater than the number of clusters |
| 118 | + nr_of_unique_weights = _get_number_of_unique_weights(model, -1, 0) |
| 119 | + self.assertGreater(nr_of_unique_weights, NUMBER_OF_CLUSTERS) |
| 120 | + |
| 121 | + # Record the number of unique values of 'bias' |
| 122 | + nr_of_bias_weights = _get_number_of_unique_weights(model, -1, 1) |
| 123 | + |
| 124 | + _, (x_test, y_test) = _get_dataset() |
| 125 | + |
| 126 | + results_original = model.evaluate(x_test, y_test) |
| 127 | + self.assertGreater(results_original[1], 0.85) |
| 128 | + |
| 129 | + clustered_model = _cluster_model(model, NUMBER_OF_CLUSTERS) |
| 130 | + |
| 131 | + results = clustered_model.evaluate(x_test, y_test) |
| 132 | + |
| 133 | + self.assertGreater(results[1], 0.85) |
| 134 | + |
| 135 | + nr_of_unique_weights = _get_number_of_unique_weights(clustered_model, -1, 0) |
| 136 | + self.assertLessEqual(nr_of_unique_weights, NUMBER_OF_CLUSTERS) |
| 137 | + |
| 138 | + # checks that we don't cluster 'bias' weights |
| 139 | + clustered_nr_of_bias_weights = _get_number_of_unique_weights(clustered_model, -1, 1) |
| 140 | + self.assertEqual(nr_of_bias_weights, clustered_nr_of_bias_weights) |
| 141 | + |
| 142 | +if __name__ == '__main__': |
| 143 | + tf.test.main() |
0 commit comments