|
| 1 | +# Copyright 2025 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 | +"""Test compression metadata detection when compression is disabled.""" |
| 16 | + |
| 17 | +import os |
| 18 | +import numpy as np |
| 19 | +import tensorflow as tf |
| 20 | +from tflite_micro.python.tflite_micro import runtime |
| 21 | +from tflite_micro.tensorflow.lite.micro import compression |
| 22 | + |
| 23 | + |
| 24 | +class CompressionDetectionTest(tf.test.TestCase): |
| 25 | + """Test compression metadata detection when compression is disabled.""" |
| 26 | + |
| 27 | + def _create_test_model(self): |
| 28 | + """Create a simple quantized model for testing.""" |
| 29 | + model = tf.keras.Sequential([ |
| 30 | + tf.keras.layers.Dense(10, input_shape=(5, ), activation='relu'), |
| 31 | + tf.keras.layers.Dense(5, activation='softmax') |
| 32 | + ]) |
| 33 | + model.compile(optimizer='adam', loss='sparse_categorical_crossentropy') |
| 34 | + |
| 35 | + # Convert to quantized TFLite |
| 36 | + converter = tf.lite.TFLiteConverter.from_keras_model(model) |
| 37 | + converter.optimizations = [tf.lite.Optimize.DEFAULT] |
| 38 | + |
| 39 | + def representative_dataset(): |
| 40 | + for _ in range(10): |
| 41 | + yield [np.random.randn(1, 5).astype(np.float32)] |
| 42 | + |
| 43 | + converter.representative_dataset = representative_dataset |
| 44 | + converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8] |
| 45 | + converter.inference_input_type = tf.uint8 |
| 46 | + converter.inference_output_type = tf.uint8 |
| 47 | + |
| 48 | + tflite_model = converter.convert() |
| 49 | + return bytes(tflite_model) if isinstance(tflite_model, |
| 50 | + bytearray) else tflite_model |
| 51 | + |
| 52 | + def test_regular_model_loads_successfully(self): |
| 53 | + """Non-compressed models should load without issues.""" |
| 54 | + model_data = self._create_test_model() |
| 55 | + interpreter = runtime.Interpreter.from_bytes(model_data) |
| 56 | + self.assertIsNotNone(interpreter) |
| 57 | + |
| 58 | + def test_compressed_model_raises_runtime_error(self): |
| 59 | + """Compressed models should raise RuntimeError when compression is disabled.""" |
| 60 | + # Create and compress a model |
| 61 | + model_data = self._create_test_model() |
| 62 | + |
| 63 | + spec = (compression.SpecBuilder().add_tensor( |
| 64 | + subgraph=0, tensor=1).with_lut(index_bitwidth=4).build()) |
| 65 | + |
| 66 | + compressed_model = compression.compress(model_data, spec) |
| 67 | + if isinstance(compressed_model, bytearray): |
| 68 | + compressed_model = bytes(compressed_model) |
| 69 | + |
| 70 | + # Should raise RuntimeError |
| 71 | + with self.assertRaises(RuntimeError): |
| 72 | + runtime.Interpreter.from_bytes(compressed_model) |
| 73 | + |
| 74 | + def test_can_load_regular_after_compressed_failure(self): |
| 75 | + """Verify we can still load regular models after compressed model fails.""" |
| 76 | + model_data = self._create_test_model() |
| 77 | + |
| 78 | + # First try compressed model (should fail) |
| 79 | + spec = (compression.SpecBuilder().add_tensor( |
| 80 | + subgraph=0, tensor=1).with_lut(index_bitwidth=4).build()) |
| 81 | + compressed_model = compression.compress(model_data, spec) |
| 82 | + |
| 83 | + with self.assertRaises(RuntimeError): |
| 84 | + runtime.Interpreter.from_bytes(bytes(compressed_model)) |
| 85 | + |
| 86 | + # Then load regular model (should succeed) |
| 87 | + interpreter = runtime.Interpreter.from_bytes(model_data) |
| 88 | + self.assertIsNotNone(interpreter) |
| 89 | + |
| 90 | + |
| 91 | +if __name__ == '__main__': |
| 92 | + # Set TF environment variables to suppress warnings |
| 93 | + os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' |
| 94 | + os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0' |
| 95 | + tf.test.main() |
0 commit comments