|
| 1 | +# Copyright 2020 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 weight clustering algorithm.""" |
| 16 | + |
| 17 | +import os |
| 18 | +import tempfile |
| 19 | + |
| 20 | +import tensorflow as tf |
| 21 | + |
| 22 | +from tensorflow_model_optimization.python.core.clustering.keras import cluster_config |
| 23 | +from tensorflow_model_optimization.python.core.common.keras.compression.algorithms import weight_clustering |
| 24 | + |
| 25 | + |
| 26 | +def _build_model(): |
| 27 | + i = tf.keras.layers.Input(shape=(28, 28), name='input') |
| 28 | + x = tf.keras.layers.Reshape((28, 28, 1))(i) |
| 29 | + x = tf.keras.layers.Conv2D( |
| 30 | + 20, 5, activation='relu', padding='valid', name='conv1')( |
| 31 | + x) |
| 32 | + x = tf.keras.layers.MaxPool2D(2, 2)(x) |
| 33 | + x = tf.keras.layers.Conv2D( |
| 34 | + 50, 5, activation='relu', padding='valid', name='conv2')( |
| 35 | + x) |
| 36 | + x = tf.keras.layers.MaxPool2D(2, 2)(x) |
| 37 | + x = tf.keras.layers.Flatten()(x) |
| 38 | + x = tf.keras.layers.Dense(500, activation='relu', name='fc1')(x) |
| 39 | + output = tf.keras.layers.Dense(10, name='fc2')(x) |
| 40 | + |
| 41 | + model = tf.keras.Model(inputs=[i], outputs=[output]) |
| 42 | + return model |
| 43 | + |
| 44 | + |
| 45 | +def _get_dataset(): |
| 46 | + mnist = tf.keras.datasets.mnist |
| 47 | + (x_train, y_train), (x_test, y_test) = mnist.load_data() |
| 48 | + x_train, x_test = x_train / 255.0, x_test / 255.0 |
| 49 | + # Use subset of 60000 examples to keep unit test speed fast. |
| 50 | + x_train = x_train[:1000] |
| 51 | + y_train = y_train[:1000] |
| 52 | + |
| 53 | + return (x_train, y_train), (x_test, y_test) |
| 54 | + |
| 55 | + |
| 56 | +def _train_model(model): |
| 57 | + loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) |
| 58 | + model.compile(optimizer='adam', loss=loss_fn, metrics=['accuracy']) |
| 59 | + (x_train, y_train), _ = _get_dataset() |
| 60 | + model.fit(x_train, y_train, epochs=1) |
| 61 | + |
| 62 | + |
| 63 | +def _save_as_saved_model(model): |
| 64 | + saved_model_dir = tempfile.mkdtemp() |
| 65 | + model.save(saved_model_dir) |
| 66 | + return saved_model_dir |
| 67 | + |
| 68 | + |
| 69 | +def _get_directory_size_in_bytes(directory): |
| 70 | + total = 0 |
| 71 | + try: |
| 72 | + for entry in os.scandir(directory): |
| 73 | + if entry.is_file(): |
| 74 | + # if it's a file, use stat() function |
| 75 | + total += entry.stat().st_size |
| 76 | + elif entry.is_dir(): |
| 77 | + # if it's a directory, recursively call this function |
| 78 | + total += _get_directory_size_in_bytes(entry.path) |
| 79 | + except NotADirectoryError: |
| 80 | + # if `directory` isn't a directory, get the file size then |
| 81 | + return os.path.getsize(directory) |
| 82 | + except PermissionError: |
| 83 | + # if for whatever reason we can't open the folder, return 0 |
| 84 | + return 0 |
| 85 | + return total |
| 86 | + |
| 87 | + |
| 88 | +class FunctionalTest(tf.test.TestCase): |
| 89 | + |
| 90 | + def testWeightClustering_TrainingE2E(self): |
| 91 | + number_of_clusters = 8 |
| 92 | + model = _build_model() |
| 93 | + _train_model(model) |
| 94 | + original_saved_model_dir = _save_as_saved_model(model) |
| 95 | + |
| 96 | + params = weight_clustering.WeightClusteringParams( |
| 97 | + number_of_clusters=number_of_clusters, |
| 98 | + cluster_centroids_init=\ |
| 99 | + cluster_config.CentroidInitialization.DENSITY_BASED) |
| 100 | + compressed_model = weight_clustering.optimize(model, params) |
| 101 | + |
| 102 | + _train_model(compressed_model) |
| 103 | + |
| 104 | + saved_model_dir = _save_as_saved_model(compressed_model) |
| 105 | + |
| 106 | + _, (x_test, y_test) = _get_dataset() |
| 107 | + |
| 108 | + loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) |
| 109 | + |
| 110 | + compressed_model.compile( |
| 111 | + optimizer='adam', loss=loss_fn, metrics=['accuracy']) |
| 112 | + |
| 113 | + results = compressed_model.evaluate(x_test, y_test) |
| 114 | + |
| 115 | + # Accuracy test. |
| 116 | + self.assertGreater(results[1], 0.85) # 0.8708 |
| 117 | + |
| 118 | + original_size = _get_directory_size_in_bytes(original_saved_model_dir) |
| 119 | + compressed_size = _get_directory_size_in_bytes(saved_model_dir) |
| 120 | + |
| 121 | + # Compressed model size test. |
| 122 | + # TODO(tfmot): gzip compression can reduce file size much better. |
| 123 | + self.assertLess(compressed_size, original_size / 1.3) |
| 124 | + |
| 125 | + def testWeightClustering_SingleLayer(self): |
| 126 | + number_of_clusters = 8 |
| 127 | + i = tf.keras.layers.Input(shape=(2), name='input') |
| 128 | + output = tf.keras.layers.Dense(3, name='fc1')(i) |
| 129 | + model = tf.keras.Model(inputs=[i], outputs=[output]) |
| 130 | + |
| 131 | + dense_layer_weights = model.layers[1].get_weights() |
| 132 | + |
| 133 | + params = weight_clustering.WeightClusteringParams( |
| 134 | + number_of_clusters=number_of_clusters, |
| 135 | + cluster_centroids_init=\ |
| 136 | + cluster_config.CentroidInitialization.DENSITY_BASED) |
| 137 | + compressed_model = weight_clustering.optimize(model, params) |
| 138 | + |
| 139 | + dense_layer_compressed_weights = compressed_model.layers[1].get_weights() |
| 140 | + |
| 141 | + # clustering_centroids. |
| 142 | + self.assertEqual( |
| 143 | + dense_layer_compressed_weights[0].shape, (number_of_clusters,)) |
| 144 | + |
| 145 | + # pulling_indices. |
| 146 | + self.assertEqual( |
| 147 | + dense_layer_compressed_weights[1].shape, |
| 148 | + dense_layer_weights[0].shape) |
| 149 | + self.assertEqual(str(dense_layer_compressed_weights[1].dtype), 'int64') |
| 150 | + self.assertAllInRange( |
| 151 | + dense_layer_compressed_weights[1], 0, number_of_clusters - 1) |
| 152 | + |
| 153 | + # bias |
| 154 | + assert (dense_layer_weights[1] == dense_layer_compressed_weights[2]).all() |
| 155 | + |
| 156 | + |
| 157 | +if __name__ == '__main__': |
| 158 | + tf.test.main() |
0 commit comments