|
| 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 | +"""Base custom model that is already retained by data.""" |
| 15 | + |
| 16 | +from __future__ import absolute_import |
| 17 | +from __future__ import division |
| 18 | +from __future__ import print_function |
| 19 | + |
| 20 | +import abc |
| 21 | +import os |
| 22 | +import tempfile |
| 23 | + |
| 24 | +import tensorflow.compat.v2 as tf |
| 25 | +from tensorflow_examples.lite.model_maker.core import compat |
| 26 | +from tensorflow_examples.lite.model_maker.core import model_export_format as mef |
| 27 | + |
| 28 | +DEFAULT_QUANTIZATION_STEPS = 2000 |
| 29 | + |
| 30 | + |
| 31 | +def get_representative_dataset_gen(dataset, num_steps): |
| 32 | + |
| 33 | + def representative_dataset_gen(): |
| 34 | + """Generates representative dataset for quantized.""" |
| 35 | + for image, _ in dataset.take(num_steps): |
| 36 | + yield [image] |
| 37 | + |
| 38 | + return representative_dataset_gen |
| 39 | + |
| 40 | + |
| 41 | +class CustomModel(abc.ABC): |
| 42 | + """"The abstract base class that represents a Tensorflow classification model.""" |
| 43 | + |
| 44 | + def __init__(self, model_export_format, model_spec, shuffle): |
| 45 | + """Initialize a instance with data, deploy mode and other related parameters. |
| 46 | +
|
| 47 | + Args: |
| 48 | + model_export_format: Model export format such as saved_model / tflite. |
| 49 | + model_spec: Specification for the model. |
| 50 | + shuffle: Whether the data should be shuffled. |
| 51 | + """ |
| 52 | + if model_export_format != mef.ModelExportFormat.TFLITE: |
| 53 | + raise ValueError('Model export format %s is not supported currently.' % |
| 54 | + str(model_export_format)) |
| 55 | + |
| 56 | + self.model_export_format = model_export_format |
| 57 | + self.model_spec = model_spec |
| 58 | + self.shuffle = shuffle |
| 59 | + self.model = None |
| 60 | + |
| 61 | + def preprocess(self, sample_data, label): |
| 62 | + """Preprocess the data.""" |
| 63 | + # TODO(yuqili): remove this method once preprocess for image classifier is |
| 64 | + # also moved to DataLoader part. |
| 65 | + return sample_data, label |
| 66 | + |
| 67 | + @abc.abstractmethod |
| 68 | + def train(self, train_data, validation_data=None, **kwargs): |
| 69 | + return |
| 70 | + |
| 71 | + @abc.abstractmethod |
| 72 | + def export(self, **kwargs): |
| 73 | + return |
| 74 | + |
| 75 | + def summary(self): |
| 76 | + self.model.summary() |
| 77 | + |
| 78 | + @abc.abstractmethod |
| 79 | + def evaluate(self, data, **kwargs): |
| 80 | + return |
| 81 | + |
| 82 | + def _gen_dataset(self, |
| 83 | + data, |
| 84 | + batch_size=32, |
| 85 | + is_training=True, |
| 86 | + input_pipeline_context=None): |
| 87 | + """Generates training / validation dataset.""" |
| 88 | + # The dataset is always sharded by number of hosts. |
| 89 | + # num_input_pipelines is the number of hosts rather than number of cores. |
| 90 | + ds = data.dataset |
| 91 | + if input_pipeline_context and input_pipeline_context.num_input_pipelines > 1: |
| 92 | + ds = ds.shard(input_pipeline_context.num_input_pipelines, |
| 93 | + input_pipeline_context.input_pipeline_id) |
| 94 | + |
| 95 | + ds = ds.map( |
| 96 | + self.preprocess, num_parallel_calls=tf.data.experimental.AUTOTUNE) |
| 97 | + |
| 98 | + if is_training: |
| 99 | + if self.shuffle: |
| 100 | + ds = ds.shuffle(buffer_size=min(data.size, 100)) |
| 101 | + ds = ds.repeat() |
| 102 | + |
| 103 | + ds = ds.batch(batch_size) |
| 104 | + ds = ds.prefetch(tf.data.experimental.AUTOTUNE) |
| 105 | + return ds |
| 106 | + |
| 107 | + def _export_tflite(self, |
| 108 | + tflite_filename, |
| 109 | + quantized=False, |
| 110 | + quantization_steps=None, |
| 111 | + representative_data=None): |
| 112 | + """Converts the retrained model to tflite format and saves it. |
| 113 | +
|
| 114 | + Args: |
| 115 | + tflite_filename: File name to save tflite model. |
| 116 | + quantized: boolean, if True, save quantized model. |
| 117 | + quantization_steps: Number of post-training quantization calibration steps |
| 118 | + to run. Used only if `quantized` is True. |
| 119 | + representative_data: Representative data used for post-training |
| 120 | + quantization. Used only if `quantized` is True. |
| 121 | + """ |
| 122 | + temp_dir = None |
| 123 | + if compat.get_tf_behavior() == 1: |
| 124 | + temp_dir = tempfile.TemporaryDirectory() |
| 125 | + save_path = os.path.join(temp_dir.name, 'saved_model') |
| 126 | + self.model.save(save_path, include_optimizer=False, save_format='tf') |
| 127 | + converter = tf.compat.v1.lite.TFLiteConverter.from_saved_model(save_path) |
| 128 | + else: |
| 129 | + converter = tf.lite.TFLiteConverter.from_keras_model(self.model) |
| 130 | + |
| 131 | + if quantized: |
| 132 | + if quantization_steps is None: |
| 133 | + quantization_steps = DEFAULT_QUANTIZATION_STEPS |
| 134 | + if representative_data is None: |
| 135 | + raise ValueError( |
| 136 | + 'representative_data couldn\'t be None if model is quantized.') |
| 137 | + ds = self._gen_dataset( |
| 138 | + representative_data, batch_size=1, is_training=False) |
| 139 | + converter.representative_dataset = tf.lite.RepresentativeDataset( |
| 140 | + get_representative_dataset_gen(ds, quantization_steps)) |
| 141 | + |
| 142 | + converter.optimizations = [tf.lite.Optimize.DEFAULT] |
| 143 | + converter.inference_input_type = tf.uint8 |
| 144 | + converter.inference_output_type = tf.uint8 |
| 145 | + converter.target_spec.supported_ops = [ |
| 146 | + tf.lite.OpsSet.TFLITE_BUILTINS_INT8 |
| 147 | + ] |
| 148 | + tflite_model = converter.convert() |
| 149 | + if temp_dir: |
| 150 | + temp_dir.cleanup() |
| 151 | + |
| 152 | + with tf.io.gfile.GFile(tflite_filename, 'wb') as f: |
| 153 | + f.write(tflite_model) |
| 154 | + |
| 155 | + tf.compat.v1.logging.info('Export to tflite model in %s.', tflite_filename) |
0 commit comments