|
| 1 | +# Copyright 2019, 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 | +from __future__ import absolute_import |
| 16 | +from __future__ import division |
| 17 | +from __future__ import print_function |
| 18 | + |
| 19 | +import itertools |
| 20 | + |
| 21 | +from absl.testing import parameterized |
| 22 | +import numpy as np |
| 23 | +import tensorflow as tf |
| 24 | + |
| 25 | +from tensorflow_model_optimization.python.core.internal.tensor_encoding.stages.research import misc |
| 26 | +from tensorflow_model_optimization.python.core.internal.tensor_encoding.testing import test_utils |
| 27 | + |
| 28 | + |
| 29 | +class SplitBySmallValueEncodingStageTest(test_utils.BaseEncodingStageTest): |
| 30 | + |
| 31 | + def default_encoding_stage(self): |
| 32 | + """See base class.""" |
| 33 | + return misc.SplitBySmallValueEncodingStage() |
| 34 | + |
| 35 | + def default_input(self): |
| 36 | + """See base class.""" |
| 37 | + return tf.random.uniform([50], minval=-1.0, maxval=1.0) |
| 38 | + |
| 39 | + @property |
| 40 | + def is_lossless(self): |
| 41 | + """See base class.""" |
| 42 | + return False |
| 43 | + |
| 44 | + def common_asserts_for_test_data(self, data): |
| 45 | + """See base class.""" |
| 46 | + self._assert_is_integer( |
| 47 | + data.encoded_x[misc.SplitBySmallValueEncodingStage.ENCODED_INDICES_KEY]) |
| 48 | + |
| 49 | + def _assert_is_integer(self, indices): |
| 50 | + """Asserts that indices values are integers.""" |
| 51 | + assert indices.dtype == np.int32 |
| 52 | + |
| 53 | + @parameterized.parameters([tf.float32, tf.float64]) |
| 54 | + def test_input_types(self, x_dtype): |
| 55 | + # Tests different input dtypes. |
| 56 | + x = tf.constant([1.0, 0.1, 0.01, 0.001, 0.0001], dtype=x_dtype) |
| 57 | + threshold = 0.05 |
| 58 | + stage = misc.SplitBySmallValueEncodingStage(threshold=threshold) |
| 59 | + encode_params, decode_params = stage.get_params() |
| 60 | + encoded_x, decoded_x = self.encode_decode_x(stage, x, encode_params, |
| 61 | + decode_params) |
| 62 | + test_data = test_utils.TestData(x, encoded_x, decoded_x) |
| 63 | + test_data = self.evaluate_test_data(test_data) |
| 64 | + |
| 65 | + self._assert_is_integer(test_data.encoded_x[ |
| 66 | + misc.SplitBySmallValueEncodingStage.ENCODED_INDICES_KEY]) |
| 67 | + |
| 68 | + # The numpy arrays must have the same dtype as the arrays from test_data. |
| 69 | + expected_encoded_values = np.array([1.0, 0.1], dtype=x.dtype.as_numpy_dtype) |
| 70 | + expected_encoded_indices = np.array([[0], [1]], dtype=np.int32) |
| 71 | + expected_decoded_x = np.array([1.0, 0.1, 0., 0., 0.], |
| 72 | + dtype=x_dtype.as_numpy_dtype) |
| 73 | + self.assertAllEqual(test_data.encoded_x[stage.ENCODED_VALUES_KEY], |
| 74 | + expected_encoded_values) |
| 75 | + self.assertAllEqual(test_data.encoded_x[stage.ENCODED_INDICES_KEY], |
| 76 | + expected_encoded_indices) |
| 77 | + self.assertAllEqual(test_data.decoded_x, expected_decoded_x) |
| 78 | + |
| 79 | + def test_all_zero_input_works(self): |
| 80 | + # Tests that encoding does not blow up with all-zero input. With all-zero |
| 81 | + # input, both of the encoded values will be empty arrays. |
| 82 | + stage = misc.SplitBySmallValueEncodingStage() |
| 83 | + test_data = self.run_one_to_many_encode_decode(stage, |
| 84 | + lambda: tf.zeros([50])) |
| 85 | + |
| 86 | + self.assertAllEqual(np.zeros((50)).astype(np.float32), test_data.decoded_x) |
| 87 | + |
| 88 | + def test_all_below_threshold_works(self): |
| 89 | + # Tests that encoding does not blow up with all-below-threshold input. In |
| 90 | + # this case, both of the encoded values will be empty arrays. |
| 91 | + stage = misc.SplitBySmallValueEncodingStage(threshold=0.1) |
| 92 | + x = tf.random.uniform([50], minval=-0.01, maxval=0.01) |
| 93 | + encode_params, decode_params = stage.get_params() |
| 94 | + encoded_x, decoded_x = self.encode_decode_x(stage, x, encode_params, |
| 95 | + decode_params) |
| 96 | + test_data = test_utils.TestData(x, encoded_x, decoded_x) |
| 97 | + test_data = self.evaluate_test_data(test_data) |
| 98 | + |
| 99 | + expected_encoded_indices = np.array([], dtype=np.int32).reshape([0, 1]) |
| 100 | + self.assertAllEqual(test_data.encoded_x[stage.ENCODED_VALUES_KEY], []) |
| 101 | + self.assertAllEqual(test_data.encoded_x[stage.ENCODED_INDICES_KEY], |
| 102 | + expected_encoded_indices) |
| 103 | + self.assertAllEqual(test_data.decoded_x, |
| 104 | + np.zeros([50], dtype=x.dtype.as_numpy_dtype)) |
| 105 | + |
| 106 | + |
| 107 | +class DifferenceBetweenIntegersEncodingStageTest( |
| 108 | + test_utils.BaseEncodingStageTest): |
| 109 | + |
| 110 | + def default_encoding_stage(self): |
| 111 | + """See base class.""" |
| 112 | + return misc.DifferenceBetweenIntegersEncodingStage() |
| 113 | + |
| 114 | + def default_input(self): |
| 115 | + """See base class.""" |
| 116 | + return tf.random.uniform([10], minval=0, maxval=10, dtype=tf.int64) |
| 117 | + |
| 118 | + @property |
| 119 | + def is_lossless(self): |
| 120 | + """See base class.""" |
| 121 | + return True |
| 122 | + |
| 123 | + def common_asserts_for_test_data(self, data): |
| 124 | + """See base class.""" |
| 125 | + self.assertAllEqual(data.x, data.decoded_x) |
| 126 | + |
| 127 | + @parameterized.parameters( |
| 128 | + itertools.product([[1,], [2,], [10,]], [tf.int32, tf.int64])) |
| 129 | + def test_with_multiple_input_shapes(self, input_dims, dtype): |
| 130 | + |
| 131 | + def x_fn(): |
| 132 | + return tf.random.uniform(input_dims, minval=0, maxval=10, dtype=dtype) |
| 133 | + |
| 134 | + test_data = self.run_one_to_many_encode_decode( |
| 135 | + self.default_encoding_stage(), x_fn) |
| 136 | + self.common_asserts_for_test_data(test_data) |
| 137 | + |
| 138 | + def test_empty_input_static(self): |
| 139 | + # Tests that the encoding works when the input shape is [0]. |
| 140 | + x = [] |
| 141 | + x = tf.convert_to_tensor(x, dtype=tf.int32) |
| 142 | + assert x.shape.as_list() == [0] |
| 143 | + |
| 144 | + stage = self.default_encoding_stage() |
| 145 | + encode_params, decode_params = stage.get_params() |
| 146 | + encoded_x, decoded_x = self.encode_decode_x(stage, x, encode_params, |
| 147 | + decode_params) |
| 148 | + |
| 149 | + test_data = self.evaluate_test_data( |
| 150 | + test_utils.TestData(x, encoded_x, decoded_x)) |
| 151 | + self.common_asserts_for_test_data(test_data) |
| 152 | + |
| 153 | + def test_empty_input_dynamic(self): |
| 154 | + # Tests that the encoding works when the input shape is [0], but not |
| 155 | + # statically known. |
| 156 | + y = tf.zeros((10,)) |
| 157 | + indices = tf.where_v2(tf.abs(y) > 1e-8) |
| 158 | + x = tf.gather_nd(y, indices) |
| 159 | + x = tf.cast(x, tf.int32) # Empty tensor. |
| 160 | + assert x.shape.as_list() == [None] |
| 161 | + stage = self.default_encoding_stage() |
| 162 | + encode_params, decode_params = stage.get_params() |
| 163 | + encoded_x, decoded_x = self.encode_decode_x(stage, x, encode_params, |
| 164 | + decode_params) |
| 165 | + |
| 166 | + test_data = self.evaluate_test_data( |
| 167 | + test_utils.TestData(x, encoded_x, decoded_x)) |
| 168 | + assert test_data.x.shape == (0,) |
| 169 | + assert test_data.encoded_x[stage.ENCODED_VALUES_KEY].shape == (0,) |
| 170 | + assert test_data.decoded_x.shape == (0,) |
| 171 | + |
| 172 | + @parameterized.parameters([tf.bool, tf.float32]) |
| 173 | + def test_encode_unsupported_type_raises(self, dtype): |
| 174 | + stage = self.default_encoding_stage() |
| 175 | + with self.assertRaisesRegexp(TypeError, 'Unsupported input type'): |
| 176 | + self.run_one_to_many_encode_decode( |
| 177 | + stage, lambda: tf.cast(self.default_input(), dtype)) |
| 178 | + |
| 179 | + def test_encode_unsupported_input_shape_raises(self): |
| 180 | + x = tf.random.uniform((3, 4), maxval=10, dtype=tf.int32) |
| 181 | + stage = self.default_encoding_stage() |
| 182 | + params, _ = stage.get_params() |
| 183 | + with self.assertRaisesRegexp(ValueError, 'Number of dimensions must be 1'): |
| 184 | + stage.encode(x, params) |
| 185 | + |
| 186 | + |
| 187 | +if __name__ == '__main__': |
| 188 | + tf.test.main() |
0 commit comments