Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/microfrontend/ops/__init__.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/microfrontend/ops/gen_audio_microfrontend_op.py +423 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/microfrontend/python/__init__.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/microfrontend/python/ops/__init__.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/microfrontend/python/ops/audio_microfrontend_op.py +110 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/__init__.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/analyzer.py +105 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/analyzer_wrapper/__init__.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/analyzer_wrapper/_pywrap_analyzer_wrapper.pyi +16 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/authoring/__init__.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/authoring/authoring.py +303 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/conversion_metadata_schema_py_generated.py +554 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/convert.py +1206 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/convert_phase.py +219 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/convert_saved_model.py +186 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/interpreter.py +994 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/interpreter_wrapper/__init__.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/interpreter_wrapper/_pywrap_tensorflow_interpreter_wrapper.pyi +48 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/lite.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/lite_constants.py +70 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/__init__.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/_pywrap_tensorflow_lite_metrics_wrapper.pyi +18 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/converter_error_data_pb2.py +37 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/metrics.py +70 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/metrics_interface.py +48 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/wrapper/__init__.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/wrapper/metrics_wrapper.py +34 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/op_hint.py +1338 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/optimize/__init__.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/optimize/_pywrap_tensorflow_lite_calibration_wrapper.pyi +40 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/optimize/calibrator.py +255 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/schema_py_generated.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/schema_util.py +45 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/tflite_convert.py +694 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/tflite_keras_util.py +194 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/util.py +1070 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/wrap_toco.py +66 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/__init__.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/logging/__init__.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/logging/gen_html.py +265 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/logging/toco_conversion_log_pb2.py +37 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/model_flags_pb2.py +40 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/python/__init__.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/python/toco_from_protos.py +93 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/toco_flags_pb2.py +34 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/types_pb2.py +25 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/__init__.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/flatbuffer_utils.py +432 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/optimize/__init__.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/optimize/debugging/__init__.py +0 -0
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/microfrontend/ops/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensor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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Python wrappers around TensorFlow ops.
|
| 2 |
+
|
| 3 |
+
This file is MACHINE GENERATED! Do not edit.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import collections
|
| 7 |
+
|
| 8 |
+
from tensorflow.python import pywrap_tfe as pywrap_tfe
|
| 9 |
+
from tensorflow.python.eager import context as _context
|
| 10 |
+
from tensorflow.python.eager import core as _core
|
| 11 |
+
from tensorflow.python.eager import execute as _execute
|
| 12 |
+
from tensorflow.python.framework import dtypes as _dtypes
|
| 13 |
+
from tensorflow.security.fuzzing.py import annotation_types as _atypes
|
| 14 |
+
|
| 15 |
+
from tensorflow.python.framework import op_def_registry as _op_def_registry
|
| 16 |
+
from tensorflow.python.framework import ops as _ops
|
| 17 |
+
from tensorflow.python.framework import op_def_library as _op_def_library
|
| 18 |
+
from tensorflow.python.util.deprecation import deprecated_endpoints
|
| 19 |
+
from tensorflow.python.util import dispatch as _dispatch
|
| 20 |
+
from tensorflow.python.util.tf_export import tf_export
|
| 21 |
+
|
| 22 |
+
from typing import TypeVar, List, Any
|
| 23 |
+
from typing_extensions import Annotated
|
| 24 |
+
|
| 25 |
+
TV_AudioMicrofrontend_out_type = TypeVar("TV_AudioMicrofrontend_out_type", _atypes.Float32, _atypes.UInt16)
|
| 26 |
+
|
| 27 |
+
@_dispatch.add_fallback_dispatch_list
|
| 28 |
+
@_dispatch.add_type_based_api_dispatcher
|
| 29 |
+
@tf_export('audio_microfrontend')
|
| 30 |
+
def audio_microfrontend(audio: Annotated[Any, _atypes.Int16], sample_rate:int=16000, window_size:int=25, window_step:int=10, num_channels:int=32, upper_band_limit:float=7500, lower_band_limit:float=125, smoothing_bits:int=10, even_smoothing:float=0.025, odd_smoothing:float=0.06, min_signal_remaining:float=0.05, enable_pcan:bool=False, pcan_strength:float=0.95, pcan_offset:float=80, gain_bits:int=21, enable_log:bool=True, scale_shift:int=6, left_context:int=0, right_context:int=0, frame_stride:int=1, zero_padding:bool=False, out_scale:int=1, out_type:TV_AudioMicrofrontend_out_type=_dtypes.uint16, name=None) -> Annotated[Any, TV_AudioMicrofrontend_out_type]:
|
| 31 |
+
r"""Audio Microfrontend Op.
|
| 32 |
+
|
| 33 |
+
This Op converts a sequence of audio data into one or more
|
| 34 |
+
feature vectors containing filterbanks of the input. The
|
| 35 |
+
conversion process uses a lightweight library to perform:
|
| 36 |
+
|
| 37 |
+
1. A slicing window function
|
| 38 |
+
2. Short-time FFTs
|
| 39 |
+
3. Filterbank calculations
|
| 40 |
+
4. Noise reduction
|
| 41 |
+
5. PCAN Auto Gain Control
|
| 42 |
+
6. Logarithmic scaling
|
| 43 |
+
|
| 44 |
+
Arguments
|
| 45 |
+
audio: 1D Tensor, int16 audio data in temporal ordering.
|
| 46 |
+
sample_rate: Integer, the sample rate of the audio in Hz.
|
| 47 |
+
window_size: Integer, length of desired time frames in ms.
|
| 48 |
+
window_step: Integer, length of step size for the next frame in ms.
|
| 49 |
+
num_channels: Integer, the number of filterbank channels to use.
|
| 50 |
+
upper_band_limit: Float, the highest frequency included in the filterbanks.
|
| 51 |
+
lower_band_limit: Float, the lowest frequency included in the filterbanks.
|
| 52 |
+
smoothing_bits: Int, scale up signal by 2^(smoothing_bits) before reduction.
|
| 53 |
+
even_smoothing: Float, smoothing coefficient for even-numbered channels.
|
| 54 |
+
odd_smoothing: Float, smoothing coefficient for odd-numbered channels.
|
| 55 |
+
min_signal_remaining: Float, fraction of signal to preserve in smoothing.
|
| 56 |
+
enable_pcan: Bool, enable PCAN auto gain control.
|
| 57 |
+
pcan_strength: Float, gain normalization exponent.
|
| 58 |
+
pcan_offset: Float, positive value added in the normalization denominator.
|
| 59 |
+
gain_bits: Int, number of fractional bits in the gain.
|
| 60 |
+
enable_log: Bool, enable logarithmic scaling of filterbanks.
|
| 61 |
+
scale_shift: Integer, scale filterbanks by 2^(scale_shift).
|
| 62 |
+
left_context: Integer, number of preceding frames to attach to each frame.
|
| 63 |
+
right_context: Integer, number of preceding frames to attach to each frame.
|
| 64 |
+
frame_stride: Integer, M frames to skip over, where output[n] = frame[n*M].
|
| 65 |
+
zero_padding: Bool, if left/right context is out-of-bounds, attach frame of
|
| 66 |
+
zeroes. Otherwise, frame[0] or frame[size-1] will be copied.
|
| 67 |
+
out_scale: Integer, divide all filterbanks by this number.
|
| 68 |
+
out_type: DType, type of the output Tensor, defaults to UINT16.
|
| 69 |
+
|
| 70 |
+
Returns
|
| 71 |
+
filterbanks: 2D Tensor, each row is a time frame, each column is a channel.
|
| 72 |
+
|
| 73 |
+
Args:
|
| 74 |
+
audio: A `Tensor` of type `int16`.
|
| 75 |
+
sample_rate: An optional `int`. Defaults to `16000`.
|
| 76 |
+
window_size: An optional `int`. Defaults to `25`.
|
| 77 |
+
window_step: An optional `int`. Defaults to `10`.
|
| 78 |
+
num_channels: An optional `int`. Defaults to `32`.
|
| 79 |
+
upper_band_limit: An optional `float`. Defaults to `7500`.
|
| 80 |
+
lower_band_limit: An optional `float`. Defaults to `125`.
|
| 81 |
+
smoothing_bits: An optional `int`. Defaults to `10`.
|
| 82 |
+
even_smoothing: An optional `float`. Defaults to `0.025`.
|
| 83 |
+
odd_smoothing: An optional `float`. Defaults to `0.06`.
|
| 84 |
+
min_signal_remaining: An optional `float`. Defaults to `0.05`.
|
| 85 |
+
enable_pcan: An optional `bool`. Defaults to `False`.
|
| 86 |
+
pcan_strength: An optional `float`. Defaults to `0.95`.
|
| 87 |
+
pcan_offset: An optional `float`. Defaults to `80`.
|
| 88 |
+
gain_bits: An optional `int`. Defaults to `21`.
|
| 89 |
+
enable_log: An optional `bool`. Defaults to `True`.
|
| 90 |
+
scale_shift: An optional `int`. Defaults to `6`.
|
| 91 |
+
left_context: An optional `int`. Defaults to `0`.
|
| 92 |
+
right_context: An optional `int`. Defaults to `0`.
|
| 93 |
+
frame_stride: An optional `int`. Defaults to `1`.
|
| 94 |
+
zero_padding: An optional `bool`. Defaults to `False`.
|
| 95 |
+
out_scale: An optional `int`. Defaults to `1`.
|
| 96 |
+
out_type: An optional `tf.DType` from: `tf.uint16, tf.float32`. Defaults to `tf.uint16`.
|
| 97 |
+
name: A name for the operation (optional).
|
| 98 |
+
|
| 99 |
+
Returns:
|
| 100 |
+
A `Tensor` of type `out_type`.
|
| 101 |
+
"""
|
| 102 |
+
_ctx = _context._context or _context.context()
|
| 103 |
+
tld = _ctx._thread_local_data
|
| 104 |
+
if tld.is_eager:
|
| 105 |
+
try:
|
| 106 |
+
_result = pywrap_tfe.TFE_Py_FastPathExecute(
|
| 107 |
+
_ctx, "AudioMicrofrontend", name, audio, "sample_rate", sample_rate,
|
| 108 |
+
"window_size", window_size, "window_step", window_step,
|
| 109 |
+
"num_channels", num_channels, "upper_band_limit", upper_band_limit,
|
| 110 |
+
"lower_band_limit", lower_band_limit, "smoothing_bits",
|
| 111 |
+
smoothing_bits, "even_smoothing", even_smoothing, "odd_smoothing",
|
| 112 |
+
odd_smoothing, "min_signal_remaining", min_signal_remaining,
|
| 113 |
+
"enable_pcan", enable_pcan, "pcan_strength", pcan_strength,
|
| 114 |
+
"pcan_offset", pcan_offset, "gain_bits", gain_bits, "enable_log",
|
| 115 |
+
enable_log, "scale_shift", scale_shift, "left_context", left_context,
|
| 116 |
+
"right_context", right_context, "frame_stride", frame_stride,
|
| 117 |
+
"zero_padding", zero_padding, "out_scale", out_scale, "out_type",
|
| 118 |
+
out_type)
|
| 119 |
+
return _result
|
| 120 |
+
except _core._NotOkStatusException as e:
|
| 121 |
+
_ops.raise_from_not_ok_status(e, name)
|
| 122 |
+
except _core._FallbackException:
|
| 123 |
+
pass
|
| 124 |
+
try:
|
| 125 |
+
_result = _dispatcher_for_audio_microfrontend(
|
| 126 |
+
(audio, sample_rate, window_size, window_step, num_channels,
|
| 127 |
+
upper_band_limit, lower_band_limit, smoothing_bits, even_smoothing,
|
| 128 |
+
odd_smoothing, min_signal_remaining, enable_pcan, pcan_strength,
|
| 129 |
+
pcan_offset, gain_bits, enable_log, scale_shift, left_context,
|
| 130 |
+
right_context, frame_stride, zero_padding, out_scale, out_type,
|
| 131 |
+
name,), None)
|
| 132 |
+
if _result is not NotImplemented:
|
| 133 |
+
return _result
|
| 134 |
+
return audio_microfrontend_eager_fallback(
|
| 135 |
+
audio, sample_rate=sample_rate, window_size=window_size,
|
| 136 |
+
window_step=window_step, num_channels=num_channels,
|
| 137 |
+
upper_band_limit=upper_band_limit,
|
| 138 |
+
lower_band_limit=lower_band_limit, smoothing_bits=smoothing_bits,
|
| 139 |
+
even_smoothing=even_smoothing, odd_smoothing=odd_smoothing,
|
| 140 |
+
min_signal_remaining=min_signal_remaining, enable_pcan=enable_pcan,
|
| 141 |
+
pcan_strength=pcan_strength, pcan_offset=pcan_offset,
|
| 142 |
+
gain_bits=gain_bits, enable_log=enable_log, scale_shift=scale_shift,
|
| 143 |
+
left_context=left_context, right_context=right_context,
|
| 144 |
+
frame_stride=frame_stride, zero_padding=zero_padding,
|
| 145 |
+
out_scale=out_scale, out_type=out_type, name=name, ctx=_ctx)
|
| 146 |
+
except _core._SymbolicException:
|
| 147 |
+
pass # Add nodes to the TensorFlow graph.
|
| 148 |
+
except (TypeError, ValueError):
|
| 149 |
+
_result = _dispatch.dispatch(
|
| 150 |
+
audio_microfrontend, (), dict(audio=audio,
|
| 151 |
+
sample_rate=sample_rate,
|
| 152 |
+
window_size=window_size,
|
| 153 |
+
window_step=window_step,
|
| 154 |
+
num_channels=num_channels,
|
| 155 |
+
upper_band_limit=upper_band_limit,
|
| 156 |
+
lower_band_limit=lower_band_limit,
|
| 157 |
+
smoothing_bits=smoothing_bits,
|
| 158 |
+
even_smoothing=even_smoothing,
|
| 159 |
+
odd_smoothing=odd_smoothing,
|
| 160 |
+
min_signal_remaining=min_signal_remaining,
|
| 161 |
+
enable_pcan=enable_pcan,
|
| 162 |
+
pcan_strength=pcan_strength,
|
| 163 |
+
pcan_offset=pcan_offset,
|
| 164 |
+
gain_bits=gain_bits,
|
| 165 |
+
enable_log=enable_log,
|
| 166 |
+
scale_shift=scale_shift,
|
| 167 |
+
left_context=left_context,
|
| 168 |
+
right_context=right_context,
|
| 169 |
+
frame_stride=frame_stride,
|
| 170 |
+
zero_padding=zero_padding,
|
| 171 |
+
out_scale=out_scale,
|
| 172 |
+
out_type=out_type, name=name)
|
| 173 |
+
)
|
| 174 |
+
if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
|
| 175 |
+
return _result
|
| 176 |
+
raise
|
| 177 |
+
else:
|
| 178 |
+
_result = _dispatcher_for_audio_microfrontend(
|
| 179 |
+
(audio, sample_rate, window_size, window_step, num_channels,
|
| 180 |
+
upper_band_limit, lower_band_limit, smoothing_bits, even_smoothing,
|
| 181 |
+
odd_smoothing, min_signal_remaining, enable_pcan, pcan_strength,
|
| 182 |
+
pcan_offset, gain_bits, enable_log, scale_shift, left_context,
|
| 183 |
+
right_context, frame_stride, zero_padding, out_scale, out_type,
|
| 184 |
+
name,), None)
|
| 185 |
+
if _result is not NotImplemented:
|
| 186 |
+
return _result
|
| 187 |
+
# Add nodes to the TensorFlow graph.
|
| 188 |
+
if sample_rate is None:
|
| 189 |
+
sample_rate = 16000
|
| 190 |
+
sample_rate = _execute.make_int(sample_rate, "sample_rate")
|
| 191 |
+
if window_size is None:
|
| 192 |
+
window_size = 25
|
| 193 |
+
window_size = _execute.make_int(window_size, "window_size")
|
| 194 |
+
if window_step is None:
|
| 195 |
+
window_step = 10
|
| 196 |
+
window_step = _execute.make_int(window_step, "window_step")
|
| 197 |
+
if num_channels is None:
|
| 198 |
+
num_channels = 32
|
| 199 |
+
num_channels = _execute.make_int(num_channels, "num_channels")
|
| 200 |
+
if upper_band_limit is None:
|
| 201 |
+
upper_band_limit = 7500
|
| 202 |
+
upper_band_limit = _execute.make_float(upper_band_limit, "upper_band_limit")
|
| 203 |
+
if lower_band_limit is None:
|
| 204 |
+
lower_band_limit = 125
|
| 205 |
+
lower_band_limit = _execute.make_float(lower_band_limit, "lower_band_limit")
|
| 206 |
+
if smoothing_bits is None:
|
| 207 |
+
smoothing_bits = 10
|
| 208 |
+
smoothing_bits = _execute.make_int(smoothing_bits, "smoothing_bits")
|
| 209 |
+
if even_smoothing is None:
|
| 210 |
+
even_smoothing = 0.025
|
| 211 |
+
even_smoothing = _execute.make_float(even_smoothing, "even_smoothing")
|
| 212 |
+
if odd_smoothing is None:
|
| 213 |
+
odd_smoothing = 0.06
|
| 214 |
+
odd_smoothing = _execute.make_float(odd_smoothing, "odd_smoothing")
|
| 215 |
+
if min_signal_remaining is None:
|
| 216 |
+
min_signal_remaining = 0.05
|
| 217 |
+
min_signal_remaining = _execute.make_float(min_signal_remaining, "min_signal_remaining")
|
| 218 |
+
if enable_pcan is None:
|
| 219 |
+
enable_pcan = False
|
| 220 |
+
enable_pcan = _execute.make_bool(enable_pcan, "enable_pcan")
|
| 221 |
+
if pcan_strength is None:
|
| 222 |
+
pcan_strength = 0.95
|
| 223 |
+
pcan_strength = _execute.make_float(pcan_strength, "pcan_strength")
|
| 224 |
+
if pcan_offset is None:
|
| 225 |
+
pcan_offset = 80
|
| 226 |
+
pcan_offset = _execute.make_float(pcan_offset, "pcan_offset")
|
| 227 |
+
if gain_bits is None:
|
| 228 |
+
gain_bits = 21
|
| 229 |
+
gain_bits = _execute.make_int(gain_bits, "gain_bits")
|
| 230 |
+
if enable_log is None:
|
| 231 |
+
enable_log = True
|
| 232 |
+
enable_log = _execute.make_bool(enable_log, "enable_log")
|
| 233 |
+
if scale_shift is None:
|
| 234 |
+
scale_shift = 6
|
| 235 |
+
scale_shift = _execute.make_int(scale_shift, "scale_shift")
|
| 236 |
+
if left_context is None:
|
| 237 |
+
left_context = 0
|
| 238 |
+
left_context = _execute.make_int(left_context, "left_context")
|
| 239 |
+
if right_context is None:
|
| 240 |
+
right_context = 0
|
| 241 |
+
right_context = _execute.make_int(right_context, "right_context")
|
| 242 |
+
if frame_stride is None:
|
| 243 |
+
frame_stride = 1
|
| 244 |
+
frame_stride = _execute.make_int(frame_stride, "frame_stride")
|
| 245 |
+
if zero_padding is None:
|
| 246 |
+
zero_padding = False
|
| 247 |
+
zero_padding = _execute.make_bool(zero_padding, "zero_padding")
|
| 248 |
+
if out_scale is None:
|
| 249 |
+
out_scale = 1
|
| 250 |
+
out_scale = _execute.make_int(out_scale, "out_scale")
|
| 251 |
+
if out_type is None:
|
| 252 |
+
out_type = _dtypes.uint16
|
| 253 |
+
out_type = _execute.make_type(out_type, "out_type")
|
| 254 |
+
try:
|
| 255 |
+
_, _, _op, _outputs = _op_def_library._apply_op_helper(
|
| 256 |
+
"AudioMicrofrontend", audio=audio, sample_rate=sample_rate,
|
| 257 |
+
window_size=window_size,
|
| 258 |
+
window_step=window_step,
|
| 259 |
+
num_channels=num_channels,
|
| 260 |
+
upper_band_limit=upper_band_limit,
|
| 261 |
+
lower_band_limit=lower_band_limit,
|
| 262 |
+
smoothing_bits=smoothing_bits,
|
| 263 |
+
even_smoothing=even_smoothing,
|
| 264 |
+
odd_smoothing=odd_smoothing,
|
| 265 |
+
min_signal_remaining=min_signal_remaining,
|
| 266 |
+
enable_pcan=enable_pcan,
|
| 267 |
+
pcan_strength=pcan_strength,
|
| 268 |
+
pcan_offset=pcan_offset, gain_bits=gain_bits,
|
| 269 |
+
enable_log=enable_log, scale_shift=scale_shift,
|
| 270 |
+
left_context=left_context,
|
| 271 |
+
right_context=right_context,
|
| 272 |
+
frame_stride=frame_stride,
|
| 273 |
+
zero_padding=zero_padding, out_scale=out_scale,
|
| 274 |
+
out_type=out_type, name=name)
|
| 275 |
+
except (TypeError, ValueError):
|
| 276 |
+
_result = _dispatch.dispatch(
|
| 277 |
+
audio_microfrontend, (), dict(audio=audio, sample_rate=sample_rate,
|
| 278 |
+
window_size=window_size,
|
| 279 |
+
window_step=window_step,
|
| 280 |
+
num_channels=num_channels,
|
| 281 |
+
upper_band_limit=upper_band_limit,
|
| 282 |
+
lower_band_limit=lower_band_limit,
|
| 283 |
+
smoothing_bits=smoothing_bits,
|
| 284 |
+
even_smoothing=even_smoothing,
|
| 285 |
+
odd_smoothing=odd_smoothing,
|
| 286 |
+
min_signal_remaining=min_signal_remaining,
|
| 287 |
+
enable_pcan=enable_pcan,
|
| 288 |
+
pcan_strength=pcan_strength,
|
| 289 |
+
pcan_offset=pcan_offset,
|
| 290 |
+
gain_bits=gain_bits,
|
| 291 |
+
enable_log=enable_log,
|
| 292 |
+
scale_shift=scale_shift,
|
| 293 |
+
left_context=left_context,
|
| 294 |
+
right_context=right_context,
|
| 295 |
+
frame_stride=frame_stride,
|
| 296 |
+
zero_padding=zero_padding,
|
| 297 |
+
out_scale=out_scale,
|
| 298 |
+
out_type=out_type, name=name)
|
| 299 |
+
)
|
| 300 |
+
if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
|
| 301 |
+
return _result
|
| 302 |
+
raise
|
| 303 |
+
_result = _outputs[:]
|
| 304 |
+
if _execute.must_record_gradient():
|
| 305 |
+
_attrs = ("sample_rate", _op._get_attr_int("sample_rate"), "window_size",
|
| 306 |
+
_op._get_attr_int("window_size"), "window_step",
|
| 307 |
+
_op._get_attr_int("window_step"), "num_channels",
|
| 308 |
+
_op._get_attr_int("num_channels"), "upper_band_limit",
|
| 309 |
+
_op.get_attr("upper_band_limit"), "lower_band_limit",
|
| 310 |
+
_op.get_attr("lower_band_limit"), "smoothing_bits",
|
| 311 |
+
_op._get_attr_int("smoothing_bits"), "even_smoothing",
|
| 312 |
+
_op.get_attr("even_smoothing"), "odd_smoothing",
|
| 313 |
+
_op.get_attr("odd_smoothing"), "min_signal_remaining",
|
| 314 |
+
_op.get_attr("min_signal_remaining"), "enable_pcan",
|
| 315 |
+
_op._get_attr_bool("enable_pcan"), "pcan_strength",
|
| 316 |
+
_op.get_attr("pcan_strength"), "pcan_offset",
|
| 317 |
+
_op.get_attr("pcan_offset"), "gain_bits",
|
| 318 |
+
_op._get_attr_int("gain_bits"), "enable_log",
|
| 319 |
+
_op._get_attr_bool("enable_log"), "scale_shift",
|
| 320 |
+
_op._get_attr_int("scale_shift"), "left_context",
|
| 321 |
+
_op._get_attr_int("left_context"), "right_context",
|
| 322 |
+
_op._get_attr_int("right_context"), "frame_stride",
|
| 323 |
+
_op._get_attr_int("frame_stride"), "zero_padding",
|
| 324 |
+
_op._get_attr_bool("zero_padding"), "out_scale",
|
| 325 |
+
_op._get_attr_int("out_scale"), "out_type",
|
| 326 |
+
_op._get_attr_type("out_type"))
|
| 327 |
+
_inputs_flat = _op.inputs
|
| 328 |
+
_execute.record_gradient(
|
| 329 |
+
"AudioMicrofrontend", _inputs_flat, _attrs, _result)
|
| 330 |
+
_result, = _result
|
| 331 |
+
return _result
|
| 332 |
+
|
| 333 |
+
AudioMicrofrontend = tf_export("raw_ops.AudioMicrofrontend")(_ops.to_raw_op(audio_microfrontend))
|
| 334 |
+
_dispatcher_for_audio_microfrontend = audio_microfrontend._tf_type_based_dispatcher.Dispatch
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def audio_microfrontend_eager_fallback(audio: Annotated[Any, _atypes.Int16], sample_rate: int, window_size: int, window_step: int, num_channels: int, upper_band_limit: float, lower_band_limit: float, smoothing_bits: int, even_smoothing: float, odd_smoothing: float, min_signal_remaining: float, enable_pcan: bool, pcan_strength: float, pcan_offset: float, gain_bits: int, enable_log: bool, scale_shift: int, left_context: int, right_context: int, frame_stride: int, zero_padding: bool, out_scale: int, out_type: TV_AudioMicrofrontend_out_type, name, ctx) -> Annotated[Any, TV_AudioMicrofrontend_out_type]:
|
| 338 |
+
if sample_rate is None:
|
| 339 |
+
sample_rate = 16000
|
| 340 |
+
sample_rate = _execute.make_int(sample_rate, "sample_rate")
|
| 341 |
+
if window_size is None:
|
| 342 |
+
window_size = 25
|
| 343 |
+
window_size = _execute.make_int(window_size, "window_size")
|
| 344 |
+
if window_step is None:
|
| 345 |
+
window_step = 10
|
| 346 |
+
window_step = _execute.make_int(window_step, "window_step")
|
| 347 |
+
if num_channels is None:
|
| 348 |
+
num_channels = 32
|
| 349 |
+
num_channels = _execute.make_int(num_channels, "num_channels")
|
| 350 |
+
if upper_band_limit is None:
|
| 351 |
+
upper_band_limit = 7500
|
| 352 |
+
upper_band_limit = _execute.make_float(upper_band_limit, "upper_band_limit")
|
| 353 |
+
if lower_band_limit is None:
|
| 354 |
+
lower_band_limit = 125
|
| 355 |
+
lower_band_limit = _execute.make_float(lower_band_limit, "lower_band_limit")
|
| 356 |
+
if smoothing_bits is None:
|
| 357 |
+
smoothing_bits = 10
|
| 358 |
+
smoothing_bits = _execute.make_int(smoothing_bits, "smoothing_bits")
|
| 359 |
+
if even_smoothing is None:
|
| 360 |
+
even_smoothing = 0.025
|
| 361 |
+
even_smoothing = _execute.make_float(even_smoothing, "even_smoothing")
|
| 362 |
+
if odd_smoothing is None:
|
| 363 |
+
odd_smoothing = 0.06
|
| 364 |
+
odd_smoothing = _execute.make_float(odd_smoothing, "odd_smoothing")
|
| 365 |
+
if min_signal_remaining is None:
|
| 366 |
+
min_signal_remaining = 0.05
|
| 367 |
+
min_signal_remaining = _execute.make_float(min_signal_remaining, "min_signal_remaining")
|
| 368 |
+
if enable_pcan is None:
|
| 369 |
+
enable_pcan = False
|
| 370 |
+
enable_pcan = _execute.make_bool(enable_pcan, "enable_pcan")
|
| 371 |
+
if pcan_strength is None:
|
| 372 |
+
pcan_strength = 0.95
|
| 373 |
+
pcan_strength = _execute.make_float(pcan_strength, "pcan_strength")
|
| 374 |
+
if pcan_offset is None:
|
| 375 |
+
pcan_offset = 80
|
| 376 |
+
pcan_offset = _execute.make_float(pcan_offset, "pcan_offset")
|
| 377 |
+
if gain_bits is None:
|
| 378 |
+
gain_bits = 21
|
| 379 |
+
gain_bits = _execute.make_int(gain_bits, "gain_bits")
|
| 380 |
+
if enable_log is None:
|
| 381 |
+
enable_log = True
|
| 382 |
+
enable_log = _execute.make_bool(enable_log, "enable_log")
|
| 383 |
+
if scale_shift is None:
|
| 384 |
+
scale_shift = 6
|
| 385 |
+
scale_shift = _execute.make_int(scale_shift, "scale_shift")
|
| 386 |
+
if left_context is None:
|
| 387 |
+
left_context = 0
|
| 388 |
+
left_context = _execute.make_int(left_context, "left_context")
|
| 389 |
+
if right_context is None:
|
| 390 |
+
right_context = 0
|
| 391 |
+
right_context = _execute.make_int(right_context, "right_context")
|
| 392 |
+
if frame_stride is None:
|
| 393 |
+
frame_stride = 1
|
| 394 |
+
frame_stride = _execute.make_int(frame_stride, "frame_stride")
|
| 395 |
+
if zero_padding is None:
|
| 396 |
+
zero_padding = False
|
| 397 |
+
zero_padding = _execute.make_bool(zero_padding, "zero_padding")
|
| 398 |
+
if out_scale is None:
|
| 399 |
+
out_scale = 1
|
| 400 |
+
out_scale = _execute.make_int(out_scale, "out_scale")
|
| 401 |
+
if out_type is None:
|
| 402 |
+
out_type = _dtypes.uint16
|
| 403 |
+
out_type = _execute.make_type(out_type, "out_type")
|
| 404 |
+
audio = _ops.convert_to_tensor(audio, _dtypes.int16)
|
| 405 |
+
_inputs_flat = [audio]
|
| 406 |
+
_attrs = ("sample_rate", sample_rate, "window_size", window_size,
|
| 407 |
+
"window_step", window_step, "num_channels", num_channels,
|
| 408 |
+
"upper_band_limit", upper_band_limit, "lower_band_limit", lower_band_limit,
|
| 409 |
+
"smoothing_bits", smoothing_bits, "even_smoothing", even_smoothing,
|
| 410 |
+
"odd_smoothing", odd_smoothing, "min_signal_remaining",
|
| 411 |
+
min_signal_remaining, "enable_pcan", enable_pcan, "pcan_strength",
|
| 412 |
+
pcan_strength, "pcan_offset", pcan_offset, "gain_bits", gain_bits,
|
| 413 |
+
"enable_log", enable_log, "scale_shift", scale_shift, "left_context",
|
| 414 |
+
left_context, "right_context", right_context, "frame_stride", frame_stride,
|
| 415 |
+
"zero_padding", zero_padding, "out_scale", out_scale, "out_type", out_type)
|
| 416 |
+
_result = _execute.execute(b"AudioMicrofrontend", 1, inputs=_inputs_flat,
|
| 417 |
+
attrs=_attrs, ctx=ctx, name=name)
|
| 418 |
+
if _execute.must_record_gradient():
|
| 419 |
+
_execute.record_gradient(
|
| 420 |
+
"AudioMicrofrontend", _inputs_flat, _attrs, _result)
|
| 421 |
+
_result, = _result
|
| 422 |
+
return _result
|
| 423 |
+
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/microfrontend/python/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/microfrontend/python/ops/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/microfrontend/python/ops/audio_microfrontend_op.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2018 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 |
+
"""AudioMicrofrontend Op creates filterbanks from audio data."""
|
| 16 |
+
|
| 17 |
+
from tensorflow.lite.experimental.microfrontend.ops import gen_audio_microfrontend_op
|
| 18 |
+
from tensorflow.python.framework import dtypes
|
| 19 |
+
from tensorflow.python.framework import load_library
|
| 20 |
+
from tensorflow.python.framework import ops
|
| 21 |
+
from tensorflow.python.ops import array_ops
|
| 22 |
+
from tensorflow.python.platform import resource_loader
|
| 23 |
+
|
| 24 |
+
_audio_microfrontend_op = load_library.load_op_library(
|
| 25 |
+
resource_loader.get_path_to_datafile("_audio_microfrontend_op.so"))
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def audio_microfrontend(audio,
|
| 29 |
+
sample_rate=16000,
|
| 30 |
+
window_size=25,
|
| 31 |
+
window_step=10,
|
| 32 |
+
num_channels=32,
|
| 33 |
+
upper_band_limit=7500.0,
|
| 34 |
+
lower_band_limit=125.0,
|
| 35 |
+
smoothing_bits=10,
|
| 36 |
+
even_smoothing=0.025,
|
| 37 |
+
odd_smoothing=0.06,
|
| 38 |
+
min_signal_remaining=0.05,
|
| 39 |
+
enable_pcan=True,
|
| 40 |
+
pcan_strength=0.95,
|
| 41 |
+
pcan_offset=80.0,
|
| 42 |
+
gain_bits=21,
|
| 43 |
+
enable_log=True,
|
| 44 |
+
scale_shift=6,
|
| 45 |
+
left_context=0,
|
| 46 |
+
right_context=0,
|
| 47 |
+
frame_stride=1,
|
| 48 |
+
zero_padding=False,
|
| 49 |
+
out_scale=1,
|
| 50 |
+
out_type=dtypes.uint16):
|
| 51 |
+
"""Audio Microfrontend Op.
|
| 52 |
+
|
| 53 |
+
This Op converts a sequence of audio data into one or more
|
| 54 |
+
feature vectors containing filterbanks of the input. The
|
| 55 |
+
conversion process uses a lightweight library to perform:
|
| 56 |
+
|
| 57 |
+
1. A slicing window function
|
| 58 |
+
2. Short-time FFTs
|
| 59 |
+
3. Filterbank calculations
|
| 60 |
+
4. Noise reduction
|
| 61 |
+
5. PCAN Auto Gain Control
|
| 62 |
+
6. Logarithmic scaling
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
audio: 1D Tensor, int16 audio data in temporal ordering.
|
| 66 |
+
sample_rate: Integer, the sample rate of the audio in Hz.
|
| 67 |
+
window_size: Integer, length of desired time frames in ms.
|
| 68 |
+
window_step: Integer, length of step size for the next frame in ms.
|
| 69 |
+
num_channels: Integer, the number of filterbank channels to use.
|
| 70 |
+
upper_band_limit: Float, the highest frequency included in the filterbanks.
|
| 71 |
+
lower_band_limit: Float, the lowest frequency included in the filterbanks.
|
| 72 |
+
smoothing_bits: Int, scale up signal by 2^(smoothing_bits) before reduction.
|
| 73 |
+
even_smoothing: Float, smoothing coefficient for even-numbered channels.
|
| 74 |
+
odd_smoothing: Float, smoothing coefficient for odd-numbered channels.
|
| 75 |
+
min_signal_remaining: Float, fraction of signal to preserve in smoothing.
|
| 76 |
+
enable_pcan: Bool, enable PCAN auto gain control.
|
| 77 |
+
pcan_strength: Float, gain normalization exponent.
|
| 78 |
+
pcan_offset: Float, positive value added in the normalization denominator.
|
| 79 |
+
gain_bits: Int, number of fractional bits in the gain.
|
| 80 |
+
enable_log: Bool, enable logarithmic scaling of filterbanks.
|
| 81 |
+
scale_shift: Integer, scale filterbanks by 2^(scale_shift).
|
| 82 |
+
left_context: Integer, number of preceding frames to attach to each frame.
|
| 83 |
+
right_context: Integer, number of preceding frames to attach to each frame.
|
| 84 |
+
frame_stride: Integer, M frames to skip over, where output[n] = frame[n*M].
|
| 85 |
+
zero_padding: Bool, if left/right context is out-of-bounds, attach frame of
|
| 86 |
+
zeroes. Otherwise, frame[0] or frame[size-1] will be copied.
|
| 87 |
+
out_scale: Integer, divide all filterbanks by this number.
|
| 88 |
+
out_type: DType, type of the output Tensor, defaults to UINT16.
|
| 89 |
+
|
| 90 |
+
Returns:
|
| 91 |
+
filterbanks: 2D Tensor, each row is a time frame, each column is a channel.
|
| 92 |
+
|
| 93 |
+
Raises:
|
| 94 |
+
ValueError: If the audio tensor is not explicitly a vector.
|
| 95 |
+
"""
|
| 96 |
+
audio_shape = audio.shape
|
| 97 |
+
if audio_shape.ndims is None:
|
| 98 |
+
raise ValueError("Input to `AudioMicrofrontend` should have known rank.")
|
| 99 |
+
if len(audio_shape) > 1:
|
| 100 |
+
audio = array_ops.reshape(audio, [-1])
|
| 101 |
+
|
| 102 |
+
return gen_audio_microfrontend_op.audio_microfrontend(
|
| 103 |
+
audio, sample_rate, window_size, window_step, num_channels,
|
| 104 |
+
upper_band_limit, lower_band_limit, smoothing_bits, even_smoothing,
|
| 105 |
+
odd_smoothing, min_signal_remaining, enable_pcan, pcan_strength,
|
| 106 |
+
pcan_offset, gain_bits, enable_log, scale_shift, left_context,
|
| 107 |
+
right_context, frame_stride, zero_padding, out_scale, out_type)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
ops.NotDifferentiable("AudioMicrofrontend")
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/analyzer.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""This tool analyzes a TensorFlow Lite graph."""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
|
| 19 |
+
# pylint: disable=g-import-not-at-top
|
| 20 |
+
if not os.path.splitext(__file__)[0].endswith(
|
| 21 |
+
os.path.join("tflite_runtime", "analyzer")):
|
| 22 |
+
# This file is part of tensorflow package.
|
| 23 |
+
from tensorflow.lite.python import wrap_toco
|
| 24 |
+
from tensorflow.lite.python.analyzer_wrapper import _pywrap_analyzer_wrapper as _analyzer_wrapper
|
| 25 |
+
from tensorflow.python.util.tf_export import tf_export as _tf_export
|
| 26 |
+
else:
|
| 27 |
+
# This file is part of tflite_runtime package.
|
| 28 |
+
from tflite_runtime import _pywrap_analyzer_wrapper as _analyzer_wrapper
|
| 29 |
+
|
| 30 |
+
def _tf_export(*x, **kwargs):
|
| 31 |
+
del x, kwargs
|
| 32 |
+
return lambda x: x
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@_tf_export("lite.experimental.Analyzer")
|
| 36 |
+
class ModelAnalyzer():
|
| 37 |
+
"""Provides a collection of TFLite model analyzer tools.
|
| 38 |
+
|
| 39 |
+
Example:
|
| 40 |
+
|
| 41 |
+
```python
|
| 42 |
+
model = tf.keras.applications.MobileNetV3Large()
|
| 43 |
+
fb_model = tf.lite.TFLiteConverterV2.from_keras_model(model).convert()
|
| 44 |
+
tf.lite.experimental.Analyzer.analyze(model_content=fb_model)
|
| 45 |
+
# === TFLite ModelAnalyzer ===
|
| 46 |
+
#
|
| 47 |
+
# Your TFLite model has ‘1’ subgraph(s). In the subgraph description below,
|
| 48 |
+
# T# represents the Tensor numbers. For example, in Subgraph#0, the MUL op
|
| 49 |
+
# takes tensor #0 and tensor #19 as input and produces tensor #136 as output.
|
| 50 |
+
#
|
| 51 |
+
# Subgraph#0 main(T#0) -> [T#263]
|
| 52 |
+
# Op#0 MUL(T#0, T#19) -> [T#136]
|
| 53 |
+
# Op#1 ADD(T#136, T#18) -> [T#137]
|
| 54 |
+
# Op#2 CONV_2D(T#137, T#44, T#93) -> [T#138]
|
| 55 |
+
# Op#3 HARD_SWISH(T#138) -> [T#139]
|
| 56 |
+
# Op#4 DEPTHWISE_CONV_2D(T#139, T#94, T#24) -> [T#140]
|
| 57 |
+
# ...
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
WARNING: Experimental interface, subject to change.
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
@staticmethod
|
| 64 |
+
def analyze(model_path=None,
|
| 65 |
+
model_content=None,
|
| 66 |
+
gpu_compatibility=False,
|
| 67 |
+
**kwargs):
|
| 68 |
+
"""Analyzes the given tflite_model with dumping model structure.
|
| 69 |
+
|
| 70 |
+
This tool provides a way to understand users' TFLite flatbuffer model by
|
| 71 |
+
dumping internal graph structure. It also provides additional features
|
| 72 |
+
like checking GPU delegate compatibility.
|
| 73 |
+
|
| 74 |
+
WARNING: Experimental interface, subject to change.
|
| 75 |
+
The output format is not guaranteed to stay stable, so don't
|
| 76 |
+
write scripts to this.
|
| 77 |
+
|
| 78 |
+
Args:
|
| 79 |
+
model_path: TFLite flatbuffer model path.
|
| 80 |
+
model_content: TFLite flatbuffer model object.
|
| 81 |
+
gpu_compatibility: Whether to check GPU delegate compatibility.
|
| 82 |
+
**kwargs: Experimental keyword arguments to analyze API.
|
| 83 |
+
|
| 84 |
+
Returns:
|
| 85 |
+
Print analyzed report via console output.
|
| 86 |
+
"""
|
| 87 |
+
if not model_path and not model_content:
|
| 88 |
+
raise ValueError("neither `model_path` nor `model_content` is provided")
|
| 89 |
+
if model_path:
|
| 90 |
+
print(f"=== {model_path} ===\n")
|
| 91 |
+
tflite_model = model_path
|
| 92 |
+
input_is_filepath = True
|
| 93 |
+
else:
|
| 94 |
+
print("=== TFLite ModelAnalyzer ===\n")
|
| 95 |
+
tflite_model = model_content
|
| 96 |
+
input_is_filepath = False
|
| 97 |
+
|
| 98 |
+
if kwargs.get("experimental_use_mlir", False):
|
| 99 |
+
print(
|
| 100 |
+
wrap_toco.wrapped_flat_buffer_file_to_mlir(tflite_model,
|
| 101 |
+
input_is_filepath))
|
| 102 |
+
else:
|
| 103 |
+
print(
|
| 104 |
+
_analyzer_wrapper.ModelAnalyzer(tflite_model, input_is_filepath,
|
| 105 |
+
gpu_compatibility))
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/analyzer_wrapper/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/analyzer_wrapper/_pywrap_analyzer_wrapper.pyi
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 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 |
+
|
| 16 |
+
def ModelAnalyzer(arg0: str, arg1: bool, arg2: bool) -> str: ...
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/authoring/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/authoring/authoring.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""TensorFlow Authoring tool package for TFLite compatibility.
|
| 16 |
+
|
| 17 |
+
WARNING: The package is experimental and subject to change.
|
| 18 |
+
|
| 19 |
+
This package provides a way to check TFLite compatibility at model authoring
|
| 20 |
+
time.
|
| 21 |
+
|
| 22 |
+
Example:
|
| 23 |
+
@tf.lite.experimental.authoring.compatible
|
| 24 |
+
@tf.function(input_signature=[
|
| 25 |
+
tf.TensorSpec(shape=[None], dtype=tf.float32)
|
| 26 |
+
])
|
| 27 |
+
def f(x):
|
| 28 |
+
return tf.cosh(x)
|
| 29 |
+
|
| 30 |
+
result = f(tf.constant([0.0]))
|
| 31 |
+
|
| 32 |
+
> COMPATIBILITY WARNING: op 'tf.Cosh' require(s) "Select TF Ops" for model
|
| 33 |
+
> conversion for TensorFlow Lite.
|
| 34 |
+
> Op: tf.Cosh
|
| 35 |
+
> - tensorflow/python/framework/op_def_library.py:xxx
|
| 36 |
+
> - tensorflow/python/ops/gen_math_ops.py:xxx
|
| 37 |
+
> - simple_authoring.py:xxx
|
| 38 |
+
"""
|
| 39 |
+
import functools
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# pylint: disable=g-import-not-at-top
|
| 43 |
+
from tensorflow.lite.python import convert
|
| 44 |
+
from tensorflow.lite.python import lite
|
| 45 |
+
from tensorflow.lite.python.metrics import converter_error_data_pb2
|
| 46 |
+
from tensorflow.python.util.tf_export import tf_export as _tf_export
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
_CUSTOM_OPS_HDR = "Custom ops: "
|
| 50 |
+
_TF_OPS_HDR = "TF Select ops: "
|
| 51 |
+
_AUTHORING_ERROR_HDR = "COMPATIBILITY ERROR"
|
| 52 |
+
_AUTHORING_WARNING_HDR = "COMPATIBILITY WARNING"
|
| 53 |
+
_FUNC_GRAPH_SRC_PATH = "tensorflow/python/framework/func_graph.py"
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class CompatibilityError(Exception):
|
| 57 |
+
"""Raised when an error occurs with TFLite compatibility."""
|
| 58 |
+
pass
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class _Compatible:
|
| 62 |
+
"""A decorator class to check TFLite compatibility created by `lite.experimental.authoring.compatible`."""
|
| 63 |
+
|
| 64 |
+
def __init__(self,
|
| 65 |
+
target,
|
| 66 |
+
converter_target_spec=None,
|
| 67 |
+
converter_allow_custom_ops=None,
|
| 68 |
+
raise_exception=False):
|
| 69 |
+
"""Initialize the decorator object.
|
| 70 |
+
|
| 71 |
+
Here is the description of the object variables.
|
| 72 |
+
- _func : decorated function.
|
| 73 |
+
- _obj_func : for class object, we need to use this object to provide `self`
|
| 74 |
+
instance as 1 first argument.
|
| 75 |
+
- _verified : whether the compatibility is checked or not.
|
| 76 |
+
|
| 77 |
+
Args:
|
| 78 |
+
target: decorated function.
|
| 79 |
+
converter_target_spec : target_spec of TFLite converter parameter.
|
| 80 |
+
converter_allow_custom_ops : allow_custom_ops of TFLite converter
|
| 81 |
+
parameter.
|
| 82 |
+
raise_exception : to raise an exception on compatibility issues.
|
| 83 |
+
User need to use get_compatibility_log() to check details.
|
| 84 |
+
"""
|
| 85 |
+
functools.update_wrapper(self, target)
|
| 86 |
+
self._func = target
|
| 87 |
+
self._obj_func = None
|
| 88 |
+
self._verified = False
|
| 89 |
+
self._log_messages = []
|
| 90 |
+
self._raise_exception = raise_exception
|
| 91 |
+
self._converter_target_spec = converter_target_spec
|
| 92 |
+
self._converter_allow_custom_ops = converter_allow_custom_ops
|
| 93 |
+
|
| 94 |
+
def __get__(self, instance, cls):
|
| 95 |
+
"""A Python descriptor interface."""
|
| 96 |
+
self._obj_func = self._func.__get__(instance, cls)
|
| 97 |
+
return self
|
| 98 |
+
|
| 99 |
+
def _get_func(self):
|
| 100 |
+
"""Returns decorated function object.
|
| 101 |
+
|
| 102 |
+
For a class method, use self._obj_func to provide `self` instance.
|
| 103 |
+
"""
|
| 104 |
+
if self._obj_func is not None:
|
| 105 |
+
return self._obj_func
|
| 106 |
+
else:
|
| 107 |
+
return self._func
|
| 108 |
+
|
| 109 |
+
def __call__(self, *args, **kwargs): # pylint: disable=g-doc-args
|
| 110 |
+
"""Calls decorated function object.
|
| 111 |
+
|
| 112 |
+
Also verifies if the function is compatible with TFLite.
|
| 113 |
+
|
| 114 |
+
Returns:
|
| 115 |
+
A execution result of the decorated function.
|
| 116 |
+
"""
|
| 117 |
+
|
| 118 |
+
if not self._verified:
|
| 119 |
+
model = self._get_func()
|
| 120 |
+
concrete_func = model.get_concrete_function(*args, **kwargs)
|
| 121 |
+
converter = lite.TFLiteConverterV2.from_concrete_functions(
|
| 122 |
+
[concrete_func], model)
|
| 123 |
+
# Set provided converter parameters
|
| 124 |
+
if self._converter_target_spec is not None:
|
| 125 |
+
converter.target_spec = self._converter_target_spec
|
| 126 |
+
if self._converter_allow_custom_ops is not None:
|
| 127 |
+
converter.allow_custom_ops = self._converter_allow_custom_ops
|
| 128 |
+
try:
|
| 129 |
+
converter.convert()
|
| 130 |
+
except convert.ConverterError as err:
|
| 131 |
+
self._decode_error(err)
|
| 132 |
+
finally:
|
| 133 |
+
self._verified = True
|
| 134 |
+
|
| 135 |
+
return self._get_func()(*args, **kwargs)
|
| 136 |
+
|
| 137 |
+
def get_concrete_function(self, *args, **kwargs):
|
| 138 |
+
"""Returns a concrete function of the decorated function."""
|
| 139 |
+
return self._get_func().get_concrete_function(*args, **kwargs)
|
| 140 |
+
|
| 141 |
+
def _get_location_string(self, location):
|
| 142 |
+
"""Dump location of ConveterError.errors.location."""
|
| 143 |
+
callstack = []
|
| 144 |
+
for single_call in reversed(location.call):
|
| 145 |
+
if (location.type ==
|
| 146 |
+
converter_error_data_pb2.ConverterErrorData.CALLSITELOC):
|
| 147 |
+
callstack.append(
|
| 148 |
+
f" - {single_call.source.filename}:{single_call.source.line}")
|
| 149 |
+
else:
|
| 150 |
+
callstack.append(str(single_call))
|
| 151 |
+
callstack_dump = "\n".join(callstack)
|
| 152 |
+
return callstack_dump
|
| 153 |
+
|
| 154 |
+
def _dump_error_details(self, ops, locations):
|
| 155 |
+
"""Dump the list of ops and locations."""
|
| 156 |
+
for i in range(0, len(ops)):
|
| 157 |
+
callstack_dump = self._get_location_string(locations[i])
|
| 158 |
+
err_string = f"Op: {ops[i]}\n{callstack_dump}\n"
|
| 159 |
+
self._log(err_string)
|
| 160 |
+
|
| 161 |
+
def _decode_error_legacy(self, err):
|
| 162 |
+
"""Parses the given legacy ConverterError for OSS."""
|
| 163 |
+
for line in str(err).splitlines():
|
| 164 |
+
# Check custom op usage error.
|
| 165 |
+
if line.startswith(_CUSTOM_OPS_HDR):
|
| 166 |
+
custom_ops = line[len(_CUSTOM_OPS_HDR):]
|
| 167 |
+
err_string = (
|
| 168 |
+
f"{_AUTHORING_ERROR_HDR}: op '{custom_ops}' is(are) not natively "
|
| 169 |
+
"supported by TensorFlow Lite. You need to provide a custom "
|
| 170 |
+
"operator. https://www.tensorflow.org/lite/guide/ops_custom")
|
| 171 |
+
self._log(err_string)
|
| 172 |
+
# Check TensorFlow op usage error.
|
| 173 |
+
elif line.startswith(_TF_OPS_HDR):
|
| 174 |
+
tf_ops = line[len(_TF_OPS_HDR):]
|
| 175 |
+
err_string = (
|
| 176 |
+
f"{_AUTHORING_WARNING_HDR}: op '{tf_ops}' require(s) \"Select TF "
|
| 177 |
+
"Ops\" for model conversion for TensorFlow Lite. "
|
| 178 |
+
"https://www.tensorflow.org/lite/guide/ops_select")
|
| 179 |
+
self._log(err_string)
|
| 180 |
+
|
| 181 |
+
def _decode_converter_error(self, err):
|
| 182 |
+
"""Parses the given ConverterError which has detailed error information."""
|
| 183 |
+
custom_ops = []
|
| 184 |
+
custom_ops_location = []
|
| 185 |
+
tf_ops = []
|
| 186 |
+
tf_ops_location = []
|
| 187 |
+
gpu_not_compatible_ops = []
|
| 188 |
+
for err in err.errors:
|
| 189 |
+
# Check custom op usage error.
|
| 190 |
+
if err.error_code == converter_error_data_pb2.ConverterErrorData.ERROR_NEEDS_CUSTOM_OPS:
|
| 191 |
+
custom_ops.append(err.operator.name)
|
| 192 |
+
custom_ops_location.append(err.location)
|
| 193 |
+
# Check TensorFlow op usage error.
|
| 194 |
+
elif err.error_code == converter_error_data_pb2.ConverterErrorData.ERROR_NEEDS_FLEX_OPS:
|
| 195 |
+
tf_ops.append(err.operator.name)
|
| 196 |
+
tf_ops_location.append(err.location)
|
| 197 |
+
# Check GPU delegate compatibility error.
|
| 198 |
+
elif err.error_code == converter_error_data_pb2.ConverterErrorData.ERROR_GPU_NOT_COMPATIBLE:
|
| 199 |
+
gpu_not_compatible_ops.append(err.operator.name)
|
| 200 |
+
# Log the first line of ConveterError.errors.error_message only
|
| 201 |
+
# since the seond line is "Error code: xxxx"
|
| 202 |
+
self._log(err.error_message.splitlines()[0])
|
| 203 |
+
self._log(self._get_location_string(err.location) + "\n")
|
| 204 |
+
else:
|
| 205 |
+
# Log other errors.
|
| 206 |
+
self._log(f"{_AUTHORING_ERROR_HDR}: {err.error_message}")
|
| 207 |
+
self._log(self._get_location_string(err.location) + "\n")
|
| 208 |
+
|
| 209 |
+
if custom_ops:
|
| 210 |
+
custom_ops_str = ", ".join(sorted(custom_ops))
|
| 211 |
+
err_string = (
|
| 212 |
+
f"{_AUTHORING_ERROR_HDR}: op '{custom_ops_str}' is(are) not natively "
|
| 213 |
+
"supported by TensorFlow Lite. You need to provide a custom "
|
| 214 |
+
"operator. https://www.tensorflow.org/lite/guide/ops_custom")
|
| 215 |
+
self._log(err_string)
|
| 216 |
+
self._dump_error_details(custom_ops, custom_ops_location)
|
| 217 |
+
|
| 218 |
+
if tf_ops:
|
| 219 |
+
tf_ops_str = ", ".join(sorted(tf_ops))
|
| 220 |
+
err_string = (
|
| 221 |
+
f"{_AUTHORING_WARNING_HDR}: op '{tf_ops_str}' require(s) \"Select TF"
|
| 222 |
+
" Ops\" for model conversion for TensorFlow Lite. "
|
| 223 |
+
"https://www.tensorflow.org/lite/guide/ops_select")
|
| 224 |
+
self._log(err_string)
|
| 225 |
+
self._dump_error_details(tf_ops, tf_ops_location)
|
| 226 |
+
|
| 227 |
+
if gpu_not_compatible_ops:
|
| 228 |
+
not_compatible_ops_str = ", ".join(sorted(gpu_not_compatible_ops))
|
| 229 |
+
err_string = (
|
| 230 |
+
f"{_AUTHORING_WARNING_HDR}: op '{not_compatible_ops_str}' aren't "
|
| 231 |
+
"compatible with TensorFlow Lite GPU delegate. "
|
| 232 |
+
"https://www.tensorflow.org/lite/performance/gpu")
|
| 233 |
+
self._log(err_string)
|
| 234 |
+
|
| 235 |
+
def _decode_error(self, err):
|
| 236 |
+
"""Parses the given ConverterError and generates compatibility warnings."""
|
| 237 |
+
if hasattr(err, "errors"):
|
| 238 |
+
self._decode_converter_error(err)
|
| 239 |
+
else:
|
| 240 |
+
self._decode_error_legacy(err)
|
| 241 |
+
|
| 242 |
+
if self._raise_exception and self._log_messages:
|
| 243 |
+
raise CompatibilityError(f"CompatibilityException at {repr(self._func)}")
|
| 244 |
+
|
| 245 |
+
def _log(self, message):
|
| 246 |
+
"""Log and print authoring warning / error message."""
|
| 247 |
+
self._log_messages.append(message)
|
| 248 |
+
print(message)
|
| 249 |
+
|
| 250 |
+
def get_compatibility_log(self):
|
| 251 |
+
"""Returns list of compatibility log messages.
|
| 252 |
+
|
| 253 |
+
WARNING: This method should only be used for unit tests.
|
| 254 |
+
|
| 255 |
+
Returns:
|
| 256 |
+
The list of log messages by the recent compatibility check.
|
| 257 |
+
Raises:
|
| 258 |
+
RuntimeError: when the compatibility was NOT checked.
|
| 259 |
+
"""
|
| 260 |
+
if not self._verified:
|
| 261 |
+
raise RuntimeError("target compatibility isn't verified yet")
|
| 262 |
+
return self._log_messages
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
@_tf_export("lite.experimental.authoring.compatible")
|
| 266 |
+
def compatible(target=None, converter_target_spec=None, **kwargs):
|
| 267 |
+
"""Wraps `tf.function` into a callable function with TFLite compatibility checking.
|
| 268 |
+
|
| 269 |
+
Example:
|
| 270 |
+
|
| 271 |
+
```python
|
| 272 |
+
@tf.lite.experimental.authoring.compatible
|
| 273 |
+
@tf.function(input_signature=[
|
| 274 |
+
tf.TensorSpec(shape=[None], dtype=tf.float32)
|
| 275 |
+
])
|
| 276 |
+
def f(x):
|
| 277 |
+
return tf.cosh(x)
|
| 278 |
+
|
| 279 |
+
result = f(tf.constant([0.0]))
|
| 280 |
+
# COMPATIBILITY WARNING: op 'tf.Cosh' require(s) "Select TF Ops" for model
|
| 281 |
+
# conversion for TensorFlow Lite.
|
| 282 |
+
# Op: tf.Cosh
|
| 283 |
+
# - tensorflow/python/framework/op_def_library.py:748
|
| 284 |
+
# - tensorflow/python/ops/gen_math_ops.py:2458
|
| 285 |
+
# - <stdin>:6
|
| 286 |
+
```
|
| 287 |
+
|
| 288 |
+
WARNING: Experimental interface, subject to change.
|
| 289 |
+
|
| 290 |
+
Args:
|
| 291 |
+
target: A `tf.function` to decorate.
|
| 292 |
+
converter_target_spec : target_spec of TFLite converter parameter.
|
| 293 |
+
**kwargs: The keyword arguments of the decorator class _Compatible.
|
| 294 |
+
|
| 295 |
+
Returns:
|
| 296 |
+
A callable object of `tf.lite.experimental.authoring._Compatible`.
|
| 297 |
+
"""
|
| 298 |
+
if target is None:
|
| 299 |
+
def wrapper(target):
|
| 300 |
+
return _Compatible(target, converter_target_spec, **kwargs)
|
| 301 |
+
return wrapper
|
| 302 |
+
else:
|
| 303 |
+
return _Compatible(target, converter_target_spec, **kwargs)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/conversion_metadata_schema_py_generated.py
ADDED
|
@@ -0,0 +1,554 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import flatbuffers
|
| 2 |
+
|
| 3 |
+
# automatically generated by the FlatBuffers compiler, do not modify
|
| 4 |
+
|
| 5 |
+
# namespace: tflite
|
| 6 |
+
|
| 7 |
+
from flatbuffers.compat import import_numpy
|
| 8 |
+
np = import_numpy()
|
| 9 |
+
|
| 10 |
+
class ModelType(object):
|
| 11 |
+
NONE = 0
|
| 12 |
+
TF_SAVED_MODEL = 1
|
| 13 |
+
KERAS_MODEL = 2
|
| 14 |
+
TF_CONCRETE_FUNCTIONS = 3
|
| 15 |
+
TF_GRAPH_DEF = 4
|
| 16 |
+
TF_SESSION = 5
|
| 17 |
+
JAX = 6
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class ModelOptimizationMode(object):
|
| 21 |
+
PTQ_FLOAT16 = 1001
|
| 22 |
+
PTQ_DYNAMIC_RANGE = 1002
|
| 23 |
+
PTQ_FULL_INTEGER = 1003
|
| 24 |
+
PTQ_INT16 = 1004
|
| 25 |
+
QUANTIZATION_AWARE_TRAINING = 2000
|
| 26 |
+
RANDOM_SPARSITY = 3001
|
| 27 |
+
BLOCK_SPARSITY = 3002
|
| 28 |
+
STRUCTURED_SPARSITY = 3003
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class Environment(object):
|
| 32 |
+
__slots__ = ['_tab']
|
| 33 |
+
|
| 34 |
+
@classmethod
|
| 35 |
+
def GetRootAs(cls, buf, offset=0):
|
| 36 |
+
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
|
| 37 |
+
x = Environment()
|
| 38 |
+
x.Init(buf, n + offset)
|
| 39 |
+
return x
|
| 40 |
+
|
| 41 |
+
@classmethod
|
| 42 |
+
def GetRootAsEnvironment(cls, buf, offset=0):
|
| 43 |
+
"""This method is deprecated. Please switch to GetRootAs."""
|
| 44 |
+
return cls.GetRootAs(buf, offset)
|
| 45 |
+
# Environment
|
| 46 |
+
def Init(self, buf, pos):
|
| 47 |
+
self._tab = flatbuffers.table.Table(buf, pos)
|
| 48 |
+
|
| 49 |
+
# Environment
|
| 50 |
+
def TensorflowVersion(self):
|
| 51 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
|
| 52 |
+
if o != 0:
|
| 53 |
+
return self._tab.String(o + self._tab.Pos)
|
| 54 |
+
return None
|
| 55 |
+
|
| 56 |
+
# Environment
|
| 57 |
+
def ApiVersion(self):
|
| 58 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
|
| 59 |
+
if o != 0:
|
| 60 |
+
return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos)
|
| 61 |
+
return 0
|
| 62 |
+
|
| 63 |
+
# Environment
|
| 64 |
+
def ModelType(self):
|
| 65 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8))
|
| 66 |
+
if o != 0:
|
| 67 |
+
return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos)
|
| 68 |
+
return 0
|
| 69 |
+
|
| 70 |
+
def EnvironmentStart(builder):
|
| 71 |
+
builder.StartObject(3)
|
| 72 |
+
|
| 73 |
+
def EnvironmentAddTensorflowVersion(builder, tensorflowVersion):
|
| 74 |
+
builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(tensorflowVersion), 0)
|
| 75 |
+
|
| 76 |
+
def EnvironmentAddApiVersion(builder, apiVersion):
|
| 77 |
+
builder.PrependUint32Slot(1, apiVersion, 0)
|
| 78 |
+
|
| 79 |
+
def EnvironmentAddModelType(builder, modelType):
|
| 80 |
+
builder.PrependInt32Slot(2, modelType, 0)
|
| 81 |
+
|
| 82 |
+
def EnvironmentEnd(builder):
|
| 83 |
+
return builder.EndObject()
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class EnvironmentT(object):
|
| 88 |
+
|
| 89 |
+
# EnvironmentT
|
| 90 |
+
def __init__(self):
|
| 91 |
+
self.tensorflowVersion = None # type: str
|
| 92 |
+
self.apiVersion = 0 # type: int
|
| 93 |
+
self.modelType = 0 # type: int
|
| 94 |
+
|
| 95 |
+
@classmethod
|
| 96 |
+
def InitFromBuf(cls, buf, pos):
|
| 97 |
+
environment = Environment()
|
| 98 |
+
environment.Init(buf, pos)
|
| 99 |
+
return cls.InitFromObj(environment)
|
| 100 |
+
|
| 101 |
+
@classmethod
|
| 102 |
+
def InitFromPackedBuf(cls, buf, pos=0):
|
| 103 |
+
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos)
|
| 104 |
+
return cls.InitFromBuf(buf, pos+n)
|
| 105 |
+
|
| 106 |
+
@classmethod
|
| 107 |
+
def InitFromObj(cls, environment):
|
| 108 |
+
x = EnvironmentT()
|
| 109 |
+
x._UnPack(environment)
|
| 110 |
+
return x
|
| 111 |
+
|
| 112 |
+
# EnvironmentT
|
| 113 |
+
def _UnPack(self, environment):
|
| 114 |
+
if environment is None:
|
| 115 |
+
return
|
| 116 |
+
self.tensorflowVersion = environment.TensorflowVersion()
|
| 117 |
+
self.apiVersion = environment.ApiVersion()
|
| 118 |
+
self.modelType = environment.ModelType()
|
| 119 |
+
|
| 120 |
+
# EnvironmentT
|
| 121 |
+
def Pack(self, builder):
|
| 122 |
+
if self.tensorflowVersion is not None:
|
| 123 |
+
tensorflowVersion = builder.CreateString(self.tensorflowVersion)
|
| 124 |
+
EnvironmentStart(builder)
|
| 125 |
+
if self.tensorflowVersion is not None:
|
| 126 |
+
EnvironmentAddTensorflowVersion(builder, tensorflowVersion)
|
| 127 |
+
EnvironmentAddApiVersion(builder, self.apiVersion)
|
| 128 |
+
EnvironmentAddModelType(builder, self.modelType)
|
| 129 |
+
environment = EnvironmentEnd(builder)
|
| 130 |
+
return environment
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class SparsityBlockSize(object):
|
| 134 |
+
__slots__ = ['_tab']
|
| 135 |
+
|
| 136 |
+
@classmethod
|
| 137 |
+
def GetRootAs(cls, buf, offset=0):
|
| 138 |
+
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
|
| 139 |
+
x = SparsityBlockSize()
|
| 140 |
+
x.Init(buf, n + offset)
|
| 141 |
+
return x
|
| 142 |
+
|
| 143 |
+
@classmethod
|
| 144 |
+
def GetRootAsSparsityBlockSize(cls, buf, offset=0):
|
| 145 |
+
"""This method is deprecated. Please switch to GetRootAs."""
|
| 146 |
+
return cls.GetRootAs(buf, offset)
|
| 147 |
+
# SparsityBlockSize
|
| 148 |
+
def Init(self, buf, pos):
|
| 149 |
+
self._tab = flatbuffers.table.Table(buf, pos)
|
| 150 |
+
|
| 151 |
+
# SparsityBlockSize
|
| 152 |
+
def Values(self, j):
|
| 153 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
|
| 154 |
+
if o != 0:
|
| 155 |
+
a = self._tab.Vector(o)
|
| 156 |
+
return self._tab.Get(flatbuffers.number_types.Uint32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4))
|
| 157 |
+
return 0
|
| 158 |
+
|
| 159 |
+
# SparsityBlockSize
|
| 160 |
+
def ValuesAsNumpy(self):
|
| 161 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
|
| 162 |
+
if o != 0:
|
| 163 |
+
return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint32Flags, o)
|
| 164 |
+
return 0
|
| 165 |
+
|
| 166 |
+
# SparsityBlockSize
|
| 167 |
+
def ValuesLength(self):
|
| 168 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
|
| 169 |
+
if o != 0:
|
| 170 |
+
return self._tab.VectorLen(o)
|
| 171 |
+
return 0
|
| 172 |
+
|
| 173 |
+
# SparsityBlockSize
|
| 174 |
+
def ValuesIsNone(self):
|
| 175 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
|
| 176 |
+
return o == 0
|
| 177 |
+
|
| 178 |
+
def SparsityBlockSizeStart(builder):
|
| 179 |
+
builder.StartObject(1)
|
| 180 |
+
|
| 181 |
+
def SparsityBlockSizeAddValues(builder, values):
|
| 182 |
+
builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(values), 0)
|
| 183 |
+
|
| 184 |
+
def SparsityBlockSizeStartValuesVector(builder, numElems):
|
| 185 |
+
return builder.StartVector(4, numElems, 4)
|
| 186 |
+
|
| 187 |
+
def SparsityBlockSizeEnd(builder):
|
| 188 |
+
return builder.EndObject()
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
try:
|
| 192 |
+
from typing import List
|
| 193 |
+
except:
|
| 194 |
+
pass
|
| 195 |
+
|
| 196 |
+
class SparsityBlockSizeT(object):
|
| 197 |
+
|
| 198 |
+
# SparsityBlockSizeT
|
| 199 |
+
def __init__(self):
|
| 200 |
+
self.values = None # type: List[int]
|
| 201 |
+
|
| 202 |
+
@classmethod
|
| 203 |
+
def InitFromBuf(cls, buf, pos):
|
| 204 |
+
sparsityBlockSize = SparsityBlockSize()
|
| 205 |
+
sparsityBlockSize.Init(buf, pos)
|
| 206 |
+
return cls.InitFromObj(sparsityBlockSize)
|
| 207 |
+
|
| 208 |
+
@classmethod
|
| 209 |
+
def InitFromPackedBuf(cls, buf, pos=0):
|
| 210 |
+
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos)
|
| 211 |
+
return cls.InitFromBuf(buf, pos+n)
|
| 212 |
+
|
| 213 |
+
@classmethod
|
| 214 |
+
def InitFromObj(cls, sparsityBlockSize):
|
| 215 |
+
x = SparsityBlockSizeT()
|
| 216 |
+
x._UnPack(sparsityBlockSize)
|
| 217 |
+
return x
|
| 218 |
+
|
| 219 |
+
# SparsityBlockSizeT
|
| 220 |
+
def _UnPack(self, sparsityBlockSize):
|
| 221 |
+
if sparsityBlockSize is None:
|
| 222 |
+
return
|
| 223 |
+
if not sparsityBlockSize.ValuesIsNone():
|
| 224 |
+
if np is None:
|
| 225 |
+
self.values = []
|
| 226 |
+
for i in range(sparsityBlockSize.ValuesLength()):
|
| 227 |
+
self.values.append(sparsityBlockSize.Values(i))
|
| 228 |
+
else:
|
| 229 |
+
self.values = sparsityBlockSize.ValuesAsNumpy()
|
| 230 |
+
|
| 231 |
+
# SparsityBlockSizeT
|
| 232 |
+
def Pack(self, builder):
|
| 233 |
+
if self.values is not None:
|
| 234 |
+
if np is not None and type(self.values) is np.ndarray:
|
| 235 |
+
values = builder.CreateNumpyVector(self.values)
|
| 236 |
+
else:
|
| 237 |
+
SparsityBlockSizeStartValuesVector(builder, len(self.values))
|
| 238 |
+
for i in reversed(range(len(self.values))):
|
| 239 |
+
builder.PrependUint32(self.values[i])
|
| 240 |
+
values = builder.EndVector()
|
| 241 |
+
SparsityBlockSizeStart(builder)
|
| 242 |
+
if self.values is not None:
|
| 243 |
+
SparsityBlockSizeAddValues(builder, values)
|
| 244 |
+
sparsityBlockSize = SparsityBlockSizeEnd(builder)
|
| 245 |
+
return sparsityBlockSize
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
class ConversionOptions(object):
|
| 249 |
+
__slots__ = ['_tab']
|
| 250 |
+
|
| 251 |
+
@classmethod
|
| 252 |
+
def GetRootAs(cls, buf, offset=0):
|
| 253 |
+
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
|
| 254 |
+
x = ConversionOptions()
|
| 255 |
+
x.Init(buf, n + offset)
|
| 256 |
+
return x
|
| 257 |
+
|
| 258 |
+
@classmethod
|
| 259 |
+
def GetRootAsConversionOptions(cls, buf, offset=0):
|
| 260 |
+
"""This method is deprecated. Please switch to GetRootAs."""
|
| 261 |
+
return cls.GetRootAs(buf, offset)
|
| 262 |
+
# ConversionOptions
|
| 263 |
+
def Init(self, buf, pos):
|
| 264 |
+
self._tab = flatbuffers.table.Table(buf, pos)
|
| 265 |
+
|
| 266 |
+
# ConversionOptions
|
| 267 |
+
def ModelOptimizationModes(self, j):
|
| 268 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
|
| 269 |
+
if o != 0:
|
| 270 |
+
a = self._tab.Vector(o)
|
| 271 |
+
return self._tab.Get(flatbuffers.number_types.Int32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4))
|
| 272 |
+
return 0
|
| 273 |
+
|
| 274 |
+
# ConversionOptions
|
| 275 |
+
def ModelOptimizationModesAsNumpy(self):
|
| 276 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
|
| 277 |
+
if o != 0:
|
| 278 |
+
return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int32Flags, o)
|
| 279 |
+
return 0
|
| 280 |
+
|
| 281 |
+
# ConversionOptions
|
| 282 |
+
def ModelOptimizationModesLength(self):
|
| 283 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
|
| 284 |
+
if o != 0:
|
| 285 |
+
return self._tab.VectorLen(o)
|
| 286 |
+
return 0
|
| 287 |
+
|
| 288 |
+
# ConversionOptions
|
| 289 |
+
def ModelOptimizationModesIsNone(self):
|
| 290 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
|
| 291 |
+
return o == 0
|
| 292 |
+
|
| 293 |
+
# ConversionOptions
|
| 294 |
+
def AllowCustomOps(self):
|
| 295 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
|
| 296 |
+
if o != 0:
|
| 297 |
+
return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos))
|
| 298 |
+
return False
|
| 299 |
+
|
| 300 |
+
# ConversionOptions
|
| 301 |
+
def EnableSelectTfOps(self):
|
| 302 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8))
|
| 303 |
+
if o != 0:
|
| 304 |
+
return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos))
|
| 305 |
+
return False
|
| 306 |
+
|
| 307 |
+
# ConversionOptions
|
| 308 |
+
def ForceSelectTfOps(self):
|
| 309 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10))
|
| 310 |
+
if o != 0:
|
| 311 |
+
return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos))
|
| 312 |
+
return False
|
| 313 |
+
|
| 314 |
+
# ConversionOptions
|
| 315 |
+
def SparsityBlockSizes(self, j):
|
| 316 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
|
| 317 |
+
if o != 0:
|
| 318 |
+
x = self._tab.Vector(o)
|
| 319 |
+
x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
|
| 320 |
+
x = self._tab.Indirect(x)
|
| 321 |
+
obj = SparsityBlockSize()
|
| 322 |
+
obj.Init(self._tab.Bytes, x)
|
| 323 |
+
return obj
|
| 324 |
+
return None
|
| 325 |
+
|
| 326 |
+
# ConversionOptions
|
| 327 |
+
def SparsityBlockSizesLength(self):
|
| 328 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
|
| 329 |
+
if o != 0:
|
| 330 |
+
return self._tab.VectorLen(o)
|
| 331 |
+
return 0
|
| 332 |
+
|
| 333 |
+
# ConversionOptions
|
| 334 |
+
def SparsityBlockSizesIsNone(self):
|
| 335 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
|
| 336 |
+
return o == 0
|
| 337 |
+
|
| 338 |
+
def ConversionOptionsStart(builder):
|
| 339 |
+
builder.StartObject(5)
|
| 340 |
+
|
| 341 |
+
def ConversionOptionsAddModelOptimizationModes(builder, modelOptimizationModes):
|
| 342 |
+
builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(modelOptimizationModes), 0)
|
| 343 |
+
|
| 344 |
+
def ConversionOptionsStartModelOptimizationModesVector(builder, numElems):
|
| 345 |
+
return builder.StartVector(4, numElems, 4)
|
| 346 |
+
|
| 347 |
+
def ConversionOptionsAddAllowCustomOps(builder, allowCustomOps):
|
| 348 |
+
builder.PrependBoolSlot(1, allowCustomOps, 0)
|
| 349 |
+
|
| 350 |
+
def ConversionOptionsAddEnableSelectTfOps(builder, enableSelectTfOps):
|
| 351 |
+
builder.PrependBoolSlot(2, enableSelectTfOps, 0)
|
| 352 |
+
|
| 353 |
+
def ConversionOptionsAddForceSelectTfOps(builder, forceSelectTfOps):
|
| 354 |
+
builder.PrependBoolSlot(3, forceSelectTfOps, 0)
|
| 355 |
+
|
| 356 |
+
def ConversionOptionsAddSparsityBlockSizes(builder, sparsityBlockSizes):
|
| 357 |
+
builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(sparsityBlockSizes), 0)
|
| 358 |
+
|
| 359 |
+
def ConversionOptionsStartSparsityBlockSizesVector(builder, numElems):
|
| 360 |
+
return builder.StartVector(4, numElems, 4)
|
| 361 |
+
|
| 362 |
+
def ConversionOptionsEnd(builder):
|
| 363 |
+
return builder.EndObject()
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
try:
|
| 367 |
+
from typing import List
|
| 368 |
+
except:
|
| 369 |
+
pass
|
| 370 |
+
|
| 371 |
+
class ConversionOptionsT(object):
|
| 372 |
+
|
| 373 |
+
# ConversionOptionsT
|
| 374 |
+
def __init__(self):
|
| 375 |
+
self.modelOptimizationModes = None # type: List[int]
|
| 376 |
+
self.allowCustomOps = False # type: bool
|
| 377 |
+
self.enableSelectTfOps = False # type: bool
|
| 378 |
+
self.forceSelectTfOps = False # type: bool
|
| 379 |
+
self.sparsityBlockSizes = None # type: List[SparsityBlockSizeT]
|
| 380 |
+
|
| 381 |
+
@classmethod
|
| 382 |
+
def InitFromBuf(cls, buf, pos):
|
| 383 |
+
conversionOptions = ConversionOptions()
|
| 384 |
+
conversionOptions.Init(buf, pos)
|
| 385 |
+
return cls.InitFromObj(conversionOptions)
|
| 386 |
+
|
| 387 |
+
@classmethod
|
| 388 |
+
def InitFromPackedBuf(cls, buf, pos=0):
|
| 389 |
+
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos)
|
| 390 |
+
return cls.InitFromBuf(buf, pos+n)
|
| 391 |
+
|
| 392 |
+
@classmethod
|
| 393 |
+
def InitFromObj(cls, conversionOptions):
|
| 394 |
+
x = ConversionOptionsT()
|
| 395 |
+
x._UnPack(conversionOptions)
|
| 396 |
+
return x
|
| 397 |
+
|
| 398 |
+
# ConversionOptionsT
|
| 399 |
+
def _UnPack(self, conversionOptions):
|
| 400 |
+
if conversionOptions is None:
|
| 401 |
+
return
|
| 402 |
+
if not conversionOptions.ModelOptimizationModesIsNone():
|
| 403 |
+
if np is None:
|
| 404 |
+
self.modelOptimizationModes = []
|
| 405 |
+
for i in range(conversionOptions.ModelOptimizationModesLength()):
|
| 406 |
+
self.modelOptimizationModes.append(conversionOptions.ModelOptimizationModes(i))
|
| 407 |
+
else:
|
| 408 |
+
self.modelOptimizationModes = conversionOptions.ModelOptimizationModesAsNumpy()
|
| 409 |
+
self.allowCustomOps = conversionOptions.AllowCustomOps()
|
| 410 |
+
self.enableSelectTfOps = conversionOptions.EnableSelectTfOps()
|
| 411 |
+
self.forceSelectTfOps = conversionOptions.ForceSelectTfOps()
|
| 412 |
+
if not conversionOptions.SparsityBlockSizesIsNone():
|
| 413 |
+
self.sparsityBlockSizes = []
|
| 414 |
+
for i in range(conversionOptions.SparsityBlockSizesLength()):
|
| 415 |
+
if conversionOptions.SparsityBlockSizes(i) is None:
|
| 416 |
+
self.sparsityBlockSizes.append(None)
|
| 417 |
+
else:
|
| 418 |
+
sparsityBlockSize_ = SparsityBlockSizeT.InitFromObj(conversionOptions.SparsityBlockSizes(i))
|
| 419 |
+
self.sparsityBlockSizes.append(sparsityBlockSize_)
|
| 420 |
+
|
| 421 |
+
# ConversionOptionsT
|
| 422 |
+
def Pack(self, builder):
|
| 423 |
+
if self.modelOptimizationModes is not None:
|
| 424 |
+
if np is not None and type(self.modelOptimizationModes) is np.ndarray:
|
| 425 |
+
modelOptimizationModes = builder.CreateNumpyVector(self.modelOptimizationModes)
|
| 426 |
+
else:
|
| 427 |
+
ConversionOptionsStartModelOptimizationModesVector(builder, len(self.modelOptimizationModes))
|
| 428 |
+
for i in reversed(range(len(self.modelOptimizationModes))):
|
| 429 |
+
builder.PrependInt32(self.modelOptimizationModes[i])
|
| 430 |
+
modelOptimizationModes = builder.EndVector()
|
| 431 |
+
if self.sparsityBlockSizes is not None:
|
| 432 |
+
sparsityBlockSizeslist = []
|
| 433 |
+
for i in range(len(self.sparsityBlockSizes)):
|
| 434 |
+
sparsityBlockSizeslist.append(self.sparsityBlockSizes[i].Pack(builder))
|
| 435 |
+
ConversionOptionsStartSparsityBlockSizesVector(builder, len(self.sparsityBlockSizes))
|
| 436 |
+
for i in reversed(range(len(self.sparsityBlockSizes))):
|
| 437 |
+
builder.PrependUOffsetTRelative(sparsityBlockSizeslist[i])
|
| 438 |
+
sparsityBlockSizes = builder.EndVector()
|
| 439 |
+
ConversionOptionsStart(builder)
|
| 440 |
+
if self.modelOptimizationModes is not None:
|
| 441 |
+
ConversionOptionsAddModelOptimizationModes(builder, modelOptimizationModes)
|
| 442 |
+
ConversionOptionsAddAllowCustomOps(builder, self.allowCustomOps)
|
| 443 |
+
ConversionOptionsAddEnableSelectTfOps(builder, self.enableSelectTfOps)
|
| 444 |
+
ConversionOptionsAddForceSelectTfOps(builder, self.forceSelectTfOps)
|
| 445 |
+
if self.sparsityBlockSizes is not None:
|
| 446 |
+
ConversionOptionsAddSparsityBlockSizes(builder, sparsityBlockSizes)
|
| 447 |
+
conversionOptions = ConversionOptionsEnd(builder)
|
| 448 |
+
return conversionOptions
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
class ConversionMetadata(object):
|
| 452 |
+
__slots__ = ['_tab']
|
| 453 |
+
|
| 454 |
+
@classmethod
|
| 455 |
+
def GetRootAs(cls, buf, offset=0):
|
| 456 |
+
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
|
| 457 |
+
x = ConversionMetadata()
|
| 458 |
+
x.Init(buf, n + offset)
|
| 459 |
+
return x
|
| 460 |
+
|
| 461 |
+
@classmethod
|
| 462 |
+
def GetRootAsConversionMetadata(cls, buf, offset=0):
|
| 463 |
+
"""This method is deprecated. Please switch to GetRootAs."""
|
| 464 |
+
return cls.GetRootAs(buf, offset)
|
| 465 |
+
# ConversionMetadata
|
| 466 |
+
def Init(self, buf, pos):
|
| 467 |
+
self._tab = flatbuffers.table.Table(buf, pos)
|
| 468 |
+
|
| 469 |
+
# ConversionMetadata
|
| 470 |
+
def Environment(self):
|
| 471 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
|
| 472 |
+
if o != 0:
|
| 473 |
+
x = self._tab.Indirect(o + self._tab.Pos)
|
| 474 |
+
obj = Environment()
|
| 475 |
+
obj.Init(self._tab.Bytes, x)
|
| 476 |
+
return obj
|
| 477 |
+
return None
|
| 478 |
+
|
| 479 |
+
# ConversionMetadata
|
| 480 |
+
def Options(self):
|
| 481 |
+
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
|
| 482 |
+
if o != 0:
|
| 483 |
+
x = self._tab.Indirect(o + self._tab.Pos)
|
| 484 |
+
obj = ConversionOptions()
|
| 485 |
+
obj.Init(self._tab.Bytes, x)
|
| 486 |
+
return obj
|
| 487 |
+
return None
|
| 488 |
+
|
| 489 |
+
def ConversionMetadataStart(builder):
|
| 490 |
+
builder.StartObject(2)
|
| 491 |
+
|
| 492 |
+
def ConversionMetadataAddEnvironment(builder, environment):
|
| 493 |
+
builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(environment), 0)
|
| 494 |
+
|
| 495 |
+
def ConversionMetadataAddOptions(builder, options):
|
| 496 |
+
builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(options), 0)
|
| 497 |
+
|
| 498 |
+
def ConversionMetadataEnd(builder):
|
| 499 |
+
return builder.EndObject()
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
try:
|
| 503 |
+
from typing import Optional
|
| 504 |
+
except:
|
| 505 |
+
pass
|
| 506 |
+
|
| 507 |
+
class ConversionMetadataT(object):
|
| 508 |
+
|
| 509 |
+
# ConversionMetadataT
|
| 510 |
+
def __init__(self):
|
| 511 |
+
self.environment = None # type: Optional[EnvironmentT]
|
| 512 |
+
self.options = None # type: Optional[ConversionOptionsT]
|
| 513 |
+
|
| 514 |
+
@classmethod
|
| 515 |
+
def InitFromBuf(cls, buf, pos):
|
| 516 |
+
conversionMetadata = ConversionMetadata()
|
| 517 |
+
conversionMetadata.Init(buf, pos)
|
| 518 |
+
return cls.InitFromObj(conversionMetadata)
|
| 519 |
+
|
| 520 |
+
@classmethod
|
| 521 |
+
def InitFromPackedBuf(cls, buf, pos=0):
|
| 522 |
+
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos)
|
| 523 |
+
return cls.InitFromBuf(buf, pos+n)
|
| 524 |
+
|
| 525 |
+
@classmethod
|
| 526 |
+
def InitFromObj(cls, conversionMetadata):
|
| 527 |
+
x = ConversionMetadataT()
|
| 528 |
+
x._UnPack(conversionMetadata)
|
| 529 |
+
return x
|
| 530 |
+
|
| 531 |
+
# ConversionMetadataT
|
| 532 |
+
def _UnPack(self, conversionMetadata):
|
| 533 |
+
if conversionMetadata is None:
|
| 534 |
+
return
|
| 535 |
+
if conversionMetadata.Environment() is not None:
|
| 536 |
+
self.environment = EnvironmentT.InitFromObj(conversionMetadata.Environment())
|
| 537 |
+
if conversionMetadata.Options() is not None:
|
| 538 |
+
self.options = ConversionOptionsT.InitFromObj(conversionMetadata.Options())
|
| 539 |
+
|
| 540 |
+
# ConversionMetadataT
|
| 541 |
+
def Pack(self, builder):
|
| 542 |
+
if self.environment is not None:
|
| 543 |
+
environment = self.environment.Pack(builder)
|
| 544 |
+
if self.options is not None:
|
| 545 |
+
options = self.options.Pack(builder)
|
| 546 |
+
ConversionMetadataStart(builder)
|
| 547 |
+
if self.environment is not None:
|
| 548 |
+
ConversionMetadataAddEnvironment(builder, environment)
|
| 549 |
+
if self.options is not None:
|
| 550 |
+
ConversionMetadataAddOptions(builder, options)
|
| 551 |
+
conversionMetadata = ConversionMetadataEnd(builder)
|
| 552 |
+
return conversionMetadata
|
| 553 |
+
|
| 554 |
+
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/convert.py
ADDED
|
@@ -0,0 +1,1206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 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 |
+
"""Converts a frozen graph into a TFLite FlatBuffer."""
|
| 16 |
+
|
| 17 |
+
import distutils.spawn
|
| 18 |
+
import enum
|
| 19 |
+
import hashlib
|
| 20 |
+
import os as _os
|
| 21 |
+
import platform as _platform
|
| 22 |
+
import subprocess as _subprocess
|
| 23 |
+
import tempfile as _tempfile
|
| 24 |
+
from typing import Optional
|
| 25 |
+
import warnings
|
| 26 |
+
|
| 27 |
+
from tensorflow.compiler.mlir.quantization.stablehlo import quantization_options_pb2 as quant_opts_pb2
|
| 28 |
+
from tensorflow.lite.python import lite_constants
|
| 29 |
+
from tensorflow.lite.python import util
|
| 30 |
+
from tensorflow.lite.python import wrap_toco
|
| 31 |
+
from tensorflow.lite.python.convert_phase import Component
|
| 32 |
+
from tensorflow.lite.python.convert_phase import convert_phase
|
| 33 |
+
from tensorflow.lite.python.convert_phase import ConverterError
|
| 34 |
+
from tensorflow.lite.python.convert_phase import SubComponent
|
| 35 |
+
from tensorflow.lite.python.metrics import converter_error_data_pb2
|
| 36 |
+
from tensorflow.lite.python.metrics.wrapper import metrics_wrapper as _metrics_wrapper
|
| 37 |
+
from tensorflow.lite.toco import model_flags_pb2 as _model_flags_pb2
|
| 38 |
+
from tensorflow.lite.toco import toco_flags_pb2 as _conversion_flags_pb2
|
| 39 |
+
from tensorflow.lite.toco import types_pb2 as _types_pb2
|
| 40 |
+
from tensorflow.lite.tools import flatbuffer_utils
|
| 41 |
+
from tensorflow.python.framework import dtypes
|
| 42 |
+
from tensorflow.python.framework import tensor_shape
|
| 43 |
+
from tensorflow.python.platform import resource_loader as _resource_loader
|
| 44 |
+
from tensorflow.python.util import deprecation
|
| 45 |
+
from tensorflow.python.util.tf_export import tf_export as _tf_export
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _is_quantized_input_stats_required(
|
| 49 |
+
conversion_flags: _conversion_flags_pb2.TocoFlags,
|
| 50 |
+
) -> bool:
|
| 51 |
+
"""Checks if the `quantized_input_stats` flag is required for conversion.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
conversion_flags: A protocol buffer describing the conversion process.
|
| 55 |
+
|
| 56 |
+
Returns:
|
| 57 |
+
True, if the `inference_type` or the `inference_input_type` is a quantized
|
| 58 |
+
type and it is not post training quantization, else False.
|
| 59 |
+
"""
|
| 60 |
+
quantized_inference_types = [
|
| 61 |
+
_types_pb2.QUANTIZED_UINT8,
|
| 62 |
+
_types_pb2.QUANTIZED_INT8,
|
| 63 |
+
]
|
| 64 |
+
return (
|
| 65 |
+
conversion_flags.inference_type in quantized_inference_types
|
| 66 |
+
or conversion_flags.inference_input_type in quantized_inference_types
|
| 67 |
+
) and not conversion_flags.post_training_quantize
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def convert_tensor_tf_type_to_tflite_type(
|
| 71 |
+
tf_type: dtypes.DType, usage: str = ""
|
| 72 |
+
) -> _types_pb2.IODataType:
|
| 73 |
+
"""Convert tensor type from tf type to tflite type.
|
| 74 |
+
|
| 75 |
+
Args:
|
| 76 |
+
tf_type: TensorFlow type.
|
| 77 |
+
usage: Text describing the reason for invoking this function.
|
| 78 |
+
|
| 79 |
+
Raises:
|
| 80 |
+
ValueError: If `tf_type` is unsupported.
|
| 81 |
+
|
| 82 |
+
Returns:
|
| 83 |
+
tflite_type: TFLite type. Refer to lite/toco/types.proto.
|
| 84 |
+
"""
|
| 85 |
+
mapping = {
|
| 86 |
+
dtypes.float16: _types_pb2.FLOAT16,
|
| 87 |
+
dtypes.float32: _types_pb2.FLOAT,
|
| 88 |
+
dtypes.float64: _types_pb2.FLOAT64,
|
| 89 |
+
dtypes.int8: _types_pb2.INT8,
|
| 90 |
+
dtypes.int16: _types_pb2.INT16,
|
| 91 |
+
dtypes.uint16: _types_pb2.UINT16,
|
| 92 |
+
dtypes.int32: _types_pb2.INT32,
|
| 93 |
+
dtypes.int64: _types_pb2.INT64,
|
| 94 |
+
dtypes.uint8: _types_pb2.UINT8,
|
| 95 |
+
dtypes.uint32: _types_pb2.UINT32,
|
| 96 |
+
dtypes.uint64: _types_pb2.UINT64,
|
| 97 |
+
dtypes.string: _types_pb2.STRING,
|
| 98 |
+
dtypes.bool: _types_pb2.BOOL,
|
| 99 |
+
dtypes.complex64: _types_pb2.COMPLEX64,
|
| 100 |
+
dtypes.complex128: _types_pb2.COMPLEX128,
|
| 101 |
+
}
|
| 102 |
+
tflite_type = mapping.get(tf_type)
|
| 103 |
+
if tflite_type is None:
|
| 104 |
+
raise ValueError(
|
| 105 |
+
"Unsupported TensorFlow type `{0}` provided for the {1}".format(
|
| 106 |
+
tf_type, usage
|
| 107 |
+
)
|
| 108 |
+
)
|
| 109 |
+
return tflite_type
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# Only a few restricted tensor types are allowed for explicitly setting
|
| 113 |
+
# inference/input/output types.
|
| 114 |
+
def convert_inference_tf_type_to_tflite_type(
|
| 115 |
+
tf_type: dtypes.DType, usage: str = ""
|
| 116 |
+
) -> _types_pb2.IODataType:
|
| 117 |
+
"""Convert inference type from tf type to tflite type.
|
| 118 |
+
|
| 119 |
+
Args:
|
| 120 |
+
tf_type: TensorFlow type.
|
| 121 |
+
usage: Text describing the reason for invoking this function.
|
| 122 |
+
|
| 123 |
+
Raises:
|
| 124 |
+
ValueError: If `tf_type` is unsupported.
|
| 125 |
+
|
| 126 |
+
Returns:
|
| 127 |
+
tflite_type: TFLite type. Refer to lite/toco/types.proto.
|
| 128 |
+
"""
|
| 129 |
+
mapping = {
|
| 130 |
+
dtypes.float32: _types_pb2.FLOAT,
|
| 131 |
+
dtypes.uint8: _types_pb2.QUANTIZED_UINT8,
|
| 132 |
+
dtypes.int8: _types_pb2.QUANTIZED_INT8,
|
| 133 |
+
dtypes.int16: _types_pb2.QUANTIZED_INT16,
|
| 134 |
+
}
|
| 135 |
+
tflite_type = mapping.get(tf_type)
|
| 136 |
+
if tflite_type is None:
|
| 137 |
+
raise ValueError(
|
| 138 |
+
"Unsupported TensorFlow type `{0}` provided for the {1}".format(
|
| 139 |
+
tf_type, usage
|
| 140 |
+
)
|
| 141 |
+
)
|
| 142 |
+
return tflite_type
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
# Find the deprecated conversion binary using the resource loader if using from
|
| 146 |
+
# bazel, otherwise we are in a pip where console_scripts already has the tool.
|
| 147 |
+
if lite_constants.EXPERIMENTAL_USE_TOCO_API_DIRECTLY:
|
| 148 |
+
_deprecated_conversion_binary = ""
|
| 149 |
+
else:
|
| 150 |
+
_deprecated_conversion_binary = _resource_loader.get_path_to_datafile(
|
| 151 |
+
"../toco/python/toco_from_protos"
|
| 152 |
+
)
|
| 153 |
+
if not _os.path.exists(_deprecated_conversion_binary):
|
| 154 |
+
_deprecated_conversion_binary = "toco_from_protos"
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _try_convert_to_unicode(output):
|
| 158 |
+
if output is None:
|
| 159 |
+
return ""
|
| 160 |
+
|
| 161 |
+
if isinstance(output, bytes):
|
| 162 |
+
try:
|
| 163 |
+
return output.decode("utf-8")
|
| 164 |
+
except UnicodeDecodeError:
|
| 165 |
+
pass
|
| 166 |
+
return output
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
@_tf_export("lite.OpsSet")
|
| 170 |
+
class OpsSet(enum.Enum):
|
| 171 |
+
"""Enum class defining the sets of ops available to generate TFLite models.
|
| 172 |
+
|
| 173 |
+
WARNING: Experimental interface, subject to change.
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
# Convert model using TensorFlow Lite builtin ops.
|
| 177 |
+
TFLITE_BUILTINS = "TFLITE_BUILTINS"
|
| 178 |
+
|
| 179 |
+
# Convert model using TensorFlow ops. Not all TensorFlow ops are available.
|
| 180 |
+
# WARNING: Experimental interface, subject to change.
|
| 181 |
+
SELECT_TF_OPS = "SELECT_TF_OPS"
|
| 182 |
+
|
| 183 |
+
# Convert model using only TensorFlow Lite quantized int8 operations.
|
| 184 |
+
# Specifying this will throw an error for operations that do not yet have
|
| 185 |
+
# quantized implementations.
|
| 186 |
+
TFLITE_BUILTINS_INT8 = "TFLITE_BUILTINS_INT8"
|
| 187 |
+
|
| 188 |
+
# Convert model using only TensorFlow Lite operations with quantized int8
|
| 189 |
+
# weights, int16 activations and int64 bias.
|
| 190 |
+
# Specifying this will throw an error for operations that do not yet have
|
| 191 |
+
# quantized implementations.
|
| 192 |
+
# This quantization mode may be used in models for super-resolution,
|
| 193 |
+
# audio signal processing or image de-noising. It improves accuracy
|
| 194 |
+
# significantly, but only slightly increases the model size.
|
| 195 |
+
# WARNING: These ops are currently experimental and have not yet been
|
| 196 |
+
# finalized.
|
| 197 |
+
# They are only compatible with CPU execution, and have not been optimized for
|
| 198 |
+
# production.
|
| 199 |
+
EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8 = (
|
| 200 |
+
"EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8"
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
# Convert model using only stablehlo ops.
|
| 204 |
+
# This option can not be combined with other OpsSets.
|
| 205 |
+
# The feature is in early development.
|
| 206 |
+
# The code to execute StableHLO ops in the runtime is to be implemented
|
| 207 |
+
# and the serialization format is not stabilized yet.
|
| 208 |
+
EXPERIMENTAL_STABLEHLO_OPS = "EXPERIMENTAL_STABLEHLO_OPS"
|
| 209 |
+
|
| 210 |
+
def __str__(self):
|
| 211 |
+
return str(self.value)
|
| 212 |
+
|
| 213 |
+
@staticmethod
|
| 214 |
+
def get_options():
|
| 215 |
+
"""Returns a list of OpsSet options as a list of strings."""
|
| 216 |
+
return [str(option) for option in list(OpsSet)]
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
@convert_phase(Component.OPTIMIZE_TFLITE_MODEL, SubComponent.QUANTIZE)
|
| 220 |
+
def mlir_quantize(
|
| 221 |
+
input_data_str,
|
| 222 |
+
disable_per_channel=False,
|
| 223 |
+
fully_quantize=False,
|
| 224 |
+
inference_type=_types_pb2.QUANTIZED_INT8,
|
| 225 |
+
input_data_type=dtypes.float32,
|
| 226 |
+
output_data_type=dtypes.float32,
|
| 227 |
+
enable_numeric_verify=False,
|
| 228 |
+
enable_whole_model_verify=False,
|
| 229 |
+
denylisted_ops=None,
|
| 230 |
+
denylisted_nodes=None,
|
| 231 |
+
enable_variable_quantization=False,
|
| 232 |
+
):
|
| 233 |
+
"""Quantize `input_data_str` with calibration results.
|
| 234 |
+
|
| 235 |
+
Args:
|
| 236 |
+
input_data_str: Input data in serialized form (e.g. a TFLITE model with
|
| 237 |
+
calibration results).
|
| 238 |
+
disable_per_channel: Bool indicating whether to do per-channel or per-tensor
|
| 239 |
+
quantization
|
| 240 |
+
fully_quantize: Bool indicating whether to fully quantize the model. Besides
|
| 241 |
+
model body, the input/output will be quantized as well.
|
| 242 |
+
inference_type: Data type for the activations. The default value is int8.
|
| 243 |
+
input_data_type: Data type for the inputs. The default value is float32.
|
| 244 |
+
output_data_type: Data type for the outputs. The default value is float32.
|
| 245 |
+
enable_numeric_verify: Experimental. Subject to change. Bool indicating
|
| 246 |
+
whether to add NumericVerify ops into the debug mode quantized model.
|
| 247 |
+
enable_whole_model_verify: Experimental. Subject to change. Bool indicating
|
| 248 |
+
whether to add verification for layer by layer, or on whole model. When
|
| 249 |
+
disabled (per-layer) float and quantized ops will be run from same input
|
| 250 |
+
(output of previous quantized layer). When enabled, float and quantized
|
| 251 |
+
ops will run with respective float and quantized output of previous ops.
|
| 252 |
+
denylisted_ops: Experimental. Subject to change. Set of ops to denylist.
|
| 253 |
+
denylisted_nodes: Experimental. Subject to change. Set of notes to denylist.
|
| 254 |
+
enable_variable_quantization: Experimental. Subject to change. Bool
|
| 255 |
+
indicating whether to enable quantization of the residual variables
|
| 256 |
+
remaining after the variable freezing pass.
|
| 257 |
+
|
| 258 |
+
Returns:
|
| 259 |
+
Quantized model in serialized form (e.g. a TFLITE model) with floating-point
|
| 260 |
+
inputs and outputs.
|
| 261 |
+
"""
|
| 262 |
+
return wrap_toco.wrapped_experimental_mlir_quantize(
|
| 263 |
+
input_data_str,
|
| 264 |
+
disable_per_channel,
|
| 265 |
+
fully_quantize,
|
| 266 |
+
inference_type,
|
| 267 |
+
convert_tensor_tf_type_to_tflite_type(input_data_type),
|
| 268 |
+
convert_tensor_tf_type_to_tflite_type(output_data_type),
|
| 269 |
+
enable_numeric_verify,
|
| 270 |
+
enable_whole_model_verify,
|
| 271 |
+
denylisted_ops,
|
| 272 |
+
denylisted_nodes,
|
| 273 |
+
enable_variable_quantization,
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
@convert_phase(Component.OPTIMIZE_TFLITE_MODEL, SubComponent.SPARSIFY)
|
| 278 |
+
def mlir_sparsify(input_data_str):
|
| 279 |
+
"""Sparsify `input_data_str` to encode sparse tensor with proper format.
|
| 280 |
+
|
| 281 |
+
Args:
|
| 282 |
+
input_data_str: Input data in serialized form (e.g. a TFLITE model).
|
| 283 |
+
|
| 284 |
+
Returns:
|
| 285 |
+
Sparsified model in serialized form (e.g. a TFLITE model).
|
| 286 |
+
"""
|
| 287 |
+
return wrap_toco.wrapped_experimental_mlir_sparsify(input_data_str)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def register_custom_opdefs(custom_opdefs_list):
|
| 291 |
+
"""Register the given custom opdefs to the TensorFlow global op registry.
|
| 292 |
+
|
| 293 |
+
Args:
|
| 294 |
+
custom_opdefs_list: String representing the custom ops OpDefs that are
|
| 295 |
+
included in the GraphDef.
|
| 296 |
+
|
| 297 |
+
Returns:
|
| 298 |
+
True if the registration is successfully completed.
|
| 299 |
+
"""
|
| 300 |
+
return wrap_toco.wrapped_register_custom_opdefs(custom_opdefs_list)
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def convert(
|
| 304 |
+
model_flags: _model_flags_pb2.ModelFlags,
|
| 305 |
+
conversion_flags: _conversion_flags_pb2.TocoFlags,
|
| 306 |
+
input_data_str: Optional[str] = None,
|
| 307 |
+
debug_info_str: Optional[str] = None,
|
| 308 |
+
enable_mlir_converter: bool = True,
|
| 309 |
+
):
|
| 310 |
+
"""Converts `input_data_str` to a TFLite model.
|
| 311 |
+
|
| 312 |
+
Args:
|
| 313 |
+
model_flags: Proto describing model properties, see `model_flags.proto`.
|
| 314 |
+
conversion_flags: Proto describing conversion properties, see
|
| 315 |
+
`toco/toco_flags.proto`.
|
| 316 |
+
input_data_str: Input data in serialized form (e.g. a graphdef is common, or
|
| 317 |
+
it can be hlo text or proto)
|
| 318 |
+
debug_info_str: Serialized `GraphDebugInfo` proto describing logging
|
| 319 |
+
information.
|
| 320 |
+
enable_mlir_converter: Enables MLIR-based conversion.
|
| 321 |
+
|
| 322 |
+
Returns:
|
| 323 |
+
Converted model in serialized form (e.g. a TFLITE model is common).
|
| 324 |
+
Raises:
|
| 325 |
+
ConverterError: When conversion fails in TFLiteConverter, usually due to
|
| 326 |
+
ops not being supported.
|
| 327 |
+
RuntimeError: When conversion fails, an exception is raised with the error
|
| 328 |
+
message embedded.
|
| 329 |
+
"""
|
| 330 |
+
# Historically, deprecated conversion failures would trigger a crash, so we
|
| 331 |
+
# attempt to run the converter out-of-process. The current MLIR conversion
|
| 332 |
+
# pipeline surfaces errors instead, and can be safely run in-process.
|
| 333 |
+
if enable_mlir_converter or not _deprecated_conversion_binary:
|
| 334 |
+
try:
|
| 335 |
+
return wrap_toco.wrapped_toco_convert(
|
| 336 |
+
model_flags.SerializeToString(),
|
| 337 |
+
conversion_flags.SerializeToString(),
|
| 338 |
+
input_data_str,
|
| 339 |
+
debug_info_str,
|
| 340 |
+
enable_mlir_converter,
|
| 341 |
+
)
|
| 342 |
+
except Exception as e:
|
| 343 |
+
converter_error = ConverterError(str(e))
|
| 344 |
+
|
| 345 |
+
for error_data in _metrics_wrapper.retrieve_collected_errors():
|
| 346 |
+
converter_error.append_error(error_data)
|
| 347 |
+
# Seldom we encounter the case where an unsupported
|
| 348 |
+
# `StatefulPartitionedCallOp` is not inlined and remains in the final
|
| 349 |
+
# IR. If this occurs we can set `guarantee_all_funcs_one_use` and retry.
|
| 350 |
+
# This makes the converter copy functions definitions called by
|
| 351 |
+
# multiple StatefulPartitionedCall, thus allowing them to be properly
|
| 352 |
+
# inlined.
|
| 353 |
+
if (
|
| 354 |
+
error_data.error_code
|
| 355 |
+
== converter_error_data_pb2.ConverterErrorData.ERROR_STATEFUL_PARTITIONED_CALL_IN_FINAL_IR
|
| 356 |
+
and not conversion_flags.guarantee_all_funcs_one_use
|
| 357 |
+
):
|
| 358 |
+
conversion_flags.guarantee_all_funcs_one_use = True
|
| 359 |
+
return convert(
|
| 360 |
+
model_flags,
|
| 361 |
+
conversion_flags,
|
| 362 |
+
input_data_str,
|
| 363 |
+
debug_info_str,
|
| 364 |
+
enable_mlir_converter,
|
| 365 |
+
)
|
| 366 |
+
raise converter_error
|
| 367 |
+
|
| 368 |
+
return _run_deprecated_conversion_binary(
|
| 369 |
+
model_flags.SerializeToString(),
|
| 370 |
+
conversion_flags.SerializeToString(),
|
| 371 |
+
input_data_str,
|
| 372 |
+
debug_info_str,
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
@convert_phase(
|
| 377 |
+
Component.CONVERT_TF_TO_TFLITE_MODEL,
|
| 378 |
+
SubComponent.CONVERT_GRAPHDEF_USING_DEPRECATED_CONVERTER,
|
| 379 |
+
)
|
| 380 |
+
def _run_deprecated_conversion_binary(
|
| 381 |
+
model_flags_str, conversion_flags_str, input_data_str, debug_info_str=None
|
| 382 |
+
):
|
| 383 |
+
"""Convert `input_data_str` using deprecated conversion binary.
|
| 384 |
+
|
| 385 |
+
Args:
|
| 386 |
+
model_flags_str: Serialized proto describing model properties, see
|
| 387 |
+
`model_flags.proto`.
|
| 388 |
+
conversion_flags_str: Serialized proto describing TFLite converter
|
| 389 |
+
properties, see `toco/toco_flags.proto`.
|
| 390 |
+
input_data_str: Input data in serialized form (e.g. a graphdef is common)
|
| 391 |
+
debug_info_str: Serialized `GraphDebugInfo` proto describing logging
|
| 392 |
+
information. (default None)
|
| 393 |
+
|
| 394 |
+
Returns:
|
| 395 |
+
Converted model in serialized form (e.g. a TFLITE model is common).
|
| 396 |
+
Raises:
|
| 397 |
+
ConverterError: When cannot find the deprecated conversion binary.
|
| 398 |
+
RuntimeError: When conversion fails, an exception is raised with the error
|
| 399 |
+
message embedded.
|
| 400 |
+
"""
|
| 401 |
+
if distutils.spawn.find_executable(_deprecated_conversion_binary) is None:
|
| 402 |
+
raise ConverterError("""Could not find `toco_from_protos` binary, make sure
|
| 403 |
+
your virtualenv bin directory or pip local bin directory is in your path.
|
| 404 |
+
In particular, if you have installed TensorFlow with --user, make sure you
|
| 405 |
+
add the install directory to your path.
|
| 406 |
+
|
| 407 |
+
For example:
|
| 408 |
+
Linux: export PATH=$PATH:~/.local/bin/
|
| 409 |
+
Mac: export PATH=$PATH:~/Library/Python/<version#>/bin
|
| 410 |
+
|
| 411 |
+
Alternative, use virtualenv.""")
|
| 412 |
+
# Windows and TemporaryFile are not that useful together,
|
| 413 |
+
# since you cannot have two readers/writers. So we have to
|
| 414 |
+
# make the temporaries and close and delete them explicitly.
|
| 415 |
+
conversion_filename: str = None
|
| 416 |
+
model_filename: str = None
|
| 417 |
+
input_filename: str = None
|
| 418 |
+
output_filename: str = None
|
| 419 |
+
try:
|
| 420 |
+
# Build all input files
|
| 421 |
+
with _tempfile.NamedTemporaryFile(
|
| 422 |
+
delete=False
|
| 423 |
+
) as fp_conversion, _tempfile.NamedTemporaryFile(
|
| 424 |
+
delete=False
|
| 425 |
+
) as fp_model, _tempfile.NamedTemporaryFile(
|
| 426 |
+
delete=False
|
| 427 |
+
) as fp_input, _tempfile.NamedTemporaryFile(
|
| 428 |
+
delete=False
|
| 429 |
+
) as fp_debug:
|
| 430 |
+
conversion_filename = fp_conversion.name
|
| 431 |
+
input_filename = fp_input.name
|
| 432 |
+
model_filename = fp_model.name
|
| 433 |
+
debug_filename = fp_debug.name
|
| 434 |
+
|
| 435 |
+
fp_model.write(model_flags_str)
|
| 436 |
+
fp_conversion.write(conversion_flags_str)
|
| 437 |
+
fp_input.write(input_data_str)
|
| 438 |
+
debug_info_str = debug_info_str if debug_info_str else ""
|
| 439 |
+
# if debug_info_str contains a "string value", then the call to
|
| 440 |
+
# fp_debug.write(debug_info_str) will fail with the following error
|
| 441 |
+
#
|
| 442 |
+
# TypeError: a bytes-like object is required, not 'str'
|
| 443 |
+
#
|
| 444 |
+
# Some of the subtests within the "convert_test" unit-test fail
|
| 445 |
+
# with the error shown above. So watch out for that scenario and
|
| 446 |
+
# convert debug_info_str to bytes where needed
|
| 447 |
+
if not isinstance(debug_info_str, bytes):
|
| 448 |
+
fp_debug.write(debug_info_str.encode("utf-8"))
|
| 449 |
+
else:
|
| 450 |
+
fp_debug.write(debug_info_str)
|
| 451 |
+
|
| 452 |
+
# Reserve an output file
|
| 453 |
+
with _tempfile.NamedTemporaryFile(delete=False) as fp:
|
| 454 |
+
output_filename = fp.name
|
| 455 |
+
|
| 456 |
+
# Run
|
| 457 |
+
cmd = [
|
| 458 |
+
_deprecated_conversion_binary,
|
| 459 |
+
model_filename,
|
| 460 |
+
conversion_filename,
|
| 461 |
+
input_filename,
|
| 462 |
+
output_filename,
|
| 463 |
+
"--debug_proto_file={}".format(debug_filename),
|
| 464 |
+
]
|
| 465 |
+
cmdline = " ".join(cmd)
|
| 466 |
+
is_windows = _platform.system() == "Windows"
|
| 467 |
+
proc = _subprocess.Popen(
|
| 468 |
+
cmdline,
|
| 469 |
+
shell=True,
|
| 470 |
+
stdout=_subprocess.PIPE,
|
| 471 |
+
stderr=_subprocess.STDOUT,
|
| 472 |
+
close_fds=not is_windows,
|
| 473 |
+
)
|
| 474 |
+
stdout, stderr = proc.communicate()
|
| 475 |
+
exitcode = proc.returncode
|
| 476 |
+
if exitcode == 0:
|
| 477 |
+
with open(output_filename, "rb") as fp:
|
| 478 |
+
return fp.read()
|
| 479 |
+
else:
|
| 480 |
+
stdout = _try_convert_to_unicode(stdout)
|
| 481 |
+
stderr = _try_convert_to_unicode(stderr)
|
| 482 |
+
raise ConverterError("See console for info.\n%s\n%s\n" % (stdout, stderr))
|
| 483 |
+
finally:
|
| 484 |
+
# Must manually cleanup files.
|
| 485 |
+
for filename in [
|
| 486 |
+
conversion_filename,
|
| 487 |
+
input_filename,
|
| 488 |
+
model_filename,
|
| 489 |
+
output_filename,
|
| 490 |
+
]:
|
| 491 |
+
try:
|
| 492 |
+
_os.unlink(filename)
|
| 493 |
+
except (OSError, TypeError):
|
| 494 |
+
pass
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def build_model_flags(
|
| 498 |
+
change_concat_input_ranges=False,
|
| 499 |
+
allow_nonexistent_arrays=False,
|
| 500 |
+
saved_model_dir=None,
|
| 501 |
+
saved_model_version=0,
|
| 502 |
+
saved_model_tags=None,
|
| 503 |
+
saved_model_exported_names=None,
|
| 504 |
+
**_
|
| 505 |
+
):
|
| 506 |
+
"""Builds the model flags object from params.
|
| 507 |
+
|
| 508 |
+
Args:
|
| 509 |
+
change_concat_input_ranges: Boolean to change behavior of min/max ranges for
|
| 510 |
+
inputs and outputs of the concat operator for quantized models. Changes
|
| 511 |
+
the ranges of concat operator overlap when true. (default False)
|
| 512 |
+
allow_nonexistent_arrays: Allow specifying array names that don't exist or
|
| 513 |
+
are unused in the final graph. (default False)
|
| 514 |
+
saved_model_dir: Filepath of the saved model to be converted. This value
|
| 515 |
+
will be non-empty only when the saved model import path will be used.
|
| 516 |
+
Otherwises, the graph def-based conversion will be processed.
|
| 517 |
+
saved_model_version: SavedModel file format version of The saved model file
|
| 518 |
+
to be converted. This value will be set only when the SavedModel import
|
| 519 |
+
path will be used.
|
| 520 |
+
saved_model_tags: Set of string saved model tags, formatted in the
|
| 521 |
+
comma-separated value. This value will be set only when the SavedModel
|
| 522 |
+
import path will be used.
|
| 523 |
+
saved_model_exported_names: Names to be exported (default: export all) when
|
| 524 |
+
the saved model import path is on. This value will be set only when the
|
| 525 |
+
SavedModel import path will be used.
|
| 526 |
+
|
| 527 |
+
Returns:
|
| 528 |
+
model_flags: protocol buffer describing the model.
|
| 529 |
+
"""
|
| 530 |
+
model_flags = _model_flags_pb2.ModelFlags()
|
| 531 |
+
model_flags.change_concat_input_ranges = change_concat_input_ranges
|
| 532 |
+
model_flags.allow_nonexistent_arrays = allow_nonexistent_arrays
|
| 533 |
+
if saved_model_dir:
|
| 534 |
+
model_flags.saved_model_dir = saved_model_dir
|
| 535 |
+
model_flags.saved_model_version = saved_model_version
|
| 536 |
+
if saved_model_tags:
|
| 537 |
+
model_flags.saved_model_tags.extend(saved_model_tags)
|
| 538 |
+
if saved_model_exported_names:
|
| 539 |
+
model_flags.saved_model_exported_names.extend(saved_model_exported_names)
|
| 540 |
+
return model_flags
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
def build_conversion_flags(
|
| 544 |
+
inference_type=dtypes.float32,
|
| 545 |
+
inference_input_type=None,
|
| 546 |
+
input_format=lite_constants.TENSORFLOW_GRAPHDEF,
|
| 547 |
+
output_format=lite_constants.TFLITE,
|
| 548 |
+
default_ranges_stats=None,
|
| 549 |
+
drop_control_dependency=True,
|
| 550 |
+
reorder_across_fake_quant=False,
|
| 551 |
+
allow_custom_ops=False,
|
| 552 |
+
post_training_quantize=False,
|
| 553 |
+
quantize_to_float16=False,
|
| 554 |
+
dump_graphviz_dir=None,
|
| 555 |
+
dump_graphviz_video=False,
|
| 556 |
+
target_ops=None,
|
| 557 |
+
conversion_summary_dir=None,
|
| 558 |
+
select_user_tf_ops=None,
|
| 559 |
+
allow_all_select_tf_ops=False,
|
| 560 |
+
enable_tflite_resource_variables=True,
|
| 561 |
+
unfold_batchmatmul=False,
|
| 562 |
+
legalize_custom_tensor_list_ops=False,
|
| 563 |
+
lower_tensor_list_ops=True,
|
| 564 |
+
default_to_single_batch_in_tensor_list_ops=False,
|
| 565 |
+
accumulation_type=None,
|
| 566 |
+
allow_bfloat16=False,
|
| 567 |
+
unfold_large_splat_constant=False,
|
| 568 |
+
supported_backends=None,
|
| 569 |
+
disable_per_channel_quantization=False,
|
| 570 |
+
enable_mlir_dynamic_range_quantizer=False,
|
| 571 |
+
tf_quantization_mode=None,
|
| 572 |
+
disable_infer_tensor_range=False,
|
| 573 |
+
use_fake_quant_num_bits=False,
|
| 574 |
+
enable_dynamic_update_slice=False,
|
| 575 |
+
preserve_assert_op=False,
|
| 576 |
+
guarantee_all_funcs_one_use=False,
|
| 577 |
+
enable_mlir_variable_quantization=False,
|
| 578 |
+
disable_fuse_mul_and_fc=False,
|
| 579 |
+
quantization_options: Optional[quant_opts_pb2.QuantizationOptions] = None,
|
| 580 |
+
mlir_dump_dir=None,
|
| 581 |
+
mlir_dump_pass_regex=None,
|
| 582 |
+
mlir_dump_func_regex=None,
|
| 583 |
+
mlir_enable_timing=None,
|
| 584 |
+
mlir_print_ir_before=None,
|
| 585 |
+
mlir_print_ir_after=None,
|
| 586 |
+
mlir_print_ir_module_scope=None,
|
| 587 |
+
mlir_elide_elementsattrs_if_larger=None,
|
| 588 |
+
use_buffer_offset=False,
|
| 589 |
+
reduce_type_precision=False,
|
| 590 |
+
**_
|
| 591 |
+
):
|
| 592 |
+
"""Builds protocol buffer describing a conversion of a model.
|
| 593 |
+
|
| 594 |
+
Typically this is to convert from TensorFlow GraphDef to TFLite, in which
|
| 595 |
+
case the default `input_format` and `output_format` are sufficient.
|
| 596 |
+
|
| 597 |
+
Args:
|
| 598 |
+
inference_type: Data type of numeric arrays, excluding the input layer.
|
| 599 |
+
(default tf.float32, must be in {tf.float32, tf.int8, tf.uint8})
|
| 600 |
+
inference_input_type: Data type of the numeric arrays in the input layer. If
|
| 601 |
+
`inference_input_type` is in {tf.int8, tf.uint8}, then
|
| 602 |
+
`quantized_input_stats` must be provided. (default is the value assigned
|
| 603 |
+
to `inference_type`, must be in {tf.float32, tf.int8, tf.uint8})
|
| 604 |
+
input_format: Type of data to read. (default TENSORFLOW_GRAPHDEF, must be in
|
| 605 |
+
{TENSORFLOW_GRAPHDEF})
|
| 606 |
+
output_format: Output file format. (default TFLITE, must be in {TFLITE,
|
| 607 |
+
GRAPHVIZ_DOT})
|
| 608 |
+
default_ranges_stats: Tuple of integers representing (min, max) range values
|
| 609 |
+
for all arrays without a specified range. Intended for experimenting with
|
| 610 |
+
quantization via "dummy quantization". (default None)
|
| 611 |
+
drop_control_dependency: Boolean indicating whether to drop control
|
| 612 |
+
dependencies silently. This is due to TFLite not supporting control
|
| 613 |
+
dependencies. (default True)
|
| 614 |
+
reorder_across_fake_quant: Boolean indicating whether to reorder FakeQuant
|
| 615 |
+
nodes in unexpected locations. Used when the location of the FakeQuant
|
| 616 |
+
nodes is preventing graph transformations necessary to convert the graph.
|
| 617 |
+
Results in a graph that differs from the quantized training graph,
|
| 618 |
+
potentially causing differing arithmetic behavior. (default False)
|
| 619 |
+
allow_custom_ops: Boolean indicating whether to allow custom operations.
|
| 620 |
+
When false any unknown operation is an error. When true, custom ops are
|
| 621 |
+
created for any op that is unknown. The developer will need to provide
|
| 622 |
+
these to the TensorFlow Lite runtime with a custom resolver. (default
|
| 623 |
+
False)
|
| 624 |
+
post_training_quantize: Boolean indicating whether to quantize the weights
|
| 625 |
+
of the converted float model. Model size will be reduced and there will be
|
| 626 |
+
latency improvements (at the cost of accuracy). (default False) If
|
| 627 |
+
quantization_options is set, all quantization arg will be ignored.
|
| 628 |
+
quantize_to_float16: Boolean indicating whether to convert float buffers to
|
| 629 |
+
float16. (default False)
|
| 630 |
+
dump_graphviz_dir: Full filepath of folder to dump the graphs at various
|
| 631 |
+
stages of processing GraphViz .dot files. Preferred over
|
| 632 |
+
--output_format=GRAPHVIZ_DOT in order to keep the requirements of the
|
| 633 |
+
output file. (default None)
|
| 634 |
+
dump_graphviz_video: Boolean indicating whether to dump the graph after
|
| 635 |
+
every graph transformation. (default False)
|
| 636 |
+
target_ops: Experimental flag, subject to change. Set of OpsSet options
|
| 637 |
+
indicating which converter to use. (default set([OpsSet.TFLITE_BUILTINS]))
|
| 638 |
+
conversion_summary_dir: A string, the path to the generated conversion logs.
|
| 639 |
+
select_user_tf_ops: List of user's defined TensorFlow ops need to be
|
| 640 |
+
supported in the TensorFlow Lite runtime. These ops will be supported as
|
| 641 |
+
select TensorFlow ops.
|
| 642 |
+
allow_all_select_tf_ops: If True, automatically add all TF ops (including
|
| 643 |
+
custom TF ops) to the converted model as flex ops.
|
| 644 |
+
enable_tflite_resource_variables: Experimental flag, subject to change.
|
| 645 |
+
Enables conversion of resource variables. (default False)
|
| 646 |
+
unfold_batchmatmul: Whether to unfold tf.BatchMatMul to a set of
|
| 647 |
+
tfl.fully_connected ops. If not, translate to tfl.batch_matmul.
|
| 648 |
+
legalize_custom_tensor_list_ops: Whether to legalize `tf.TensorList*` ops to
|
| 649 |
+
tfl custom if they can all be supported.
|
| 650 |
+
lower_tensor_list_ops: Whether to lower tensor list ops to builtin ops. If
|
| 651 |
+
not, use Flex tensor list ops.
|
| 652 |
+
default_to_single_batch_in_tensor_list_ops: Whether to force to use batch
|
| 653 |
+
size one when the tensor list ops has the unspecified batch size.
|
| 654 |
+
accumulation_type: Data type of the accumulators in quantized inference.
|
| 655 |
+
Typically used for float16 quantization and is either fp16 or fp32.
|
| 656 |
+
allow_bfloat16: Whether the converted model supports reduced precision
|
| 657 |
+
inference with the bfloat16 type.
|
| 658 |
+
unfold_large_splat_constant: Whether to unfold large splat constant tensors
|
| 659 |
+
in the flatbuffer model to reduce size.
|
| 660 |
+
supported_backends: List of TFLite backends which needs to check
|
| 661 |
+
compatibility.
|
| 662 |
+
disable_per_channel_quantization: Disable per-channel quantized weights for
|
| 663 |
+
dynamic range quantization. Only per-tensor quantization will be used.
|
| 664 |
+
enable_mlir_dynamic_range_quantizer: Enable MLIR dynamic range quantization.
|
| 665 |
+
If False, the old converter dynamic range quantizer is used.
|
| 666 |
+
tf_quantization_mode: Indicates the mode of TF Quantization when the output
|
| 667 |
+
model is used for TF Quantization.
|
| 668 |
+
disable_infer_tensor_range: Disable infering tensor ranges.
|
| 669 |
+
use_fake_quant_num_bits: Allow quantization parameters to be calculated from
|
| 670 |
+
num_bits attribute.
|
| 671 |
+
enable_dynamic_update_slice: Enable to convert to DynamicUpdateSlice op.
|
| 672 |
+
(default: False).
|
| 673 |
+
preserve_assert_op: Whether to preserve `TF::AssertOp` (default: False).
|
| 674 |
+
guarantee_all_funcs_one_use: Whether to clone functions so that each
|
| 675 |
+
function only has a single use. This option will be helpful if the
|
| 676 |
+
conversion fails when the `PartitionedCall` or `StatefulPartitionedCall`
|
| 677 |
+
can't be properly inlined (default: False).
|
| 678 |
+
enable_mlir_variable_quantization: Enable MLIR variable quantization. There
|
| 679 |
+
is a variable freezing pass, but some variables may not be fully frozen by
|
| 680 |
+
it. This flag enables quantization of those residual variables in the MLIR
|
| 681 |
+
graph.
|
| 682 |
+
disable_fuse_mul_and_fc: Disable fusing input multiplication with
|
| 683 |
+
fullyconnected operations. Useful when quantizing weights.
|
| 684 |
+
quantization_options: Config to indicate quantization options of each
|
| 685 |
+
components (ex: weight, bias, activation). This can be a preset method or
|
| 686 |
+
a custom method, and allows finer, modular control. This option will
|
| 687 |
+
override any other existing quantization flags. We plan on gradually
|
| 688 |
+
migrating all quantization-related specs into this option.
|
| 689 |
+
mlir_dump_dir: A string specifying the target directory to output MLIR dumps
|
| 690 |
+
produced during conversion. If populated, enables MLIR dumps.
|
| 691 |
+
mlir_dump_pass_regex: A string containing a regular expression for filtering
|
| 692 |
+
the pass names to be dumped. Effective only if `mlir_dump_dir` is
|
| 693 |
+
populated.
|
| 694 |
+
mlir_dump_func_regex: A string containing a regular expression for filtering
|
| 695 |
+
the function names to be dumped. Effective only if `mlir_dump_dir` is
|
| 696 |
+
populated.
|
| 697 |
+
mlir_enable_timing: A boolean, if set to true reports the execution time of
|
| 698 |
+
each MLIR pass.
|
| 699 |
+
mlir_print_ir_before: A string containing a regular expression. If
|
| 700 |
+
specified, prints MLIR before passes which match.
|
| 701 |
+
mlir_print_ir_after: A string containing a regular expression. If specified,
|
| 702 |
+
prints MLIR after passes which match.
|
| 703 |
+
mlir_print_ir_module_scope: A boolean, if set to true always print the
|
| 704 |
+
top-level operation when printing IR for print_ir_[before|after].
|
| 705 |
+
mlir_elide_elementsattrs_if_larger: An int, if specified elides
|
| 706 |
+
ElementsAttrs with '...' that have more elements than the given upper
|
| 707 |
+
limit.
|
| 708 |
+
use_buffer_offset: Force the model use buffer_offset & buffer_size fields
|
| 709 |
+
instead of data. i.e. store the constant tensor and custom op binaries
|
| 710 |
+
outside of Flatbuffers
|
| 711 |
+
reduce_type_precision: Convert some tensor types to a lower precision if all
|
| 712 |
+
values within that tensor are within the range of the lower precision.
|
| 713 |
+
This could have side effects e.g. reduced flatbuffer size.
|
| 714 |
+
|
| 715 |
+
Returns:
|
| 716 |
+
conversion_flags: protocol buffer describing the conversion process.
|
| 717 |
+
Raises:
|
| 718 |
+
ValueError, if the input tensor type is unknown.
|
| 719 |
+
"""
|
| 720 |
+
conversion_flags = _conversion_flags_pb2.TocoFlags()
|
| 721 |
+
conversion_flags.inference_type = convert_inference_tf_type_to_tflite_type(
|
| 722 |
+
inference_type, usage="inference_type flag"
|
| 723 |
+
)
|
| 724 |
+
if inference_input_type:
|
| 725 |
+
conversion_flags.inference_input_type = (
|
| 726 |
+
convert_inference_tf_type_to_tflite_type(
|
| 727 |
+
inference_input_type, usage="inference_input_type flag"
|
| 728 |
+
)
|
| 729 |
+
)
|
| 730 |
+
else:
|
| 731 |
+
conversion_flags.inference_input_type = conversion_flags.inference_type
|
| 732 |
+
conversion_flags.input_format = input_format
|
| 733 |
+
conversion_flags.output_format = output_format
|
| 734 |
+
if default_ranges_stats:
|
| 735 |
+
conversion_flags.default_ranges_min = default_ranges_stats[0]
|
| 736 |
+
conversion_flags.default_ranges_max = default_ranges_stats[1]
|
| 737 |
+
conversion_flags.drop_control_dependency = drop_control_dependency
|
| 738 |
+
conversion_flags.reorder_across_fake_quant = reorder_across_fake_quant
|
| 739 |
+
conversion_flags.allow_custom_ops = allow_custom_ops
|
| 740 |
+
conversion_flags.post_training_quantize = post_training_quantize
|
| 741 |
+
conversion_flags.quantize_to_float16 = quantize_to_float16
|
| 742 |
+
if dump_graphviz_dir:
|
| 743 |
+
conversion_flags.dump_graphviz_dir = dump_graphviz_dir
|
| 744 |
+
conversion_flags.dump_graphviz_include_video = dump_graphviz_video
|
| 745 |
+
if target_ops:
|
| 746 |
+
if OpsSet.SELECT_TF_OPS in target_ops:
|
| 747 |
+
conversion_flags.enable_select_tf_ops = True
|
| 748 |
+
if set(target_ops) == {OpsSet.SELECT_TF_OPS}:
|
| 749 |
+
conversion_flags.force_select_tf_ops = True
|
| 750 |
+
if OpsSet.EXPERIMENTAL_STABLEHLO_OPS in target_ops:
|
| 751 |
+
conversion_flags.convert_to_stablehlo = True
|
| 752 |
+
if OpsSet.EXPERIMENTAL_STABLEHLO_OPS in target_ops and len(target_ops) > 1:
|
| 753 |
+
raise ValueError(
|
| 754 |
+
"StableHLO Ops set can not be specified with other Ops set together"
|
| 755 |
+
)
|
| 756 |
+
if conversion_summary_dir:
|
| 757 |
+
conversion_flags.conversion_summary_dir = conversion_summary_dir
|
| 758 |
+
if select_user_tf_ops:
|
| 759 |
+
conversion_flags.select_user_tf_ops.extend(select_user_tf_ops)
|
| 760 |
+
conversion_flags.allow_all_select_tf_ops = allow_all_select_tf_ops
|
| 761 |
+
conversion_flags.enable_tflite_resource_variables = (
|
| 762 |
+
enable_tflite_resource_variables
|
| 763 |
+
)
|
| 764 |
+
conversion_flags.unfold_batchmatmul = unfold_batchmatmul
|
| 765 |
+
conversion_flags.legalize_custom_tensor_list_ops = (
|
| 766 |
+
legalize_custom_tensor_list_ops
|
| 767 |
+
)
|
| 768 |
+
conversion_flags.lower_tensor_list_ops = lower_tensor_list_ops
|
| 769 |
+
conversion_flags.default_to_single_batch_in_tensor_list_ops = (
|
| 770 |
+
default_to_single_batch_in_tensor_list_ops
|
| 771 |
+
)
|
| 772 |
+
if accumulation_type:
|
| 773 |
+
conversion_flags.accumulation_type = convert_tensor_tf_type_to_tflite_type(
|
| 774 |
+
accumulation_type, usage="accumulation_type flag"
|
| 775 |
+
)
|
| 776 |
+
conversion_flags.allow_bfloat16 = allow_bfloat16
|
| 777 |
+
conversion_flags.unfold_large_splat_constant = unfold_large_splat_constant
|
| 778 |
+
if supported_backends:
|
| 779 |
+
conversion_flags.supported_backends.extend(supported_backends)
|
| 780 |
+
conversion_flags.disable_per_channel_quantization = (
|
| 781 |
+
disable_per_channel_quantization
|
| 782 |
+
)
|
| 783 |
+
conversion_flags.enable_mlir_dynamic_range_quantizer = (
|
| 784 |
+
enable_mlir_dynamic_range_quantizer
|
| 785 |
+
)
|
| 786 |
+
conversion_flags.enable_dynamic_update_slice = enable_dynamic_update_slice
|
| 787 |
+
conversion_flags.preserve_assert_op = preserve_assert_op
|
| 788 |
+
conversion_flags.guarantee_all_funcs_one_use = guarantee_all_funcs_one_use
|
| 789 |
+
if tf_quantization_mode:
|
| 790 |
+
conversion_flags.tf_quantization_mode = tf_quantization_mode
|
| 791 |
+
conversion_flags.disable_infer_tensor_range = disable_infer_tensor_range
|
| 792 |
+
conversion_flags.use_fake_quant_num_bits = use_fake_quant_num_bits
|
| 793 |
+
conversion_flags.enable_mlir_variable_quantization = (
|
| 794 |
+
enable_mlir_variable_quantization
|
| 795 |
+
)
|
| 796 |
+
conversion_flags.disable_fuse_mul_and_fc = disable_fuse_mul_and_fc
|
| 797 |
+
if quantization_options:
|
| 798 |
+
conversion_flags.quantization_options.CopyFrom(quantization_options)
|
| 799 |
+
|
| 800 |
+
# Transfer debug options. Check for existence before populating in order to
|
| 801 |
+
# leverage defaults specified in proto definition.
|
| 802 |
+
if mlir_dump_dir is not None:
|
| 803 |
+
conversion_flags.debug_options.mlir_dump_dir = mlir_dump_dir
|
| 804 |
+
if mlir_dump_pass_regex is not None:
|
| 805 |
+
conversion_flags.debug_options.mlir_dump_pass_regex = mlir_dump_pass_regex
|
| 806 |
+
if mlir_dump_func_regex is not None:
|
| 807 |
+
conversion_flags.debug_options.mlir_dump_func_regex = mlir_dump_func_regex
|
| 808 |
+
if mlir_enable_timing is not None:
|
| 809 |
+
conversion_flags.debug_options.mlir_enable_timing = mlir_enable_timing
|
| 810 |
+
if mlir_print_ir_before is not None:
|
| 811 |
+
conversion_flags.debug_options.mlir_print_ir_before = mlir_print_ir_before
|
| 812 |
+
if mlir_print_ir_after is not None:
|
| 813 |
+
conversion_flags.debug_options.mlir_print_ir_after = mlir_print_ir_after
|
| 814 |
+
if mlir_print_ir_module_scope is not None:
|
| 815 |
+
conversion_flags.debug_options.mlir_print_ir_module_scope = (
|
| 816 |
+
mlir_print_ir_module_scope
|
| 817 |
+
)
|
| 818 |
+
if mlir_elide_elementsattrs_if_larger is not None:
|
| 819 |
+
conversion_flags.debug_options.mlir_elide_elementsattrs_if_larger = (
|
| 820 |
+
mlir_elide_elementsattrs_if_larger
|
| 821 |
+
)
|
| 822 |
+
|
| 823 |
+
if use_buffer_offset is not None:
|
| 824 |
+
conversion_flags.use_buffer_offset = use_buffer_offset
|
| 825 |
+
if reduce_type_precision is not None:
|
| 826 |
+
conversion_flags.reduce_type_precision = reduce_type_precision
|
| 827 |
+
return conversion_flags
|
| 828 |
+
|
| 829 |
+
|
| 830 |
+
@convert_phase(
|
| 831 |
+
Component.CONVERT_TF_TO_TFLITE_MODEL, SubComponent.CONVERT_GRAPHDEF
|
| 832 |
+
)
|
| 833 |
+
def convert_graphdef_with_arrays(
|
| 834 |
+
input_data,
|
| 835 |
+
input_arrays_with_shape,
|
| 836 |
+
output_arrays,
|
| 837 |
+
control_output_arrays,
|
| 838 |
+
**kwargs
|
| 839 |
+
):
|
| 840 |
+
"""Convert a frozen GraphDef that can't be loaded in TF.
|
| 841 |
+
|
| 842 |
+
Conversion can be customized by providing arguments that are forwarded to
|
| 843 |
+
`build_model_flags` and `build_conversion_flags` (see documentation).
|
| 844 |
+
|
| 845 |
+
Args:
|
| 846 |
+
input_data: Input data (i.e. often `sess.graph_def`),
|
| 847 |
+
input_arrays_with_shape: Tuple of strings representing input tensor names
|
| 848 |
+
and list of integers representing input shapes (e.g., [("foo" : [1, 16,
|
| 849 |
+
16, 3])]). Use only when graph cannot be loaded into TensorFlow and when
|
| 850 |
+
`input_tensors` is None.
|
| 851 |
+
output_arrays: List of output tensors to freeze graph with. Use only when
|
| 852 |
+
graph cannot be loaded into TensorFlow and when `output_tensors` is None.
|
| 853 |
+
control_output_arrays: Control output node names. This is used when
|
| 854 |
+
converting a Graph with no output tensors. For example, if the graph's
|
| 855 |
+
last operation is a Print op, just specify that op's name in this field.
|
| 856 |
+
This can be used together with the `output_arrays` parameter.
|
| 857 |
+
**kwargs: See `build_model_flags` and `build_conversion_flags`.
|
| 858 |
+
|
| 859 |
+
Returns:
|
| 860 |
+
The converted data. For example if TFLite was the destination, then
|
| 861 |
+
this will be a tflite flatbuffer in a bytes array.
|
| 862 |
+
|
| 863 |
+
Raises:
|
| 864 |
+
Defined in `build_conversion_flags`.
|
| 865 |
+
"""
|
| 866 |
+
model_flags = build_model_flags(**kwargs)
|
| 867 |
+
conversion_flags = build_conversion_flags(**kwargs)
|
| 868 |
+
enable_mlir_converter = kwargs.get("enable_mlir_converter", True)
|
| 869 |
+
quantized_input_stats = kwargs.get("quantized_input_stats", None)
|
| 870 |
+
|
| 871 |
+
for idx, (name, shape) in enumerate(input_arrays_with_shape):
|
| 872 |
+
input_array = model_flags.input_arrays.add()
|
| 873 |
+
if _is_quantized_input_stats_required(conversion_flags):
|
| 874 |
+
if quantized_input_stats:
|
| 875 |
+
input_array.mean_value, input_array.std_value = quantized_input_stats[
|
| 876 |
+
idx
|
| 877 |
+
]
|
| 878 |
+
else:
|
| 879 |
+
raise ValueError(
|
| 880 |
+
"The `quantized_input_stats` flag must be defined when either "
|
| 881 |
+
"`inference_type` flag or `inference_input_type` flag is set to "
|
| 882 |
+
"tf.int8 or tf.uint8."
|
| 883 |
+
)
|
| 884 |
+
input_array.name = name
|
| 885 |
+
input_array.shape.dims.extend(list(map(int, shape)))
|
| 886 |
+
|
| 887 |
+
if output_arrays:
|
| 888 |
+
for name in output_arrays:
|
| 889 |
+
model_flags.output_arrays.append(name)
|
| 890 |
+
if control_output_arrays:
|
| 891 |
+
for name in control_output_arrays:
|
| 892 |
+
model_flags.control_output_arrays.append(name)
|
| 893 |
+
|
| 894 |
+
data = convert(
|
| 895 |
+
model_flags,
|
| 896 |
+
conversion_flags,
|
| 897 |
+
input_data.SerializeToString(),
|
| 898 |
+
debug_info_str=None,
|
| 899 |
+
enable_mlir_converter=enable_mlir_converter,
|
| 900 |
+
)
|
| 901 |
+
return data
|
| 902 |
+
|
| 903 |
+
|
| 904 |
+
@convert_phase(
|
| 905 |
+
Component.CONVERT_TF_TO_TFLITE_MODEL, SubComponent.CONVERT_GRAPHDEF
|
| 906 |
+
)
|
| 907 |
+
def convert_graphdef(input_data, input_tensors, output_tensors, **kwargs):
|
| 908 |
+
"""Convert a frozen GraphDef model using the TF Lite converter.
|
| 909 |
+
|
| 910 |
+
Conversion can be customized by providing arguments that are forwarded to
|
| 911 |
+
`build_model_flags` and `build_conversion_flags` (see documentation).
|
| 912 |
+
|
| 913 |
+
Args:
|
| 914 |
+
input_data: Input data (i.e. often `sess.graph_def`),
|
| 915 |
+
input_tensors: List of input tensors. Type and shape are computed using
|
| 916 |
+
`foo.shape` and `foo.dtype`.
|
| 917 |
+
output_tensors: List of output tensors (only .name is used from this).
|
| 918 |
+
**kwargs: See `build_model_flags` and `build_conversion_flags`.
|
| 919 |
+
|
| 920 |
+
Returns:
|
| 921 |
+
The converted data. For example if TFLite was the destination, then
|
| 922 |
+
this will be a tflite flatbuffer in a bytes array.
|
| 923 |
+
|
| 924 |
+
Raises:
|
| 925 |
+
Defined in `build_conversion_flags`.
|
| 926 |
+
"""
|
| 927 |
+
model_flags = build_model_flags(**kwargs)
|
| 928 |
+
conversion_flags = build_conversion_flags(**kwargs)
|
| 929 |
+
saved_model_dir = kwargs.get("saved_model_dir", None)
|
| 930 |
+
input_shapes = kwargs.get("input_shapes", None)
|
| 931 |
+
enable_mlir_converter = kwargs.get("enable_mlir_converter", True)
|
| 932 |
+
quantized_input_stats = kwargs.get("quantized_input_stats", None)
|
| 933 |
+
debug_info = kwargs.get("debug_info", None)
|
| 934 |
+
|
| 935 |
+
for idx, input_tensor in enumerate(input_tensors):
|
| 936 |
+
input_array = model_flags.input_arrays.add()
|
| 937 |
+
if saved_model_dir:
|
| 938 |
+
input_array.name = input_tensor.name
|
| 939 |
+
else:
|
| 940 |
+
input_array.name = util.get_tensor_name(input_tensor)
|
| 941 |
+
input_array.data_type = convert_tensor_tf_type_to_tflite_type(
|
| 942 |
+
input_tensor.dtype, usage="input type of the TensorFlow model"
|
| 943 |
+
)
|
| 944 |
+
|
| 945 |
+
if _is_quantized_input_stats_required(conversion_flags):
|
| 946 |
+
if quantized_input_stats:
|
| 947 |
+
input_array.mean_value, input_array.std_value = quantized_input_stats[
|
| 948 |
+
idx
|
| 949 |
+
]
|
| 950 |
+
else:
|
| 951 |
+
# We should ideally raise an error here, but we don't as it would break
|
| 952 |
+
# several models/projects that depend on this workflow.
|
| 953 |
+
warnings.warn(
|
| 954 |
+
"Statistics for quantized inputs were expected, but not "
|
| 955 |
+
"specified; continuing anyway."
|
| 956 |
+
)
|
| 957 |
+
|
| 958 |
+
if input_shapes is None:
|
| 959 |
+
shape = input_tensor.shape
|
| 960 |
+
else:
|
| 961 |
+
shape = input_shapes[idx]
|
| 962 |
+
|
| 963 |
+
if shape.rank is not None:
|
| 964 |
+
# Create shapes with -1 for unknown dimensions.
|
| 965 |
+
dims = []
|
| 966 |
+
for dim in shape:
|
| 967 |
+
if dim is None or (
|
| 968 |
+
isinstance(dim, tensor_shape.Dimension) and dim.value is None
|
| 969 |
+
):
|
| 970 |
+
dims.append(-1)
|
| 971 |
+
else:
|
| 972 |
+
dims.append(int(dim))
|
| 973 |
+
input_array.shape.dims.extend(dims)
|
| 974 |
+
input_array.shape.unknown_rank = False
|
| 975 |
+
else:
|
| 976 |
+
input_array.shape.unknown_rank = True
|
| 977 |
+
|
| 978 |
+
for output_tensor in output_tensors:
|
| 979 |
+
if saved_model_dir:
|
| 980 |
+
model_flags.output_arrays.append(output_tensor.name)
|
| 981 |
+
else:
|
| 982 |
+
model_flags.output_arrays.append(util.get_tensor_name(output_tensor))
|
| 983 |
+
|
| 984 |
+
data = convert(
|
| 985 |
+
model_flags,
|
| 986 |
+
conversion_flags,
|
| 987 |
+
input_data.SerializeToString(),
|
| 988 |
+
debug_info_str=debug_info.SerializeToString() if debug_info else None,
|
| 989 |
+
enable_mlir_converter=enable_mlir_converter,
|
| 990 |
+
)
|
| 991 |
+
return data
|
| 992 |
+
|
| 993 |
+
|
| 994 |
+
@convert_phase(
|
| 995 |
+
Component.CONVERT_TF_TO_TFLITE_MODEL, SubComponent.CONVERT_SAVED_MODEL
|
| 996 |
+
)
|
| 997 |
+
def convert_saved_model(**kwargs):
|
| 998 |
+
"""Converts a SavedModel using TF Lite converter."""
|
| 999 |
+
model_flags = build_model_flags(**kwargs)
|
| 1000 |
+
conversion_flags = build_conversion_flags(**kwargs)
|
| 1001 |
+
data = convert(
|
| 1002 |
+
model_flags,
|
| 1003 |
+
conversion_flags,
|
| 1004 |
+
input_data_str=None,
|
| 1005 |
+
debug_info_str=None,
|
| 1006 |
+
enable_mlir_converter=True,
|
| 1007 |
+
)
|
| 1008 |
+
return data
|
| 1009 |
+
|
| 1010 |
+
|
| 1011 |
+
@convert_phase(
|
| 1012 |
+
Component.CONVERT_TF_TO_TFLITE_MODEL, SubComponent.CONVERT_JAX_HLO
|
| 1013 |
+
)
|
| 1014 |
+
def convert_jax_hlo(input_content, input_names, is_proto_format, **kwargs):
|
| 1015 |
+
"""Converts a Jax hlo-based model using TFLite converter."""
|
| 1016 |
+
model_flags = _model_flags_pb2.ModelFlags()
|
| 1017 |
+
model_flags.use_hlo_import = True
|
| 1018 |
+
if is_proto_format:
|
| 1019 |
+
model_flags.hlo_file_type = _model_flags_pb2.ModelFlags.HLO_PROTO
|
| 1020 |
+
else:
|
| 1021 |
+
model_flags.hlo_file_type = _model_flags_pb2.ModelFlags.HLO_TEXT
|
| 1022 |
+
|
| 1023 |
+
# Build input names.
|
| 1024 |
+
for input_name in input_names:
|
| 1025 |
+
input_array = model_flags.input_arrays.add()
|
| 1026 |
+
input_array.name = input_name
|
| 1027 |
+
|
| 1028 |
+
conversion_flags = build_conversion_flags(**kwargs)
|
| 1029 |
+
data = convert(
|
| 1030 |
+
model_flags,
|
| 1031 |
+
conversion_flags,
|
| 1032 |
+
input_data_str=input_content,
|
| 1033 |
+
debug_info_str=None,
|
| 1034 |
+
enable_mlir_converter=True,
|
| 1035 |
+
)
|
| 1036 |
+
return data
|
| 1037 |
+
|
| 1038 |
+
|
| 1039 |
+
@_tf_export(v1=["lite.toco_convert"])
|
| 1040 |
+
@deprecation.deprecated(None, "Use `lite.TFLiteConverter` instead.")
|
| 1041 |
+
def toco_convert(input_data, input_tensors, output_tensors, *args, **kwargs):
|
| 1042 |
+
"""Convert a TensorFlow GraphDef to TFLite.
|
| 1043 |
+
|
| 1044 |
+
This function is deprecated. Please use `tf.lite.TFLiteConverter` API instead.
|
| 1045 |
+
Conversion can be customized by providing arguments that are forwarded to
|
| 1046 |
+
`build_model_flags` and `build_conversion_flags` (see documentation for
|
| 1047 |
+
details).
|
| 1048 |
+
Args:
|
| 1049 |
+
input_data: Input data (i.e. often `sess.graph_def`).
|
| 1050 |
+
input_tensors: List of input tensors. Type and shape are computed using
|
| 1051 |
+
`foo.shape` and `foo.dtype`.
|
| 1052 |
+
output_tensors: List of output tensors (only .name is used from this).
|
| 1053 |
+
*args: See `build_model_flags` and `build_conversion_flags`.
|
| 1054 |
+
**kwargs: See `build_model_flags` and `build_conversion_flags`.
|
| 1055 |
+
|
| 1056 |
+
Returns:
|
| 1057 |
+
The converted TensorFlow Lite model in a bytes array.
|
| 1058 |
+
|
| 1059 |
+
Raises:
|
| 1060 |
+
Defined in `convert`.
|
| 1061 |
+
"""
|
| 1062 |
+
kwargs["enable_mlir_converter"] = kwargs.get("enable_mlir_converter", False)
|
| 1063 |
+
return convert_graphdef(
|
| 1064 |
+
input_data, input_tensors, output_tensors, *args, **kwargs
|
| 1065 |
+
)
|
| 1066 |
+
|
| 1067 |
+
|
| 1068 |
+
def deduplicate_readonly_buffers(tflite_model):
|
| 1069 |
+
"""Generates a new model byte array after deduplicating readonly buffers.
|
| 1070 |
+
|
| 1071 |
+
This function should be invoked after the model optimization toolkit. The
|
| 1072 |
+
model optimization toolkit assumes that each tensor object owns its each
|
| 1073 |
+
buffer separately.
|
| 1074 |
+
|
| 1075 |
+
Args:
|
| 1076 |
+
tflite_model: TFLite flatbuffer in a byte array to be deduplicated.
|
| 1077 |
+
|
| 1078 |
+
Returns:
|
| 1079 |
+
TFLite flatbuffer in a bytes array, processed with the deduplication method.
|
| 1080 |
+
"""
|
| 1081 |
+
# Load TFLite Flatbuffer byte array into an object.
|
| 1082 |
+
model = flatbuffer_utils.convert_bytearray_to_object(tflite_model)
|
| 1083 |
+
|
| 1084 |
+
# Get all the read-only buffers, which can be modified without causing any
|
| 1085 |
+
# issue in the graph invocation stage.
|
| 1086 |
+
read_only_buffer_indices = set()
|
| 1087 |
+
for subgraph in model.subgraphs:
|
| 1088 |
+
# To get all the read-only buffers:
|
| 1089 |
+
# (1) Get all read-only input tensors.
|
| 1090 |
+
# (2) Discard intermediate or output tensors.
|
| 1091 |
+
# (3) Discard the subgraph's input/output tensors.
|
| 1092 |
+
# (4) Gather the buffers of the read-only input tensors.
|
| 1093 |
+
|
| 1094 |
+
# (1) Get read-only input tensors.
|
| 1095 |
+
read_only_input_tensor_indices = set()
|
| 1096 |
+
for op in subgraph.operators:
|
| 1097 |
+
if op.inputs is None:
|
| 1098 |
+
continue
|
| 1099 |
+
for i, input_tensor_idx in enumerate(op.inputs):
|
| 1100 |
+
# Ignore mutable tensors.
|
| 1101 |
+
if op.mutatingVariableInputs is not None:
|
| 1102 |
+
# Ignore invalid tensors.
|
| 1103 |
+
if (
|
| 1104 |
+
i < len(op.mutatingVariableInputs)
|
| 1105 |
+
and op.mutatingVariableInputs[i]
|
| 1106 |
+
):
|
| 1107 |
+
continue
|
| 1108 |
+
# Ignore variable tensors.
|
| 1109 |
+
if subgraph.tensors[input_tensor_idx].isVariable:
|
| 1110 |
+
continue
|
| 1111 |
+
read_only_input_tensor_indices.add(input_tensor_idx)
|
| 1112 |
+
|
| 1113 |
+
# (2) Discard intermediate or output tensors.
|
| 1114 |
+
for op in subgraph.operators:
|
| 1115 |
+
if op.outputs is not None:
|
| 1116 |
+
for output_tensor_idx in op.outputs:
|
| 1117 |
+
read_only_input_tensor_indices.discard(output_tensor_idx)
|
| 1118 |
+
if op.intermediates is not None:
|
| 1119 |
+
for intermediate_tensor_idx in op.intermediates:
|
| 1120 |
+
read_only_input_tensor_indices.discard(intermediate_tensor_idx)
|
| 1121 |
+
|
| 1122 |
+
# (3) Discard the subgraph's input and output tensors.
|
| 1123 |
+
if subgraph.inputs is not None:
|
| 1124 |
+
for input_tensor_idx in subgraph.inputs:
|
| 1125 |
+
read_only_input_tensor_indices.discard(input_tensor_idx)
|
| 1126 |
+
if subgraph.outputs is not None:
|
| 1127 |
+
for output_tensor_idx in subgraph.outputs:
|
| 1128 |
+
read_only_input_tensor_indices.discard(output_tensor_idx)
|
| 1129 |
+
|
| 1130 |
+
# (4) Gather the buffers of the read-only input tensors.
|
| 1131 |
+
for tensor_idx in read_only_input_tensor_indices:
|
| 1132 |
+
read_only_buffer_indices.add(subgraph.tensors[tensor_idx].buffer)
|
| 1133 |
+
|
| 1134 |
+
# Ignore invalid negative index or zero-sized buffers.
|
| 1135 |
+
for buffer_idx in read_only_buffer_indices.copy():
|
| 1136 |
+
if buffer_idx < 0 or (
|
| 1137 |
+
model.buffers[buffer_idx].data is None
|
| 1138 |
+
or isinstance(model.buffers[buffer_idx].data, list)
|
| 1139 |
+
or model.buffers[buffer_idx].data.size == 0
|
| 1140 |
+
):
|
| 1141 |
+
read_only_buffer_indices.discard(buffer_idx)
|
| 1142 |
+
|
| 1143 |
+
class BufferIndex:
|
| 1144 |
+
"""A class to store index, size, hash of the buffers in TFLite model."""
|
| 1145 |
+
|
| 1146 |
+
def __init__(self, idx, size, hash_value):
|
| 1147 |
+
self.idx = idx
|
| 1148 |
+
self.size = size
|
| 1149 |
+
self.hash_value = hash_value
|
| 1150 |
+
|
| 1151 |
+
read_only_buffers = list(
|
| 1152 |
+
map(
|
| 1153 |
+
lambda index: BufferIndex( # pylint: disable=g-long-lambda
|
| 1154 |
+
index,
|
| 1155 |
+
model.buffers[index].data.size,
|
| 1156 |
+
hashlib.md5(model.buffers[index].data.data.tobytes()).hexdigest(),
|
| 1157 |
+
),
|
| 1158 |
+
read_only_buffer_indices,
|
| 1159 |
+
)
|
| 1160 |
+
)
|
| 1161 |
+
|
| 1162 |
+
# Sort read_only_buffers by buffer size & hash in descending order.
|
| 1163 |
+
read_only_buffers = sorted(
|
| 1164 |
+
read_only_buffers,
|
| 1165 |
+
key=lambda buffer: (buffer.size, buffer.hash_value),
|
| 1166 |
+
reverse=True,
|
| 1167 |
+
)
|
| 1168 |
+
|
| 1169 |
+
# Create a map of duplicate buffers (same size and same type).
|
| 1170 |
+
# eg: In [1, 2, 3, 4, 5, 6] if (1, 4, 6) and (2, 5) are each, groups of buffer
|
| 1171 |
+
# indices of the same size and type, then the map would be {4:1, 6:1, 5:2}
|
| 1172 |
+
duplicate_buffer_map = {}
|
| 1173 |
+
for i, buffer_i in enumerate(read_only_buffers):
|
| 1174 |
+
# This buffer is a duplicate.
|
| 1175 |
+
if buffer_i.idx in duplicate_buffer_map:
|
| 1176 |
+
continue
|
| 1177 |
+
# This buffer is unique. Scan rest of the list to find duplicates
|
| 1178 |
+
# of this buffer and mark them accordingly.
|
| 1179 |
+
for buffer_j in read_only_buffers[i + 1 :]:
|
| 1180 |
+
if buffer_j.idx in duplicate_buffer_map:
|
| 1181 |
+
continue
|
| 1182 |
+
if buffer_i.size != buffer_j.size:
|
| 1183 |
+
break
|
| 1184 |
+
if buffer_i.hash_value != buffer_j.hash_value:
|
| 1185 |
+
continue
|
| 1186 |
+
# Found duplicate. Nullify j-th buffer and use i-th buffer instead.
|
| 1187 |
+
duplicate_buffer_map[buffer_j.idx] = buffer_i.idx
|
| 1188 |
+
|
| 1189 |
+
# Make the duplicated tensors use the single shared buffer index.
|
| 1190 |
+
for subgraph in model.subgraphs:
|
| 1191 |
+
for op in subgraph.operators:
|
| 1192 |
+
if op.inputs is None:
|
| 1193 |
+
continue
|
| 1194 |
+
for input_tensor in op.inputs:
|
| 1195 |
+
buffer_idx = subgraph.tensors[input_tensor].buffer
|
| 1196 |
+
if buffer_idx in duplicate_buffer_map:
|
| 1197 |
+
subgraph.tensors[input_tensor].buffer = duplicate_buffer_map[
|
| 1198 |
+
buffer_idx
|
| 1199 |
+
]
|
| 1200 |
+
|
| 1201 |
+
# Nullify the unused buffers.
|
| 1202 |
+
for idx in duplicate_buffer_map:
|
| 1203 |
+
model.buffers[idx].data = None
|
| 1204 |
+
|
| 1205 |
+
# Return a TFLite flatbuffer as a byte array.
|
| 1206 |
+
return flatbuffer_utils.convert_object_to_bytearray(model)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/convert_phase.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Utilities for collecting TFLite metrics."""
|
| 16 |
+
|
| 17 |
+
import collections
|
| 18 |
+
import enum
|
| 19 |
+
import functools
|
| 20 |
+
from typing import Text
|
| 21 |
+
|
| 22 |
+
from tensorflow.lite.python.metrics import converter_error_data_pb2
|
| 23 |
+
from tensorflow.lite.python.metrics import metrics
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Component(enum.Enum):
|
| 27 |
+
"""Enum class defining name of the converter components."""
|
| 28 |
+
# Validate the given input and prepare and optimize TensorFlow Model.
|
| 29 |
+
PREPARE_TF_MODEL = "PREPARE_TF_MODEL"
|
| 30 |
+
|
| 31 |
+
# Convert to TFLite model format.
|
| 32 |
+
CONVERT_TF_TO_TFLITE_MODEL = "CONVERT_TF_TO_TFLITE_MODEL"
|
| 33 |
+
|
| 34 |
+
# RUN quantization and sparsification.
|
| 35 |
+
OPTIMIZE_TFLITE_MODEL = "OPTIMIZE_TFLITE_MODEL"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
SubComponentItem = collections.namedtuple("SubComponentItem",
|
| 39 |
+
["name", "component"])
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class SubComponent(SubComponentItem, enum.Enum):
|
| 43 |
+
"""Enum class defining name of the converter subcomponents.
|
| 44 |
+
|
| 45 |
+
This enum only defines the subcomponents in Python, there might be more
|
| 46 |
+
subcomponents defined in C++.
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
def __str__(self):
|
| 50 |
+
return self.value.name
|
| 51 |
+
|
| 52 |
+
@property
|
| 53 |
+
def name(self):
|
| 54 |
+
return self.value.name
|
| 55 |
+
|
| 56 |
+
@property
|
| 57 |
+
def component(self):
|
| 58 |
+
return self.value.component
|
| 59 |
+
|
| 60 |
+
# The subcomponent name is unspecified.
|
| 61 |
+
UNSPECIFIED = SubComponentItem("UNSPECIFIED", None)
|
| 62 |
+
|
| 63 |
+
# Valid the given input and parameters.
|
| 64 |
+
VALIDATE_INPUTS = SubComponentItem("VALIDATE_INPUTS",
|
| 65 |
+
Component.PREPARE_TF_MODEL)
|
| 66 |
+
|
| 67 |
+
# Load GraphDef from SavedModel.
|
| 68 |
+
LOAD_SAVED_MODEL = SubComponentItem("LOAD_SAVED_MODEL",
|
| 69 |
+
Component.PREPARE_TF_MODEL)
|
| 70 |
+
|
| 71 |
+
# Convert a SavedModel to frozen graph.
|
| 72 |
+
FREEZE_SAVED_MODEL = SubComponentItem("FREEZE_SAVED_MODEL",
|
| 73 |
+
Component.PREPARE_TF_MODEL)
|
| 74 |
+
|
| 75 |
+
# Save a Keras model to SavedModel.
|
| 76 |
+
CONVERT_KERAS_TO_SAVED_MODEL = SubComponentItem(
|
| 77 |
+
"CONVERT_KERAS_TO_SAVED_MODEL", Component.PREPARE_TF_MODEL)
|
| 78 |
+
|
| 79 |
+
# Save Concrete functions to SavedModel.
|
| 80 |
+
CONVERT_CONCRETE_FUNCTIONS_TO_SAVED_MODEL = SubComponentItem(
|
| 81 |
+
"CONVERT_CONCRETE_FUNCTIONS_TO_SAVED_MODEL", Component.PREPARE_TF_MODEL)
|
| 82 |
+
|
| 83 |
+
# Convert a Keras model to a frozen graph.
|
| 84 |
+
FREEZE_KERAS_MODEL = SubComponentItem("FREEZE_KERAS_MODEL",
|
| 85 |
+
Component.PREPARE_TF_MODEL)
|
| 86 |
+
|
| 87 |
+
# Replace all the variables with constants in a ConcreteFunction.
|
| 88 |
+
FREEZE_CONCRETE_FUNCTION = SubComponentItem("FREEZE_CONCRETE_FUNCTION",
|
| 89 |
+
Component.PREPARE_TF_MODEL)
|
| 90 |
+
|
| 91 |
+
# Run grappler optimization.
|
| 92 |
+
OPTIMIZE_TF_MODEL = SubComponentItem("OPTIMIZE_TF_MODEL",
|
| 93 |
+
Component.PREPARE_TF_MODEL)
|
| 94 |
+
|
| 95 |
+
# Convert using the old TOCO converter.
|
| 96 |
+
CONVERT_GRAPHDEF_USING_DEPRECATED_CONVERTER = SubComponentItem(
|
| 97 |
+
"CONVERT_GRAPHDEF_USING_DEPRECATED_CONVERTER",
|
| 98 |
+
Component.CONVERT_TF_TO_TFLITE_MODEL)
|
| 99 |
+
|
| 100 |
+
# Convert a GraphDef to TFLite model.
|
| 101 |
+
CONVERT_GRAPHDEF = SubComponentItem("CONVERT_GRAPHDEF",
|
| 102 |
+
Component.CONVERT_TF_TO_TFLITE_MODEL)
|
| 103 |
+
|
| 104 |
+
# Convert a SavedModel to TFLite model.
|
| 105 |
+
CONVERT_SAVED_MODEL = SubComponentItem("CONVERT_SAVED_MODEL",
|
| 106 |
+
Component.CONVERT_TF_TO_TFLITE_MODEL)
|
| 107 |
+
|
| 108 |
+
# Convert a Jax HLO to TFLite model.
|
| 109 |
+
CONVERT_JAX_HLO = SubComponentItem("CONVERT_JAX_HLO",
|
| 110 |
+
Component.CONVERT_TF_TO_TFLITE_MODEL)
|
| 111 |
+
|
| 112 |
+
# Do quantization by the deprecated quantizer.
|
| 113 |
+
QUANTIZE_USING_DEPRECATED_QUANTIZER = SubComponentItem(
|
| 114 |
+
"QUANTIZE_USING_DEPRECATED_QUANTIZER", Component.OPTIMIZE_TFLITE_MODEL)
|
| 115 |
+
|
| 116 |
+
# Do calibration.
|
| 117 |
+
CALIBRATE = SubComponentItem("CALIBRATE", Component.OPTIMIZE_TFLITE_MODEL)
|
| 118 |
+
|
| 119 |
+
# Do quantization by MLIR.
|
| 120 |
+
QUANTIZE = SubComponentItem("QUANTIZE", Component.OPTIMIZE_TFLITE_MODEL)
|
| 121 |
+
|
| 122 |
+
# Do sparsification by MLIR.
|
| 123 |
+
SPARSIFY = SubComponentItem("SPARSIFY", Component.OPTIMIZE_TFLITE_MODEL)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class ConverterError(Exception):
|
| 127 |
+
"""Raised when an error occurs during model conversion."""
|
| 128 |
+
|
| 129 |
+
def __init__(self, message):
|
| 130 |
+
super(ConverterError, self).__init__(message)
|
| 131 |
+
self.errors = []
|
| 132 |
+
self._parse_error_message(message)
|
| 133 |
+
|
| 134 |
+
def append_error(self,
|
| 135 |
+
error_data: converter_error_data_pb2.ConverterErrorData):
|
| 136 |
+
self.errors.append(error_data)
|
| 137 |
+
|
| 138 |
+
def _parse_error_message(self, message):
|
| 139 |
+
"""If the message matches a pattern, assigns the associated error code.
|
| 140 |
+
|
| 141 |
+
It is difficult to assign an error code to some errrors in MLIR side, Ex:
|
| 142 |
+
errors thrown by other components than TFLite or not using mlir::emitError.
|
| 143 |
+
This function try to detect them by the error message and assign the
|
| 144 |
+
corresponding error code.
|
| 145 |
+
|
| 146 |
+
Args:
|
| 147 |
+
message: The error message of this exception.
|
| 148 |
+
"""
|
| 149 |
+
error_code_mapping = {
|
| 150 |
+
"Failed to functionalize Control Flow V1 ops. Consider using Control "
|
| 151 |
+
"Flow V2 ops instead. See https://www.tensorflow.org/api_docs/python/"
|
| 152 |
+
"tf/compat/v1/enable_control_flow_v2.":
|
| 153 |
+
converter_error_data_pb2.ConverterErrorData
|
| 154 |
+
.ERROR_UNSUPPORTED_CONTROL_FLOW_V1,
|
| 155 |
+
}
|
| 156 |
+
for pattern, error_code in error_code_mapping.items():
|
| 157 |
+
if pattern in message:
|
| 158 |
+
error_data = converter_error_data_pb2.ConverterErrorData()
|
| 159 |
+
error_data.error_message = message
|
| 160 |
+
error_data.error_code = error_code
|
| 161 |
+
self.append_error(error_data)
|
| 162 |
+
return
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def convert_phase(component, subcomponent=SubComponent.UNSPECIFIED):
|
| 166 |
+
"""The decorator to identify converter component and subcomponent.
|
| 167 |
+
|
| 168 |
+
Args:
|
| 169 |
+
component: Converter component name.
|
| 170 |
+
subcomponent: Converter subcomponent name.
|
| 171 |
+
|
| 172 |
+
Returns:
|
| 173 |
+
Forward the result from the wrapped function.
|
| 174 |
+
|
| 175 |
+
Raises:
|
| 176 |
+
ValueError: if component and subcomponent name is not valid.
|
| 177 |
+
"""
|
| 178 |
+
if component not in Component:
|
| 179 |
+
raise ValueError("Given component name not found")
|
| 180 |
+
if subcomponent not in SubComponent:
|
| 181 |
+
raise ValueError("Given subcomponent name not found")
|
| 182 |
+
if (subcomponent != SubComponent.UNSPECIFIED and
|
| 183 |
+
subcomponent.component != component):
|
| 184 |
+
raise ValueError("component and subcomponent name don't match")
|
| 185 |
+
|
| 186 |
+
def report_error(error_data: converter_error_data_pb2.ConverterErrorData):
|
| 187 |
+
# Always overwrites the component information, but only overwrites the
|
| 188 |
+
# subcomponent if it is not available.
|
| 189 |
+
error_data.component = component.value
|
| 190 |
+
if not error_data.subcomponent:
|
| 191 |
+
error_data.subcomponent = subcomponent.name
|
| 192 |
+
tflite_metrics = metrics.TFLiteConverterMetrics()
|
| 193 |
+
tflite_metrics.set_converter_error(error_data)
|
| 194 |
+
|
| 195 |
+
def report_error_message(error_message: Text):
|
| 196 |
+
error_data = converter_error_data_pb2.ConverterErrorData()
|
| 197 |
+
error_data.error_message = error_message
|
| 198 |
+
report_error(error_data)
|
| 199 |
+
|
| 200 |
+
def actual_decorator(func):
|
| 201 |
+
|
| 202 |
+
@functools.wraps(func)
|
| 203 |
+
def wrapper(*args, **kwargs):
|
| 204 |
+
try:
|
| 205 |
+
return func(*args, **kwargs)
|
| 206 |
+
except ConverterError as converter_error:
|
| 207 |
+
if converter_error.errors:
|
| 208 |
+
for error_data in converter_error.errors:
|
| 209 |
+
report_error(error_data)
|
| 210 |
+
else:
|
| 211 |
+
report_error_message(str(converter_error))
|
| 212 |
+
raise converter_error from None # Re-throws the exception.
|
| 213 |
+
except Exception as error:
|
| 214 |
+
report_error_message(str(error))
|
| 215 |
+
raise error from None # Re-throws the exception.
|
| 216 |
+
|
| 217 |
+
return wrapper
|
| 218 |
+
|
| 219 |
+
return actual_decorator
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/convert_saved_model.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2018 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 |
+
"""Functions to convert SavedModel to frozen GraphDefs."""
|
| 16 |
+
|
| 17 |
+
from tensorflow.lite.python import util
|
| 18 |
+
from tensorflow.lite.python.convert_phase import Component
|
| 19 |
+
from tensorflow.lite.python.convert_phase import convert_phase
|
| 20 |
+
from tensorflow.lite.python.convert_phase import SubComponent
|
| 21 |
+
from tensorflow.python.client import session
|
| 22 |
+
from tensorflow.python.framework import ops
|
| 23 |
+
from tensorflow.python.platform import tf_logging as logging
|
| 24 |
+
from tensorflow.python.saved_model import constants
|
| 25 |
+
from tensorflow.python.saved_model import loader
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def get_meta_graph_def(saved_model_dir, tag_set):
|
| 29 |
+
"""Validate saved_model and extract MetaGraphDef.
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
saved_model_dir: saved_model path to convert.
|
| 33 |
+
tag_set: Set of tag(s) of the MetaGraphDef to load.
|
| 34 |
+
|
| 35 |
+
Returns:
|
| 36 |
+
The meta_graph_def used for tflite conversion.
|
| 37 |
+
|
| 38 |
+
Raises:
|
| 39 |
+
ValueError: No valid MetaGraphDef for given tag_set.
|
| 40 |
+
"""
|
| 41 |
+
with session.Session(graph=ops.Graph()) as sess:
|
| 42 |
+
return loader.load(sess, tag_set, saved_model_dir)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def get_signature_def(meta_graph, signature_key):
|
| 46 |
+
"""Get the signature def from meta_graph with given signature_key.
|
| 47 |
+
|
| 48 |
+
Args:
|
| 49 |
+
meta_graph: meta_graph_def.
|
| 50 |
+
signature_key: signature_def in the meta_graph_def.
|
| 51 |
+
|
| 52 |
+
Returns:
|
| 53 |
+
The signature_def used for tflite conversion.
|
| 54 |
+
|
| 55 |
+
Raises:
|
| 56 |
+
ValueError: Given signature_key is not valid for this meta_graph.
|
| 57 |
+
"""
|
| 58 |
+
signature_def_map = meta_graph.signature_def
|
| 59 |
+
signature_def_keys = set(signature_def_map.keys())
|
| 60 |
+
logging.info(
|
| 61 |
+
"The given SavedModel MetaGraphDef contains SignatureDefs with the "
|
| 62 |
+
"following keys: %s", signature_def_keys)
|
| 63 |
+
if signature_key not in signature_def_keys:
|
| 64 |
+
raise ValueError("No '{}' in the SavedModel\'s SignatureDefs. Possible "
|
| 65 |
+
"values are '{}'.".format(signature_key,
|
| 66 |
+
",".join(signature_def_keys)))
|
| 67 |
+
return signature_def_map[signature_key]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def get_inputs_outputs(signature_def):
|
| 71 |
+
"""Get inputs and outputs from SignatureDef.
|
| 72 |
+
|
| 73 |
+
Args:
|
| 74 |
+
signature_def: SignatureDef in the meta_graph_def for conversion.
|
| 75 |
+
|
| 76 |
+
Returns:
|
| 77 |
+
The inputs and outputs in the graph for conversion.
|
| 78 |
+
"""
|
| 79 |
+
inputs_tensor_info = signature_def.inputs
|
| 80 |
+
outputs_tensor_info = signature_def.outputs
|
| 81 |
+
|
| 82 |
+
def gather_names(tensor_info):
|
| 83 |
+
return [tensor_info[key].name for key in tensor_info]
|
| 84 |
+
|
| 85 |
+
inputs = gather_names(inputs_tensor_info)
|
| 86 |
+
outputs = gather_names(outputs_tensor_info)
|
| 87 |
+
return inputs, outputs
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _get_tensors(graph, signature_def_tensor_names=None,
|
| 91 |
+
user_tensor_names=None):
|
| 92 |
+
"""Gets the tensors associated with the tensor names.
|
| 93 |
+
|
| 94 |
+
Either signature_def_tensor_names or user_tensor_names should be provided. If
|
| 95 |
+
the user provides tensors, the tensors associated with the user provided
|
| 96 |
+
tensor names are provided. Otherwise, the tensors associated with the names in
|
| 97 |
+
the SignatureDef are provided.
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
graph: GraphDef representing graph.
|
| 101 |
+
signature_def_tensor_names: Tensor names stored in either the inputs or
|
| 102 |
+
outputs of a SignatureDef. (default None)
|
| 103 |
+
user_tensor_names: Tensor names provided by the user. (default None)
|
| 104 |
+
|
| 105 |
+
Returns:
|
| 106 |
+
List of tensors.
|
| 107 |
+
|
| 108 |
+
Raises:
|
| 109 |
+
ValueError:
|
| 110 |
+
signature_def_tensors and user_tensor_names are undefined or empty.
|
| 111 |
+
user_tensor_names are not valid.
|
| 112 |
+
"""
|
| 113 |
+
tensors = []
|
| 114 |
+
if user_tensor_names:
|
| 115 |
+
# Sort the tensor names.
|
| 116 |
+
user_tensor_names = sorted(user_tensor_names)
|
| 117 |
+
|
| 118 |
+
tensors = util.get_tensors_from_tensor_names(graph, user_tensor_names)
|
| 119 |
+
elif signature_def_tensor_names:
|
| 120 |
+
tensors = [
|
| 121 |
+
graph.get_tensor_by_name(name)
|
| 122 |
+
for name in sorted(signature_def_tensor_names)
|
| 123 |
+
]
|
| 124 |
+
else:
|
| 125 |
+
# Throw ValueError if signature_def_tensors and user_tensor_names are both
|
| 126 |
+
# either undefined or empty.
|
| 127 |
+
raise ValueError(
|
| 128 |
+
"Specify either signature_def_tensor_names or user_tensor_names")
|
| 129 |
+
|
| 130 |
+
return tensors
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
@convert_phase(Component.PREPARE_TF_MODEL, SubComponent.FREEZE_SAVED_MODEL)
|
| 134 |
+
def freeze_saved_model(saved_model_dir, input_arrays, input_shapes,
|
| 135 |
+
output_arrays, tag_set, signature_key):
|
| 136 |
+
"""Converts a SavedModel to a frozen graph.
|
| 137 |
+
|
| 138 |
+
Args:
|
| 139 |
+
saved_model_dir: SavedModel directory to convert.
|
| 140 |
+
input_arrays: List of input tensors to freeze graph with. Uses input arrays
|
| 141 |
+
from SignatureDef when none are provided.
|
| 142 |
+
input_shapes: Dict of strings representing input tensor names to list of
|
| 143 |
+
integers representing input shapes (e.g., {"foo": : [1, 16, 16, 3]}).
|
| 144 |
+
Automatically determined when input shapes is None (e.g., {"foo" : None}).
|
| 145 |
+
output_arrays: List of output tensors to freeze graph with. Uses output
|
| 146 |
+
arrays from SignatureDef when none are provided.
|
| 147 |
+
tag_set: Set of tags identifying the MetaGraphDef within the SavedModel to
|
| 148 |
+
analyze. All tags in the tag set must be present.
|
| 149 |
+
signature_key: Key identifying SignatureDef containing inputs and outputs.
|
| 150 |
+
|
| 151 |
+
Returns:
|
| 152 |
+
frozen_graph_def: Frozen GraphDef.
|
| 153 |
+
in_tensors: List of input tensors for the graph.
|
| 154 |
+
out_tensors: List of output tensors for the graph.
|
| 155 |
+
graph: `Graph` object.
|
| 156 |
+
|
| 157 |
+
Raises:
|
| 158 |
+
ValueError:
|
| 159 |
+
SavedModel doesn't contain a MetaGraphDef identified by tag_set.
|
| 160 |
+
signature_key is not in the MetaGraphDef.
|
| 161 |
+
assets/ directory is in the MetaGraphDef.
|
| 162 |
+
input_shapes does not match the length of input_arrays.
|
| 163 |
+
input_arrays or output_arrays are not valid.
|
| 164 |
+
"""
|
| 165 |
+
# Read SignatureDef.
|
| 166 |
+
meta_graph = get_meta_graph_def(saved_model_dir, tag_set)
|
| 167 |
+
signature_def = get_signature_def(meta_graph, signature_key)
|
| 168 |
+
inputs, outputs = get_inputs_outputs(signature_def)
|
| 169 |
+
|
| 170 |
+
# Check SavedModel for assets directory.
|
| 171 |
+
collection_def = meta_graph.collection_def
|
| 172 |
+
if constants.ASSETS_KEY in collection_def:
|
| 173 |
+
raise ValueError("SavedModels with assets/ directory are not supported.")
|
| 174 |
+
|
| 175 |
+
graph = ops.Graph()
|
| 176 |
+
with session.Session(graph=graph) as sess:
|
| 177 |
+
loader.load(sess, meta_graph.meta_info_def.tags, saved_model_dir)
|
| 178 |
+
|
| 179 |
+
# Gets input and output tensors.
|
| 180 |
+
# TODO(zhixianyan): Use TFLite supported Op list to filter outputs.
|
| 181 |
+
in_tensors = _get_tensors(graph, inputs, input_arrays)
|
| 182 |
+
out_tensors = _get_tensors(graph, outputs, output_arrays)
|
| 183 |
+
util.set_tensor_shapes(in_tensors, input_shapes)
|
| 184 |
+
|
| 185 |
+
frozen_graph_def = util.freeze_graph(sess, in_tensors, out_tensors)
|
| 186 |
+
return frozen_graph_def, in_tensors, out_tensors, sess.graph
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/interpre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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2018 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 |
+
"""Python TF-Lite interpreter."""
|
| 16 |
+
import ctypes
|
| 17 |
+
import enum
|
| 18 |
+
import os
|
| 19 |
+
import platform
|
| 20 |
+
import sys
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
# pylint: disable=g-import-not-at-top
|
| 25 |
+
if not os.path.splitext(__file__)[0].endswith(
|
| 26 |
+
os.path.join('tflite_runtime', 'interpreter')):
|
| 27 |
+
# This file is part of tensorflow package.
|
| 28 |
+
from tensorflow.lite.python.interpreter_wrapper import _pywrap_tensorflow_interpreter_wrapper as _interpreter_wrapper
|
| 29 |
+
from tensorflow.lite.python.metrics import metrics
|
| 30 |
+
from tensorflow.python.util.tf_export import tf_export as _tf_export
|
| 31 |
+
else:
|
| 32 |
+
# This file is part of tflite_runtime package.
|
| 33 |
+
from tflite_runtime import _pywrap_tensorflow_interpreter_wrapper as _interpreter_wrapper
|
| 34 |
+
from tflite_runtime import metrics_portable as metrics
|
| 35 |
+
|
| 36 |
+
def _tf_export(*x, **kwargs):
|
| 37 |
+
del x, kwargs
|
| 38 |
+
return lambda x: x
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# pylint: enable=g-import-not-at-top
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class Delegate:
|
| 45 |
+
"""Python wrapper class to manage TfLiteDelegate objects.
|
| 46 |
+
|
| 47 |
+
The shared library is expected to have two functions,
|
| 48 |
+
tflite_plugin_create_delegate and tflite_plugin_destroy_delegate,
|
| 49 |
+
which should implement the API specified in
|
| 50 |
+
tensorflow/lite/delegates/external/external_delegate_interface.h.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
def __init__(self, library, options=None):
|
| 54 |
+
"""Loads delegate from the shared library.
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
library: Shared library name.
|
| 58 |
+
options: Dictionary of options that are required to load the delegate. All
|
| 59 |
+
keys and values in the dictionary should be serializable. Consult the
|
| 60 |
+
documentation of the specific delegate for required and legal options.
|
| 61 |
+
(default None)
|
| 62 |
+
|
| 63 |
+
Raises:
|
| 64 |
+
RuntimeError: This is raised if the Python implementation is not CPython.
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
# TODO(b/136468453): Remove need for __del__ ordering needs of CPython
|
| 68 |
+
# by using explicit closes(). See implementation of Interpreter __del__.
|
| 69 |
+
if platform.python_implementation() != 'CPython':
|
| 70 |
+
raise RuntimeError('Delegates are currently only supported into CPython'
|
| 71 |
+
'due to missing immediate reference counting.')
|
| 72 |
+
|
| 73 |
+
self._library = ctypes.pydll.LoadLibrary(library)
|
| 74 |
+
self._library.tflite_plugin_create_delegate.argtypes = [
|
| 75 |
+
ctypes.POINTER(ctypes.c_char_p),
|
| 76 |
+
ctypes.POINTER(ctypes.c_char_p), ctypes.c_int,
|
| 77 |
+
ctypes.CFUNCTYPE(None, ctypes.c_char_p)
|
| 78 |
+
]
|
| 79 |
+
# The return type is really 'TfLiteDelegate*', but 'void*' is close enough.
|
| 80 |
+
self._library.tflite_plugin_create_delegate.restype = ctypes.c_void_p
|
| 81 |
+
|
| 82 |
+
# Convert the options from a dictionary to lists of char pointers.
|
| 83 |
+
options = options or {}
|
| 84 |
+
options_keys = (ctypes.c_char_p * len(options))()
|
| 85 |
+
options_values = (ctypes.c_char_p * len(options))()
|
| 86 |
+
for idx, (key, value) in enumerate(options.items()):
|
| 87 |
+
options_keys[idx] = str(key).encode('utf-8')
|
| 88 |
+
options_values[idx] = str(value).encode('utf-8')
|
| 89 |
+
|
| 90 |
+
class ErrorMessageCapture:
|
| 91 |
+
|
| 92 |
+
def __init__(self):
|
| 93 |
+
self.message = ''
|
| 94 |
+
|
| 95 |
+
def report(self, x):
|
| 96 |
+
self.message += x if isinstance(x, str) else x.decode('utf-8')
|
| 97 |
+
|
| 98 |
+
capture = ErrorMessageCapture()
|
| 99 |
+
error_capturer_cb = ctypes.CFUNCTYPE(None, ctypes.c_char_p)(capture.report)
|
| 100 |
+
# Do not make a copy of _delegate_ptr. It is freed by Delegate's finalizer.
|
| 101 |
+
self._delegate_ptr = self._library.tflite_plugin_create_delegate(
|
| 102 |
+
options_keys, options_values, len(options), error_capturer_cb)
|
| 103 |
+
if self._delegate_ptr is None:
|
| 104 |
+
raise ValueError(capture.message)
|
| 105 |
+
|
| 106 |
+
def __del__(self):
|
| 107 |
+
# __del__ can not be called multiple times, so if the delegate is destroyed.
|
| 108 |
+
# don't try to destroy it twice.
|
| 109 |
+
if self._library is not None:
|
| 110 |
+
self._library.tflite_plugin_destroy_delegate.argtypes = [ctypes.c_void_p]
|
| 111 |
+
self._library.tflite_plugin_destroy_delegate(self._delegate_ptr)
|
| 112 |
+
self._library = None
|
| 113 |
+
|
| 114 |
+
def _get_native_delegate_pointer(self):
|
| 115 |
+
"""Returns the native TfLiteDelegate pointer.
|
| 116 |
+
|
| 117 |
+
It is not safe to copy this pointer because it needs to be freed.
|
| 118 |
+
|
| 119 |
+
Returns:
|
| 120 |
+
TfLiteDelegate *
|
| 121 |
+
"""
|
| 122 |
+
return self._delegate_ptr
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
@_tf_export('lite.experimental.load_delegate')
|
| 126 |
+
def load_delegate(library, options=None):
|
| 127 |
+
"""Returns loaded Delegate object.
|
| 128 |
+
|
| 129 |
+
Example usage:
|
| 130 |
+
|
| 131 |
+
```
|
| 132 |
+
import tensorflow as tf
|
| 133 |
+
|
| 134 |
+
try:
|
| 135 |
+
delegate = tf.lite.experimental.load_delegate('delegate.so')
|
| 136 |
+
except ValueError:
|
| 137 |
+
// Fallback to CPU
|
| 138 |
+
|
| 139 |
+
if delegate:
|
| 140 |
+
interpreter = tf.lite.Interpreter(
|
| 141 |
+
model_path='model.tflite',
|
| 142 |
+
experimental_delegates=[delegate])
|
| 143 |
+
else:
|
| 144 |
+
interpreter = tf.lite.Interpreter(model_path='model.tflite')
|
| 145 |
+
```
|
| 146 |
+
|
| 147 |
+
This is typically used to leverage EdgeTPU for running TensorFlow Lite models.
|
| 148 |
+
For more information see: https://coral.ai/docs/edgetpu/tflite-python/
|
| 149 |
+
|
| 150 |
+
Args:
|
| 151 |
+
library: Name of shared library containing the
|
| 152 |
+
[TfLiteDelegate](https://www.tensorflow.org/lite/performance/delegates).
|
| 153 |
+
options: Dictionary of options that are required to load the delegate. All
|
| 154 |
+
keys and values in the dictionary should be convertible to str. Consult
|
| 155 |
+
the documentation of the specific delegate for required and legal options.
|
| 156 |
+
(default None)
|
| 157 |
+
|
| 158 |
+
Returns:
|
| 159 |
+
Delegate object.
|
| 160 |
+
|
| 161 |
+
Raises:
|
| 162 |
+
ValueError: Delegate failed to load.
|
| 163 |
+
RuntimeError: If delegate loading is used on unsupported platform.
|
| 164 |
+
"""
|
| 165 |
+
try:
|
| 166 |
+
delegate = Delegate(library, options)
|
| 167 |
+
except ValueError as e:
|
| 168 |
+
raise ValueError('Failed to load delegate from {}\n{}'.format(
|
| 169 |
+
library, str(e)))
|
| 170 |
+
return delegate
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class SignatureRunner:
|
| 174 |
+
"""SignatureRunner class for running TFLite models using SignatureDef.
|
| 175 |
+
|
| 176 |
+
This class should be instantiated through TFLite Interpreter only using
|
| 177 |
+
get_signature_runner method on Interpreter.
|
| 178 |
+
Example,
|
| 179 |
+
signature = interpreter.get_signature_runner("my_signature")
|
| 180 |
+
result = signature(input_1=my_input_1, input_2=my_input_2)
|
| 181 |
+
print(result["my_output"])
|
| 182 |
+
print(result["my_second_output"])
|
| 183 |
+
All names used are this specific SignatureDef names.
|
| 184 |
+
|
| 185 |
+
Notes:
|
| 186 |
+
No other function on this object or on the interpreter provided should be
|
| 187 |
+
called while this object call has not finished.
|
| 188 |
+
"""
|
| 189 |
+
|
| 190 |
+
def __init__(self, interpreter=None, signature_key=None):
|
| 191 |
+
"""Constructor.
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
interpreter: Interpreter object that is already initialized with the
|
| 195 |
+
requested model.
|
| 196 |
+
signature_key: SignatureDef key to be used.
|
| 197 |
+
"""
|
| 198 |
+
if not interpreter:
|
| 199 |
+
raise ValueError('None interpreter provided.')
|
| 200 |
+
if not signature_key:
|
| 201 |
+
raise ValueError('None signature_key provided.')
|
| 202 |
+
self._interpreter = interpreter
|
| 203 |
+
self._interpreter_wrapper = interpreter._interpreter
|
| 204 |
+
self._signature_key = signature_key
|
| 205 |
+
signature_defs = interpreter._get_full_signature_list()
|
| 206 |
+
if signature_key not in signature_defs:
|
| 207 |
+
raise ValueError('Invalid signature_key provided.')
|
| 208 |
+
self._signature_def = signature_defs[signature_key]
|
| 209 |
+
self._outputs = self._signature_def['outputs'].items()
|
| 210 |
+
self._inputs = self._signature_def['inputs']
|
| 211 |
+
|
| 212 |
+
self._subgraph_index = (
|
| 213 |
+
self._interpreter_wrapper.GetSubgraphIndexFromSignature(
|
| 214 |
+
self._signature_key))
|
| 215 |
+
|
| 216 |
+
def __call__(self, **kwargs):
|
| 217 |
+
"""Runs the SignatureDef given the provided inputs in arguments.
|
| 218 |
+
|
| 219 |
+
Args:
|
| 220 |
+
**kwargs: key,value for inputs to the model. Key is the SignatureDef input
|
| 221 |
+
name. Value is numpy array with the value.
|
| 222 |
+
|
| 223 |
+
Returns:
|
| 224 |
+
dictionary of the results from the model invoke.
|
| 225 |
+
Key in the dictionary is SignatureDef output name.
|
| 226 |
+
Value is the result Tensor.
|
| 227 |
+
"""
|
| 228 |
+
|
| 229 |
+
if len(kwargs) != len(self._inputs):
|
| 230 |
+
raise ValueError(
|
| 231 |
+
'Invalid number of inputs provided for running a SignatureDef, '
|
| 232 |
+
'expected %s vs provided %s' % (len(self._inputs), len(kwargs)))
|
| 233 |
+
|
| 234 |
+
# Resize input tensors
|
| 235 |
+
for input_name, value in kwargs.items():
|
| 236 |
+
if input_name not in self._inputs:
|
| 237 |
+
raise ValueError('Invalid Input name (%s) for SignatureDef' %
|
| 238 |
+
input_name)
|
| 239 |
+
self._interpreter_wrapper.ResizeInputTensor(
|
| 240 |
+
self._inputs[input_name], np.array(value.shape, dtype=np.int32),
|
| 241 |
+
False, self._subgraph_index)
|
| 242 |
+
# Allocate tensors.
|
| 243 |
+
self._interpreter_wrapper.AllocateTensors(self._subgraph_index)
|
| 244 |
+
# Set the input values.
|
| 245 |
+
for input_name, value in kwargs.items():
|
| 246 |
+
self._interpreter_wrapper.SetTensor(self._inputs[input_name], value,
|
| 247 |
+
self._subgraph_index)
|
| 248 |
+
|
| 249 |
+
self._interpreter_wrapper.Invoke(self._subgraph_index)
|
| 250 |
+
result = {}
|
| 251 |
+
for output_name, output_index in self._outputs:
|
| 252 |
+
result[output_name] = self._interpreter_wrapper.GetTensor(
|
| 253 |
+
output_index, self._subgraph_index)
|
| 254 |
+
return result
|
| 255 |
+
|
| 256 |
+
def get_input_details(self):
|
| 257 |
+
"""Gets input tensor details.
|
| 258 |
+
|
| 259 |
+
Returns:
|
| 260 |
+
A dictionary from input name to tensor details where each item is a
|
| 261 |
+
dictionary with details about an input tensor. Each dictionary contains
|
| 262 |
+
the following fields that describe the tensor:
|
| 263 |
+
|
| 264 |
+
+ `name`: The tensor name.
|
| 265 |
+
+ `index`: The tensor index in the interpreter.
|
| 266 |
+
+ `shape`: The shape of the tensor.
|
| 267 |
+
+ `shape_signature`: Same as `shape` for models with known/fixed shapes.
|
| 268 |
+
If any dimension sizes are unknown, they are indicated with `-1`.
|
| 269 |
+
+ `dtype`: The numpy data type (such as `np.int32` or `np.uint8`).
|
| 270 |
+
+ `quantization`: Deprecated, use `quantization_parameters`. This field
|
| 271 |
+
only works for per-tensor quantization, whereas
|
| 272 |
+
`quantization_parameters` works in all cases.
|
| 273 |
+
+ `quantization_parameters`: A dictionary of parameters used to quantize
|
| 274 |
+
the tensor:
|
| 275 |
+
~ `scales`: List of scales (one if per-tensor quantization).
|
| 276 |
+
~ `zero_points`: List of zero_points (one if per-tensor quantization).
|
| 277 |
+
~ `quantized_dimension`: Specifies the dimension of per-axis
|
| 278 |
+
quantization, in the case of multiple scales/zero_points.
|
| 279 |
+
+ `sparsity_parameters`: A dictionary of parameters used to encode a
|
| 280 |
+
sparse tensor. This is empty if the tensor is dense.
|
| 281 |
+
"""
|
| 282 |
+
result = {}
|
| 283 |
+
for input_name, tensor_index in self._inputs.items():
|
| 284 |
+
result[input_name] = self._interpreter._get_tensor_details( # pylint: disable=protected-access
|
| 285 |
+
tensor_index, self._subgraph_index)
|
| 286 |
+
return result
|
| 287 |
+
|
| 288 |
+
def get_output_details(self):
|
| 289 |
+
"""Gets output tensor details.
|
| 290 |
+
|
| 291 |
+
Returns:
|
| 292 |
+
A dictionary from input name to tensor details where each item is a
|
| 293 |
+
dictionary with details about an output tensor. The dictionary contains
|
| 294 |
+
the same fields as described for `get_input_details()`.
|
| 295 |
+
"""
|
| 296 |
+
result = {}
|
| 297 |
+
for output_name, tensor_index in self._outputs:
|
| 298 |
+
result[output_name] = self._interpreter._get_tensor_details( # pylint: disable=protected-access
|
| 299 |
+
tensor_index, self._subgraph_index)
|
| 300 |
+
return result
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
@_tf_export('lite.experimental.OpResolverType')
|
| 304 |
+
@enum.unique
|
| 305 |
+
class OpResolverType(enum.Enum):
|
| 306 |
+
"""Different types of op resolvers for Tensorflow Lite.
|
| 307 |
+
|
| 308 |
+
* `AUTO`: Indicates the op resolver that is chosen by default in TfLite
|
| 309 |
+
Python, which is the "BUILTIN" as described below.
|
| 310 |
+
* `BUILTIN`: Indicates the op resolver for built-in ops with optimized kernel
|
| 311 |
+
implementation.
|
| 312 |
+
* `BUILTIN_REF`: Indicates the op resolver for built-in ops with reference
|
| 313 |
+
kernel implementation. It's generally used for testing and debugging.
|
| 314 |
+
* `BUILTIN_WITHOUT_DEFAULT_DELEGATES`: Indicates the op resolver for
|
| 315 |
+
built-in ops with optimized kernel implementation, but it will disable
|
| 316 |
+
the application of default TfLite delegates (like the XNNPACK delegate) to
|
| 317 |
+
the model graph. Generally this should not be used unless there are issues
|
| 318 |
+
with the default configuration.
|
| 319 |
+
"""
|
| 320 |
+
# Corresponds to an op resolver chosen by default in TfLite Python.
|
| 321 |
+
AUTO = 0
|
| 322 |
+
|
| 323 |
+
# Corresponds to tflite::ops::builtin::BuiltinOpResolver in C++.
|
| 324 |
+
BUILTIN = 1
|
| 325 |
+
|
| 326 |
+
# Corresponds to tflite::ops::builtin::BuiltinRefOpResolver in C++.
|
| 327 |
+
BUILTIN_REF = 2
|
| 328 |
+
|
| 329 |
+
# Corresponds to
|
| 330 |
+
# tflite::ops::builtin::BuiltinOpResolverWithoutDefaultDelegates in C++.
|
| 331 |
+
BUILTIN_WITHOUT_DEFAULT_DELEGATES = 3
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def _get_op_resolver_id(op_resolver_type=OpResolverType.AUTO):
|
| 335 |
+
"""Get a integer identifier for the op resolver."""
|
| 336 |
+
|
| 337 |
+
# Note: the integer identifier value needs to be same w/ op resolver ids
|
| 338 |
+
# defined in interpreter_wrapper/interpreter_wrapper.cc.
|
| 339 |
+
return {
|
| 340 |
+
# Note AUTO and BUILTIN currently share the same identifier.
|
| 341 |
+
OpResolverType.AUTO: 1,
|
| 342 |
+
OpResolverType.BUILTIN: 1,
|
| 343 |
+
OpResolverType.BUILTIN_REF: 2,
|
| 344 |
+
OpResolverType.BUILTIN_WITHOUT_DEFAULT_DELEGATES: 3
|
| 345 |
+
}.get(op_resolver_type, None)
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
@_tf_export('lite.Interpreter')
|
| 349 |
+
class Interpreter:
|
| 350 |
+
"""Interpreter interface for running TensorFlow Lite models.
|
| 351 |
+
|
| 352 |
+
Models obtained from `TfLiteConverter` can be run in Python with
|
| 353 |
+
`Interpreter`.
|
| 354 |
+
|
| 355 |
+
As an example, lets generate a simple Keras model and convert it to TFLite
|
| 356 |
+
(`TfLiteConverter` also supports other input formats with `from_saved_model`
|
| 357 |
+
and `from_concrete_function`)
|
| 358 |
+
|
| 359 |
+
>>> x = np.array([[1.], [2.]])
|
| 360 |
+
>>> y = np.array([[2.], [4.]])
|
| 361 |
+
>>> model = tf.keras.models.Sequential([
|
| 362 |
+
... tf.keras.layers.Dropout(0.2),
|
| 363 |
+
... tf.keras.layers.Dense(units=1, input_shape=[1])
|
| 364 |
+
... ])
|
| 365 |
+
>>> model.compile(optimizer='sgd', loss='mean_squared_error')
|
| 366 |
+
>>> model.fit(x, y, epochs=1)
|
| 367 |
+
>>> converter = tf.lite.TFLiteConverter.from_keras_model(model)
|
| 368 |
+
>>> tflite_model = converter.convert()
|
| 369 |
+
|
| 370 |
+
`tflite_model` can be saved to a file and loaded later, or directly into the
|
| 371 |
+
`Interpreter`. Since TensorFlow Lite pre-plans tensor allocations to optimize
|
| 372 |
+
inference, the user needs to call `allocate_tensors()` before any inference.
|
| 373 |
+
|
| 374 |
+
>>> interpreter = tf.lite.Interpreter(model_content=tflite_model)
|
| 375 |
+
>>> interpreter.allocate_tensors() # Needed before execution!
|
| 376 |
+
|
| 377 |
+
Sample execution:
|
| 378 |
+
|
| 379 |
+
>>> output = interpreter.get_output_details()[0] # Model has single output.
|
| 380 |
+
>>> input = interpreter.get_input_details()[0] # Model has single input.
|
| 381 |
+
>>> input_data = tf.constant(1., shape=[1, 1])
|
| 382 |
+
>>> interpreter.set_tensor(input['index'], input_data)
|
| 383 |
+
>>> interpreter.invoke()
|
| 384 |
+
>>> interpreter.get_tensor(output['index']).shape
|
| 385 |
+
(1, 1)
|
| 386 |
+
|
| 387 |
+
Use `get_signature_runner()` for a more user-friendly inference API.
|
| 388 |
+
"""
|
| 389 |
+
|
| 390 |
+
def __init__(
|
| 391 |
+
self,
|
| 392 |
+
model_path=None,
|
| 393 |
+
model_content=None,
|
| 394 |
+
experimental_delegates=None,
|
| 395 |
+
num_threads=None,
|
| 396 |
+
experimental_op_resolver_type=OpResolverType.AUTO,
|
| 397 |
+
experimental_preserve_all_tensors=False,
|
| 398 |
+
experimental_disable_delegate_clustering=False,
|
| 399 |
+
):
|
| 400 |
+
"""Constructor.
|
| 401 |
+
|
| 402 |
+
Args:
|
| 403 |
+
model_path: Path to TF-Lite Flatbuffer file.
|
| 404 |
+
model_content: Content of model.
|
| 405 |
+
experimental_delegates: Experimental. Subject to change. List of
|
| 406 |
+
[TfLiteDelegate](https://www.tensorflow.org/lite/performance/delegates)
|
| 407 |
+
objects returned by lite.load_delegate().
|
| 408 |
+
num_threads: Sets the number of threads used by the interpreter and
|
| 409 |
+
available to CPU kernels. If not set, the interpreter will use an
|
| 410 |
+
implementation-dependent default number of threads. Currently, only a
|
| 411 |
+
subset of kernels, such as conv, support multi-threading. num_threads
|
| 412 |
+
should be >= -1. Setting num_threads to 0 has the effect to disable
|
| 413 |
+
multithreading, which is equivalent to setting num_threads to 1. If set
|
| 414 |
+
to the value -1, the number of threads used will be
|
| 415 |
+
implementation-defined and platform-dependent.
|
| 416 |
+
experimental_op_resolver_type: The op resolver used by the interpreter. It
|
| 417 |
+
must be an instance of OpResolverType. By default, we use the built-in
|
| 418 |
+
op resolver which corresponds to tflite::ops::builtin::BuiltinOpResolver
|
| 419 |
+
in C++.
|
| 420 |
+
experimental_preserve_all_tensors: If true, then intermediate tensors used
|
| 421 |
+
during computation are preserved for inspection, and if the passed op
|
| 422 |
+
resolver type is AUTO or BUILTIN, the type will be changed to
|
| 423 |
+
BUILTIN_WITHOUT_DEFAULT_DELEGATES so that no Tensorflow Lite default
|
| 424 |
+
delegates are applied. If false, getting intermediate tensors could
|
| 425 |
+
result in undefined values or None, especially when the graph is
|
| 426 |
+
successfully modified by the Tensorflow Lite default delegate.
|
| 427 |
+
experimental_disable_delegate_clustering: If true, don't perform delegate
|
| 428 |
+
clustering during delegate graph partitioning phase. Disabling delegate
|
| 429 |
+
clustering will make the execution order of ops respect the
|
| 430 |
+
explicitly-inserted control dependencies in the graph (inserted via
|
| 431 |
+
`with tf.control_dependencies()`) since the TF Lite converter will drop
|
| 432 |
+
control dependencies by default. Most users shouldn't turn this flag to
|
| 433 |
+
True if they don't insert explicit control dependencies or the graph
|
| 434 |
+
execution order is expected. For automatically inserted control
|
| 435 |
+
dependencies (with `tf.Variable`, `tf.Print` etc), the user doesn't need
|
| 436 |
+
to turn this flag to True since they are respected by default. Note that
|
| 437 |
+
this flag is currently experimental, and it might be removed/updated if
|
| 438 |
+
the TF Lite converter doesn't drop such control dependencies in the
|
| 439 |
+
model. Default is False.
|
| 440 |
+
|
| 441 |
+
Raises:
|
| 442 |
+
ValueError: If the interpreter was unable to create.
|
| 443 |
+
"""
|
| 444 |
+
if not hasattr(self, '_custom_op_registerers'):
|
| 445 |
+
self._custom_op_registerers = []
|
| 446 |
+
|
| 447 |
+
actual_resolver_type = experimental_op_resolver_type
|
| 448 |
+
if experimental_preserve_all_tensors and (
|
| 449 |
+
experimental_op_resolver_type == OpResolverType.AUTO or
|
| 450 |
+
experimental_op_resolver_type == OpResolverType.BUILTIN):
|
| 451 |
+
actual_resolver_type = OpResolverType.BUILTIN_WITHOUT_DEFAULT_DELEGATES
|
| 452 |
+
op_resolver_id = _get_op_resolver_id(actual_resolver_type)
|
| 453 |
+
if op_resolver_id is None:
|
| 454 |
+
raise ValueError('Unrecognized passed in op resolver type: {}'.format(
|
| 455 |
+
experimental_op_resolver_type))
|
| 456 |
+
|
| 457 |
+
if model_path and not model_content:
|
| 458 |
+
custom_op_registerers_by_name = [
|
| 459 |
+
x for x in self._custom_op_registerers if isinstance(x, str)
|
| 460 |
+
]
|
| 461 |
+
custom_op_registerers_by_func = [
|
| 462 |
+
x for x in self._custom_op_registerers if not isinstance(x, str)
|
| 463 |
+
]
|
| 464 |
+
self._interpreter = _interpreter_wrapper.CreateWrapperFromFile(
|
| 465 |
+
model_path,
|
| 466 |
+
op_resolver_id,
|
| 467 |
+
custom_op_registerers_by_name,
|
| 468 |
+
custom_op_registerers_by_func,
|
| 469 |
+
experimental_preserve_all_tensors,
|
| 470 |
+
experimental_disable_delegate_clustering,
|
| 471 |
+
)
|
| 472 |
+
if not self._interpreter:
|
| 473 |
+
raise ValueError('Failed to open {}'.format(model_path))
|
| 474 |
+
elif model_content and not model_path:
|
| 475 |
+
custom_op_registerers_by_name = [
|
| 476 |
+
x for x in self._custom_op_registerers if isinstance(x, str)
|
| 477 |
+
]
|
| 478 |
+
custom_op_registerers_by_func = [
|
| 479 |
+
x for x in self._custom_op_registerers if not isinstance(x, str)
|
| 480 |
+
]
|
| 481 |
+
# Take a reference, so the pointer remains valid.
|
| 482 |
+
# Since python strings are immutable then PyString_XX functions
|
| 483 |
+
# will always return the same pointer.
|
| 484 |
+
self._model_content = model_content
|
| 485 |
+
self._interpreter = _interpreter_wrapper.CreateWrapperFromBuffer(
|
| 486 |
+
model_content,
|
| 487 |
+
op_resolver_id,
|
| 488 |
+
custom_op_registerers_by_name,
|
| 489 |
+
custom_op_registerers_by_func,
|
| 490 |
+
experimental_preserve_all_tensors,
|
| 491 |
+
experimental_disable_delegate_clustering,
|
| 492 |
+
)
|
| 493 |
+
elif not model_content and not model_path:
|
| 494 |
+
raise ValueError('`model_path` or `model_content` must be specified.')
|
| 495 |
+
else:
|
| 496 |
+
raise ValueError('Can\'t both provide `model_path` and `model_content`')
|
| 497 |
+
|
| 498 |
+
if num_threads is not None:
|
| 499 |
+
if not isinstance(num_threads, int):
|
| 500 |
+
raise ValueError('type of num_threads should be int')
|
| 501 |
+
if num_threads < 1:
|
| 502 |
+
raise ValueError('num_threads should >= 1')
|
| 503 |
+
self._interpreter.SetNumThreads(num_threads)
|
| 504 |
+
|
| 505 |
+
# Each delegate is a wrapper that owns the delegates that have been loaded
|
| 506 |
+
# as plugins. The interpreter wrapper will be using them, but we need to
|
| 507 |
+
# hold them in a list so that the lifetime is preserved at least as long as
|
| 508 |
+
# the interpreter wrapper.
|
| 509 |
+
self._delegates = []
|
| 510 |
+
if experimental_delegates:
|
| 511 |
+
self._delegates = experimental_delegates
|
| 512 |
+
for delegate in self._delegates:
|
| 513 |
+
self._interpreter.ModifyGraphWithDelegate(
|
| 514 |
+
delegate._get_native_delegate_pointer()) # pylint: disable=protected-access
|
| 515 |
+
self._signature_defs = self.get_signature_list()
|
| 516 |
+
|
| 517 |
+
self._metrics = metrics.TFLiteMetrics()
|
| 518 |
+
self._metrics.increase_counter_interpreter_creation()
|
| 519 |
+
|
| 520 |
+
def __del__(self):
|
| 521 |
+
# Must make sure the interpreter is destroyed before things that
|
| 522 |
+
# are used by it like the delegates. NOTE this only works on CPython
|
| 523 |
+
# probably.
|
| 524 |
+
# TODO(b/136468453): Remove need for __del__ ordering needs of CPython
|
| 525 |
+
# by using explicit closes(). See implementation of Interpreter __del__.
|
| 526 |
+
self._interpreter = None
|
| 527 |
+
self._delegates = None
|
| 528 |
+
|
| 529 |
+
def allocate_tensors(self):
|
| 530 |
+
self._ensure_safe()
|
| 531 |
+
return self._interpreter.AllocateTensors()
|
| 532 |
+
|
| 533 |
+
def _safe_to_run(self):
|
| 534 |
+
"""Returns true if there exist no numpy array buffers.
|
| 535 |
+
|
| 536 |
+
This means it is safe to run tflite calls that may destroy internally
|
| 537 |
+
allocated memory. This works, because in the wrapper.cc we have made
|
| 538 |
+
the numpy base be the self._interpreter.
|
| 539 |
+
"""
|
| 540 |
+
# NOTE, our tensor() call in cpp will use _interpreter as a base pointer.
|
| 541 |
+
# If this environment is the only _interpreter, then the ref count should be
|
| 542 |
+
# 2 (1 in self and 1 in temporary of sys.getrefcount).
|
| 543 |
+
return sys.getrefcount(self._interpreter) == 2
|
| 544 |
+
|
| 545 |
+
def _ensure_safe(self):
|
| 546 |
+
"""Makes sure no numpy arrays pointing to internal buffers are active.
|
| 547 |
+
|
| 548 |
+
This should be called from any function that will call a function on
|
| 549 |
+
_interpreter that may reallocate memory e.g. invoke(), ...
|
| 550 |
+
|
| 551 |
+
Raises:
|
| 552 |
+
RuntimeError: If there exist numpy objects pointing to internal memory
|
| 553 |
+
then we throw.
|
| 554 |
+
"""
|
| 555 |
+
if not self._safe_to_run():
|
| 556 |
+
raise RuntimeError("""There is at least 1 reference to internal data
|
| 557 |
+
in the interpreter in the form of a numpy array or slice. Be sure to
|
| 558 |
+
only hold the function returned from tensor() if you are using raw
|
| 559 |
+
data access.""")
|
| 560 |
+
|
| 561 |
+
# Experimental and subject to change
|
| 562 |
+
def _get_op_details(self, op_index):
|
| 563 |
+
"""Gets a dictionary with arrays of ids for tensors involved with an op.
|
| 564 |
+
|
| 565 |
+
Args:
|
| 566 |
+
op_index: Operation/node index of node to query.
|
| 567 |
+
|
| 568 |
+
Returns:
|
| 569 |
+
a dictionary containing the index, op name, and arrays with lists of the
|
| 570 |
+
indices for the inputs and outputs of the op/node.
|
| 571 |
+
"""
|
| 572 |
+
op_index = int(op_index)
|
| 573 |
+
op_name = self._interpreter.NodeName(op_index)
|
| 574 |
+
op_inputs = self._interpreter.NodeInputs(op_index)
|
| 575 |
+
op_outputs = self._interpreter.NodeOutputs(op_index)
|
| 576 |
+
|
| 577 |
+
details = {
|
| 578 |
+
'index': op_index,
|
| 579 |
+
'op_name': op_name,
|
| 580 |
+
'inputs': op_inputs,
|
| 581 |
+
'outputs': op_outputs,
|
| 582 |
+
}
|
| 583 |
+
|
| 584 |
+
return details
|
| 585 |
+
|
| 586 |
+
def _get_tensor_details(self, tensor_index, subgraph_index):
|
| 587 |
+
"""Gets tensor details.
|
| 588 |
+
|
| 589 |
+
Args:
|
| 590 |
+
tensor_index: Tensor index of tensor to query.
|
| 591 |
+
subgraph_index: Index of the subgraph.
|
| 592 |
+
|
| 593 |
+
Returns:
|
| 594 |
+
A dictionary containing the following fields of the tensor:
|
| 595 |
+
'name': The tensor name.
|
| 596 |
+
'index': The tensor index in the interpreter.
|
| 597 |
+
'shape': The shape of the tensor.
|
| 598 |
+
'quantization': Deprecated, use 'quantization_parameters'. This field
|
| 599 |
+
only works for per-tensor quantization, whereas
|
| 600 |
+
'quantization_parameters' works in all cases.
|
| 601 |
+
'quantization_parameters': The parameters used to quantize the tensor:
|
| 602 |
+
'scales': List of scales (one if per-tensor quantization)
|
| 603 |
+
'zero_points': List of zero_points (one if per-tensor quantization)
|
| 604 |
+
'quantized_dimension': Specifies the dimension of per-axis
|
| 605 |
+
quantization, in the case of multiple scales/zero_points.
|
| 606 |
+
|
| 607 |
+
Raises:
|
| 608 |
+
ValueError: If tensor_index is invalid.
|
| 609 |
+
"""
|
| 610 |
+
tensor_index = int(tensor_index)
|
| 611 |
+
subgraph_index = int(subgraph_index)
|
| 612 |
+
tensor_name = self._interpreter.TensorName(tensor_index, subgraph_index)
|
| 613 |
+
tensor_size = self._interpreter.TensorSize(tensor_index, subgraph_index)
|
| 614 |
+
tensor_size_signature = self._interpreter.TensorSizeSignature(
|
| 615 |
+
tensor_index, subgraph_index)
|
| 616 |
+
tensor_type = self._interpreter.TensorType(tensor_index, subgraph_index)
|
| 617 |
+
tensor_quantization = self._interpreter.TensorQuantization(
|
| 618 |
+
tensor_index, subgraph_index)
|
| 619 |
+
tensor_quantization_params = self._interpreter.TensorQuantizationParameters(
|
| 620 |
+
tensor_index, subgraph_index)
|
| 621 |
+
tensor_sparsity_params = self._interpreter.TensorSparsityParameters(
|
| 622 |
+
tensor_index, subgraph_index)
|
| 623 |
+
|
| 624 |
+
if not tensor_type:
|
| 625 |
+
raise ValueError('Could not get tensor details')
|
| 626 |
+
|
| 627 |
+
details = {
|
| 628 |
+
'name': tensor_name,
|
| 629 |
+
'index': tensor_index,
|
| 630 |
+
'shape': tensor_size,
|
| 631 |
+
'shape_signature': tensor_size_signature,
|
| 632 |
+
'dtype': tensor_type,
|
| 633 |
+
'quantization': tensor_quantization,
|
| 634 |
+
'quantization_parameters': {
|
| 635 |
+
'scales': tensor_quantization_params[0],
|
| 636 |
+
'zero_points': tensor_quantization_params[1],
|
| 637 |
+
'quantized_dimension': tensor_quantization_params[2],
|
| 638 |
+
},
|
| 639 |
+
'sparsity_parameters': tensor_sparsity_params
|
| 640 |
+
}
|
| 641 |
+
|
| 642 |
+
return details
|
| 643 |
+
|
| 644 |
+
# Experimental and subject to change
|
| 645 |
+
def _get_ops_details(self):
|
| 646 |
+
"""Gets op details for every node.
|
| 647 |
+
|
| 648 |
+
Returns:
|
| 649 |
+
A list of dictionaries containing arrays with lists of tensor ids for
|
| 650 |
+
tensors involved in the op.
|
| 651 |
+
"""
|
| 652 |
+
return [
|
| 653 |
+
self._get_op_details(idx) for idx in range(self._interpreter.NumNodes())
|
| 654 |
+
]
|
| 655 |
+
|
| 656 |
+
def get_tensor_details(self):
|
| 657 |
+
"""Gets tensor details for every tensor with valid tensor details.
|
| 658 |
+
|
| 659 |
+
Tensors where required information about the tensor is not found are not
|
| 660 |
+
added to the list. This includes temporary tensors without a name.
|
| 661 |
+
|
| 662 |
+
Returns:
|
| 663 |
+
A list of dictionaries containing tensor information.
|
| 664 |
+
"""
|
| 665 |
+
tensor_details = []
|
| 666 |
+
for idx in range(self._interpreter.NumTensors(0)):
|
| 667 |
+
try:
|
| 668 |
+
tensor_details.append(self._get_tensor_details(idx, subgraph_index=0))
|
| 669 |
+
except ValueError:
|
| 670 |
+
pass
|
| 671 |
+
return tensor_details
|
| 672 |
+
|
| 673 |
+
def get_input_details(self):
|
| 674 |
+
"""Gets model input tensor details.
|
| 675 |
+
|
| 676 |
+
Returns:
|
| 677 |
+
A list in which each item is a dictionary with details about
|
| 678 |
+
an input tensor. Each dictionary contains the following fields
|
| 679 |
+
that describe the tensor:
|
| 680 |
+
|
| 681 |
+
+ `name`: The tensor name.
|
| 682 |
+
+ `index`: The tensor index in the interpreter.
|
| 683 |
+
+ `shape`: The shape of the tensor.
|
| 684 |
+
+ `shape_signature`: Same as `shape` for models with known/fixed shapes.
|
| 685 |
+
If any dimension sizes are unknown, they are indicated with `-1`.
|
| 686 |
+
+ `dtype`: The numpy data type (such as `np.int32` or `np.uint8`).
|
| 687 |
+
+ `quantization`: Deprecated, use `quantization_parameters`. This field
|
| 688 |
+
only works for per-tensor quantization, whereas
|
| 689 |
+
`quantization_parameters` works in all cases.
|
| 690 |
+
+ `quantization_parameters`: A dictionary of parameters used to quantize
|
| 691 |
+
the tensor:
|
| 692 |
+
~ `scales`: List of scales (one if per-tensor quantization).
|
| 693 |
+
~ `zero_points`: List of zero_points (one if per-tensor quantization).
|
| 694 |
+
~ `quantized_dimension`: Specifies the dimension of per-axis
|
| 695 |
+
quantization, in the case of multiple scales/zero_points.
|
| 696 |
+
+ `sparsity_parameters`: A dictionary of parameters used to encode a
|
| 697 |
+
sparse tensor. This is empty if the tensor is dense.
|
| 698 |
+
"""
|
| 699 |
+
return [
|
| 700 |
+
self._get_tensor_details(i, subgraph_index=0)
|
| 701 |
+
for i in self._interpreter.InputIndices()
|
| 702 |
+
]
|
| 703 |
+
|
| 704 |
+
def set_tensor(self, tensor_index, value):
|
| 705 |
+
"""Sets the value of the input tensor.
|
| 706 |
+
|
| 707 |
+
Note this copies data in `value`.
|
| 708 |
+
|
| 709 |
+
If you want to avoid copying, you can use the `tensor()` function to get a
|
| 710 |
+
numpy buffer pointing to the input buffer in the tflite interpreter.
|
| 711 |
+
|
| 712 |
+
Args:
|
| 713 |
+
tensor_index: Tensor index of tensor to set. This value can be gotten from
|
| 714 |
+
the 'index' field in get_input_details.
|
| 715 |
+
value: Value of tensor to set.
|
| 716 |
+
|
| 717 |
+
Raises:
|
| 718 |
+
ValueError: If the interpreter could not set the tensor.
|
| 719 |
+
"""
|
| 720 |
+
self._interpreter.SetTensor(tensor_index, value)
|
| 721 |
+
|
| 722 |
+
def resize_tensor_input(self, input_index, tensor_size, strict=False):
|
| 723 |
+
"""Resizes an input tensor.
|
| 724 |
+
|
| 725 |
+
Args:
|
| 726 |
+
input_index: Tensor index of input to set. This value can be gotten from
|
| 727 |
+
the 'index' field in get_input_details.
|
| 728 |
+
tensor_size: The tensor_shape to resize the input to.
|
| 729 |
+
strict: Only unknown dimensions can be resized when `strict` is True.
|
| 730 |
+
Unknown dimensions are indicated as `-1` in the `shape_signature`
|
| 731 |
+
attribute of a given tensor. (default False)
|
| 732 |
+
|
| 733 |
+
Raises:
|
| 734 |
+
ValueError: If the interpreter could not resize the input tensor.
|
| 735 |
+
|
| 736 |
+
Usage:
|
| 737 |
+
```
|
| 738 |
+
interpreter = Interpreter(model_content=tflite_model)
|
| 739 |
+
interpreter.resize_tensor_input(0, [num_test_images, 224, 224, 3])
|
| 740 |
+
interpreter.allocate_tensors()
|
| 741 |
+
interpreter.set_tensor(0, test_images)
|
| 742 |
+
interpreter.invoke()
|
| 743 |
+
```
|
| 744 |
+
"""
|
| 745 |
+
self._ensure_safe()
|
| 746 |
+
# `ResizeInputTensor` now only accepts int32 numpy array as `tensor_size
|
| 747 |
+
# parameter.
|
| 748 |
+
tensor_size = np.array(tensor_size, dtype=np.int32)
|
| 749 |
+
self._interpreter.ResizeInputTensor(input_index, tensor_size, strict)
|
| 750 |
+
|
| 751 |
+
def get_output_details(self):
|
| 752 |
+
"""Gets model output tensor details.
|
| 753 |
+
|
| 754 |
+
Returns:
|
| 755 |
+
A list in which each item is a dictionary with details about
|
| 756 |
+
an output tensor. The dictionary contains the same fields as
|
| 757 |
+
described for `get_input_details()`.
|
| 758 |
+
"""
|
| 759 |
+
return [
|
| 760 |
+
self._get_tensor_details(i, subgraph_index=0)
|
| 761 |
+
for i in self._interpreter.OutputIndices()
|
| 762 |
+
]
|
| 763 |
+
|
| 764 |
+
def get_signature_list(self):
|
| 765 |
+
"""Gets list of SignatureDefs in the model.
|
| 766 |
+
|
| 767 |
+
Example,
|
| 768 |
+
```
|
| 769 |
+
signatures = interpreter.get_signature_list()
|
| 770 |
+
print(signatures)
|
| 771 |
+
|
| 772 |
+
# {
|
| 773 |
+
# 'add': {'inputs': ['x', 'y'], 'outputs': ['output_0']}
|
| 774 |
+
# }
|
| 775 |
+
|
| 776 |
+
Then using the names in the signature list you can get a callable from
|
| 777 |
+
get_signature_runner().
|
| 778 |
+
```
|
| 779 |
+
|
| 780 |
+
Returns:
|
| 781 |
+
A list of SignatureDef details in a dictionary structure.
|
| 782 |
+
It is keyed on the SignatureDef method name, and the value holds
|
| 783 |
+
dictionary of inputs and outputs.
|
| 784 |
+
"""
|
| 785 |
+
full_signature_defs = self._interpreter.GetSignatureDefs()
|
| 786 |
+
for _, signature_def in full_signature_defs.items():
|
| 787 |
+
signature_def['inputs'] = list(signature_def['inputs'].keys())
|
| 788 |
+
signature_def['outputs'] = list(signature_def['outputs'].keys())
|
| 789 |
+
return full_signature_defs
|
| 790 |
+
|
| 791 |
+
def _get_full_signature_list(self):
|
| 792 |
+
"""Gets list of SignatureDefs in the model.
|
| 793 |
+
|
| 794 |
+
Example,
|
| 795 |
+
```
|
| 796 |
+
signatures = interpreter._get_full_signature_list()
|
| 797 |
+
print(signatures)
|
| 798 |
+
|
| 799 |
+
# {
|
| 800 |
+
# 'add': {'inputs': {'x': 1, 'y': 0}, 'outputs': {'output_0': 4}}
|
| 801 |
+
# }
|
| 802 |
+
|
| 803 |
+
Then using the names in the signature list you can get a callable from
|
| 804 |
+
get_signature_runner().
|
| 805 |
+
```
|
| 806 |
+
|
| 807 |
+
Returns:
|
| 808 |
+
A list of SignatureDef details in a dictionary structure.
|
| 809 |
+
It is keyed on the SignatureDef method name, and the value holds
|
| 810 |
+
dictionary of inputs and outputs.
|
| 811 |
+
"""
|
| 812 |
+
return self._interpreter.GetSignatureDefs()
|
| 813 |
+
|
| 814 |
+
def get_signature_runner(self, signature_key=None):
|
| 815 |
+
"""Gets callable for inference of specific SignatureDef.
|
| 816 |
+
|
| 817 |
+
Example usage,
|
| 818 |
+
```
|
| 819 |
+
interpreter = tf.lite.Interpreter(model_content=tflite_model)
|
| 820 |
+
interpreter.allocate_tensors()
|
| 821 |
+
fn = interpreter.get_signature_runner('div_with_remainder')
|
| 822 |
+
output = fn(x=np.array([3]), y=np.array([2]))
|
| 823 |
+
print(output)
|
| 824 |
+
# {
|
| 825 |
+
# 'quotient': array([1.], dtype=float32)
|
| 826 |
+
# 'remainder': array([1.], dtype=float32)
|
| 827 |
+
# }
|
| 828 |
+
```
|
| 829 |
+
|
| 830 |
+
None can be passed for signature_key if the model has a single Signature
|
| 831 |
+
only.
|
| 832 |
+
|
| 833 |
+
All names used are this specific SignatureDef names.
|
| 834 |
+
|
| 835 |
+
|
| 836 |
+
Args:
|
| 837 |
+
signature_key: Signature key for the SignatureDef, it can be None if and
|
| 838 |
+
only if the model has a single SignatureDef. Default value is None.
|
| 839 |
+
|
| 840 |
+
Returns:
|
| 841 |
+
This returns a callable that can run inference for SignatureDef defined
|
| 842 |
+
by argument 'signature_key'.
|
| 843 |
+
The callable will take key arguments corresponding to the arguments of the
|
| 844 |
+
SignatureDef, that should have numpy values.
|
| 845 |
+
The callable will returns dictionary that maps from output names to numpy
|
| 846 |
+
values of the computed results.
|
| 847 |
+
|
| 848 |
+
Raises:
|
| 849 |
+
ValueError: If passed signature_key is invalid.
|
| 850 |
+
"""
|
| 851 |
+
if signature_key is None:
|
| 852 |
+
if len(self._signature_defs) != 1:
|
| 853 |
+
raise ValueError(
|
| 854 |
+
'SignatureDef signature_key is None and model has {0} Signatures. '
|
| 855 |
+
'None is only allowed when the model has 1 SignatureDef'.format(
|
| 856 |
+
len(self._signature_defs)))
|
| 857 |
+
else:
|
| 858 |
+
signature_key = next(iter(self._signature_defs))
|
| 859 |
+
return SignatureRunner(interpreter=self, signature_key=signature_key)
|
| 860 |
+
|
| 861 |
+
def get_tensor(self, tensor_index, subgraph_index=0):
|
| 862 |
+
"""Gets the value of the output tensor (get a copy).
|
| 863 |
+
|
| 864 |
+
If you wish to avoid the copy, use `tensor()`. This function cannot be used
|
| 865 |
+
to read intermediate results.
|
| 866 |
+
|
| 867 |
+
Args:
|
| 868 |
+
tensor_index: Tensor index of tensor to get. This value can be gotten from
|
| 869 |
+
the 'index' field in get_output_details.
|
| 870 |
+
subgraph_index: Index of the subgraph to fetch the tensor. Default value
|
| 871 |
+
is 0, which means to fetch from the primary subgraph.
|
| 872 |
+
|
| 873 |
+
Returns:
|
| 874 |
+
a numpy array.
|
| 875 |
+
"""
|
| 876 |
+
return self._interpreter.GetTensor(tensor_index, subgraph_index)
|
| 877 |
+
|
| 878 |
+
def tensor(self, tensor_index):
|
| 879 |
+
"""Returns function that gives a numpy view of the current tensor buffer.
|
| 880 |
+
|
| 881 |
+
This allows reading and writing to this tensors w/o copies. This more
|
| 882 |
+
closely mirrors the C++ Interpreter class interface's tensor() member, hence
|
| 883 |
+
the name. Be careful to not hold these output references through calls
|
| 884 |
+
to `allocate_tensors()` and `invoke()`. This function cannot be used to read
|
| 885 |
+
intermediate results.
|
| 886 |
+
|
| 887 |
+
Usage:
|
| 888 |
+
|
| 889 |
+
```
|
| 890 |
+
interpreter.allocate_tensors()
|
| 891 |
+
input = interpreter.tensor(interpreter.get_input_details()[0]["index"])
|
| 892 |
+
output = interpreter.tensor(interpreter.get_output_details()[0]["index"])
|
| 893 |
+
for i in range(10):
|
| 894 |
+
input().fill(3.)
|
| 895 |
+
interpreter.invoke()
|
| 896 |
+
print("inference %s" % output())
|
| 897 |
+
```
|
| 898 |
+
|
| 899 |
+
Notice how this function avoids making a numpy array directly. This is
|
| 900 |
+
because it is important to not hold actual numpy views to the data longer
|
| 901 |
+
than necessary. If you do, then the interpreter can no longer be invoked,
|
| 902 |
+
because it is possible the interpreter would resize and invalidate the
|
| 903 |
+
referenced tensors. The NumPy API doesn't allow any mutability of the
|
| 904 |
+
the underlying buffers.
|
| 905 |
+
|
| 906 |
+
WRONG:
|
| 907 |
+
|
| 908 |
+
```
|
| 909 |
+
input = interpreter.tensor(interpreter.get_input_details()[0]["index"])()
|
| 910 |
+
output = interpreter.tensor(interpreter.get_output_details()[0]["index"])()
|
| 911 |
+
interpreter.allocate_tensors() # This will throw RuntimeError
|
| 912 |
+
for i in range(10):
|
| 913 |
+
input.fill(3.)
|
| 914 |
+
interpreter.invoke() # this will throw RuntimeError since input,output
|
| 915 |
+
```
|
| 916 |
+
|
| 917 |
+
Args:
|
| 918 |
+
tensor_index: Tensor index of tensor to get. This value can be gotten from
|
| 919 |
+
the 'index' field in get_output_details.
|
| 920 |
+
|
| 921 |
+
Returns:
|
| 922 |
+
A function that can return a new numpy array pointing to the internal
|
| 923 |
+
TFLite tensor state at any point. It is safe to hold the function forever,
|
| 924 |
+
but it is not safe to hold the numpy array forever.
|
| 925 |
+
"""
|
| 926 |
+
return lambda: self._interpreter.tensor(self._interpreter, tensor_index)
|
| 927 |
+
|
| 928 |
+
def invoke(self):
|
| 929 |
+
"""Invoke the interpreter.
|
| 930 |
+
|
| 931 |
+
Be sure to set the input sizes, allocate tensors and fill values before
|
| 932 |
+
calling this. Also, note that this function releases the GIL so heavy
|
| 933 |
+
computation can be done in the background while the Python interpreter
|
| 934 |
+
continues. No other function on this object should be called while the
|
| 935 |
+
invoke() call has not finished.
|
| 936 |
+
|
| 937 |
+
Raises:
|
| 938 |
+
ValueError: When the underlying interpreter fails raise ValueError.
|
| 939 |
+
"""
|
| 940 |
+
self._ensure_safe()
|
| 941 |
+
self._interpreter.Invoke()
|
| 942 |
+
|
| 943 |
+
def reset_all_variables(self):
|
| 944 |
+
return self._interpreter.ResetVariableTensors()
|
| 945 |
+
|
| 946 |
+
# Experimental and subject to change.
|
| 947 |
+
def _native_handle(self):
|
| 948 |
+
"""Returns a pointer to the underlying tflite::Interpreter instance.
|
| 949 |
+
|
| 950 |
+
This allows extending tflite.Interpreter's functionality in a custom C++
|
| 951 |
+
function. Consider how that may work in a custom pybind wrapper:
|
| 952 |
+
|
| 953 |
+
m.def("SomeNewFeature", ([](py::object handle) {
|
| 954 |
+
auto* interpreter =
|
| 955 |
+
reinterpret_cast<tflite::Interpreter*>(handle.cast<intptr_t>());
|
| 956 |
+
...
|
| 957 |
+
}))
|
| 958 |
+
|
| 959 |
+
and corresponding Python call:
|
| 960 |
+
|
| 961 |
+
SomeNewFeature(interpreter.native_handle())
|
| 962 |
+
|
| 963 |
+
Note: This approach is fragile. Users must guarantee the C++ extension build
|
| 964 |
+
is consistent with the tflite.Interpreter's underlying C++ build.
|
| 965 |
+
"""
|
| 966 |
+
return self._interpreter.interpreter()
|
| 967 |
+
|
| 968 |
+
|
| 969 |
+
class InterpreterWithCustomOps(Interpreter):
|
| 970 |
+
"""Interpreter interface for TensorFlow Lite Models that accepts custom ops.
|
| 971 |
+
|
| 972 |
+
The interface provided by this class is experimental and therefore not exposed
|
| 973 |
+
as part of the public API.
|
| 974 |
+
|
| 975 |
+
Wraps the tf.lite.Interpreter class and adds the ability to load custom ops
|
| 976 |
+
by providing the names of functions that take a pointer to a BuiltinOpResolver
|
| 977 |
+
and add a custom op.
|
| 978 |
+
"""
|
| 979 |
+
|
| 980 |
+
def __init__(self, custom_op_registerers=None, **kwargs):
|
| 981 |
+
"""Constructor.
|
| 982 |
+
|
| 983 |
+
Args:
|
| 984 |
+
custom_op_registerers: List of str (symbol names) or functions that take a
|
| 985 |
+
pointer to a MutableOpResolver and register a custom op. When passing
|
| 986 |
+
functions, use a pybind function that takes a uintptr_t that can be
|
| 987 |
+
recast as a pointer to a MutableOpResolver.
|
| 988 |
+
**kwargs: Additional arguments passed to Interpreter.
|
| 989 |
+
|
| 990 |
+
Raises:
|
| 991 |
+
ValueError: If the interpreter was unable to create.
|
| 992 |
+
"""
|
| 993 |
+
self._custom_op_registerers = custom_op_registerers or []
|
| 994 |
+
super(InterpreterWithCustomOps, self).__init__(**kwargs)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/interpreter_wrapper/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/interpreter_wrapper/_pywrap_tensorflow_interpreter_wrapper.pyi
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 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 |
+
|
| 16 |
+
from typing import Any
|
| 17 |
+
|
| 18 |
+
class InterpreterWrapper:
|
| 19 |
+
def __init__(self, *args, **kwargs) -> None: ...
|
| 20 |
+
def AllocateTensors(self, subgraph_index: int = ...) -> object: ...
|
| 21 |
+
def GetSignatureDefs(self) -> object: ...
|
| 22 |
+
def GetSubgraphIndexFromSignature(self, arg0: str) -> object: ...
|
| 23 |
+
def GetTensor(self, tensor_index: int, subgraph_index: int = ...) -> object: ...
|
| 24 |
+
def InputIndices(self) -> object: ...
|
| 25 |
+
def Invoke(self, subgraph_index: int = ...) -> object: ...
|
| 26 |
+
def ModifyGraphWithDelegate(self, arg0: int) -> object: ...
|
| 27 |
+
def NodeInputs(self, arg0: int) -> object: ...
|
| 28 |
+
def NodeName(self, arg0: int) -> str: ...
|
| 29 |
+
def NodeOutputs(self, arg0: int) -> object: ...
|
| 30 |
+
def NumNodes(self) -> int: ...
|
| 31 |
+
def NumTensors(self, arg0: int) -> int: ...
|
| 32 |
+
def OutputIndices(self) -> object: ...
|
| 33 |
+
def ResetVariableTensors(self) -> object: ...
|
| 34 |
+
def ResizeInputTensor(self, i: int, value: object, strict: bool, subgraph_index: int = ...) -> object: ...
|
| 35 |
+
def SetNumThreads(self, arg0: int) -> object: ...
|
| 36 |
+
def SetTensor(self, i: int, value: object, subgraph_index: int = ...) -> object: ...
|
| 37 |
+
def TensorName(self, arg0: int, arg1: int) -> str: ...
|
| 38 |
+
def TensorQuantization(self, arg0: int, arg1: int) -> object: ...
|
| 39 |
+
def TensorQuantizationParameters(self, arg0: int, arg1: int) -> object: ...
|
| 40 |
+
def TensorSize(self, arg0: int, arg1: int) -> object: ...
|
| 41 |
+
def TensorSizeSignature(self, arg0: int, arg1: int) -> object: ...
|
| 42 |
+
def TensorSparsityParameters(self, arg0: int, arg1: int) -> object: ...
|
| 43 |
+
def TensorType(self, arg0: int, arg1: int) -> object: ...
|
| 44 |
+
def interpreter(self) -> int: ...
|
| 45 |
+
def tensor(self, base_object: object, tensor_index: int, subgraph_index: int = ...) -> object: ...
|
| 46 |
+
|
| 47 |
+
def CreateWrapperFromBuffer(*args, **kwargs) -> Any: ...
|
| 48 |
+
def CreateWrapperFromFile(*args, **kwargs) -> Any: ...
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/lite.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/lite_constants.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2018 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 |
+
"""Constants for TFLite."""
|
| 16 |
+
|
| 17 |
+
from tensorflow.lite.toco import toco_flags_pb2 as _toco_flags_pb2
|
| 18 |
+
from tensorflow.python.framework import dtypes
|
| 19 |
+
from tensorflow.python.util.all_util import remove_undocumented
|
| 20 |
+
from tensorflow.python.util.tf_export import tf_export as _tf_export
|
| 21 |
+
|
| 22 |
+
FLOAT = dtypes.float32
|
| 23 |
+
FLOAT16 = dtypes.float16
|
| 24 |
+
INT32 = dtypes.int32
|
| 25 |
+
INT64 = dtypes.int64
|
| 26 |
+
STRING = dtypes.string
|
| 27 |
+
QUANTIZED_UINT8 = dtypes.uint8
|
| 28 |
+
INT8 = dtypes.int8
|
| 29 |
+
INT16 = dtypes.int16
|
| 30 |
+
COMPLEX64 = dtypes.complex64
|
| 31 |
+
TENSORFLOW_GRAPHDEF = _toco_flags_pb2.TENSORFLOW_GRAPHDEF
|
| 32 |
+
TFLITE = _toco_flags_pb2.TFLITE
|
| 33 |
+
GRAPHVIZ_DOT = _toco_flags_pb2.GRAPHVIZ_DOT
|
| 34 |
+
|
| 35 |
+
_tf_export(v1=["lite.constants.FLOAT"]).export_constant(__name__, "FLOAT")
|
| 36 |
+
_tf_export(v1=["lite.constants.FLOAT16"]).export_constant(__name__, "FLOAT16")
|
| 37 |
+
_tf_export(v1=["lite.constants.INT32"]).export_constant(__name__, "INT32")
|
| 38 |
+
_tf_export(v1=["lite.constants.INT64"]).export_constant(__name__, "INT64")
|
| 39 |
+
_tf_export(v1=["lite.constants.STRING"]).export_constant(__name__, "STRING")
|
| 40 |
+
_tf_export(v1=["lite.constants.QUANTIZED_UINT8"]).export_constant(
|
| 41 |
+
__name__, "QUANTIZED_UINT8")
|
| 42 |
+
_tf_export(v1=["lite.constants.INT8"]).export_constant(__name__, "INT8")
|
| 43 |
+
_tf_export(v1=["lite.constants.INT16"]).export_constant(__name__, "INT16")
|
| 44 |
+
_tf_export(v1=["lite.constants.TFLITE"]).export_constant(__name__, "TFLITE")
|
| 45 |
+
_tf_export(v1=["lite.constants.GRAPHVIZ_DOT"]).export_constant(
|
| 46 |
+
__name__, "GRAPHVIZ_DOT")
|
| 47 |
+
|
| 48 |
+
# Currently the default mode of operation is to shell to another python process
|
| 49 |
+
# to protect against crashes. However, it breaks some dependent targets because
|
| 50 |
+
# it forces us to depend on an external py_binary. The experimental API doesn't
|
| 51 |
+
# have that drawback.
|
| 52 |
+
EXPERIMENTAL_USE_TOCO_API_DIRECTLY = False
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
_allowed_symbols = [
|
| 56 |
+
"FLOAT",
|
| 57 |
+
"FLOAT16",
|
| 58 |
+
"INT32",
|
| 59 |
+
"INT64",
|
| 60 |
+
"STRING",
|
| 61 |
+
"QUANTIZED_UINT8",
|
| 62 |
+
"INT8",
|
| 63 |
+
"INT16",
|
| 64 |
+
"COMPLEX64",
|
| 65 |
+
"TENSORFLOW_GRAPHDEF",
|
| 66 |
+
"TFLITE",
|
| 67 |
+
"GRAPHVIZ_DOT",
|
| 68 |
+
"EXPERIMENTAL_USE_TOCO_API_DIRECTLY",
|
| 69 |
+
]
|
| 70 |
+
remove_undocumented(__name__, _allowed_symbols)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/_pywrap_tensorflow_lite_metrics_wrapper.pyi
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 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 |
+
|
| 16 |
+
class MetricsWrapper:
|
| 17 |
+
def __init__(self, arg0: str) -> None: ...
|
| 18 |
+
def ExportMetrics(self) -> object: ...
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/converter_error_data_pb2.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Generated by the protocol buffer compiler. DO NOT EDIT!
|
| 3 |
+
# source: tensorflow/lite/python/metrics/converter_error_data.proto
|
| 4 |
+
"""Generated protocol buffer code."""
|
| 5 |
+
from google.protobuf.internal import builder as _builder
|
| 6 |
+
from google.protobuf import descriptor as _descriptor
|
| 7 |
+
from google.protobuf import descriptor_pool as _descriptor_pool
|
| 8 |
+
from google.protobuf import symbol_database as _symbol_database
|
| 9 |
+
# @@protoc_insertion_point(imports)
|
| 10 |
+
|
| 11 |
+
_sym_db = _symbol_database.Default()
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n9tensorflow/lite/python/metrics/converter_error_data.proto\x12\x0etflite.metrics\"\xdc\x06\n\x12\x43onverterErrorData\x12\x11\n\tcomponent\x18\x01 \x01(\t\x12\x14\n\x0csubcomponent\x18\x02 \x01(\t\x12@\n\nerror_code\x18\x03 \x01(\x0e\x32,.tflite.metrics.ConverterErrorData.ErrorCode\x12\x15\n\rerror_message\x18\x04 \x01(\t\x12=\n\x08operator\x18\x05 \x01(\x0b\x32+.tflite.metrics.ConverterErrorData.Operator\x12=\n\x08location\x18\x06 \x01(\x0b\x32+.tflite.metrics.ConverterErrorData.Location\x1a\x18\n\x08Operator\x12\x0c\n\x04name\x18\x01 \x01(\t\x1a\x39\n\x07\x46ileLoc\x12\x10\n\x08\x66ilename\x18\x01 \x01(\t\x12\x0c\n\x04line\x18\x02 \x01(\r\x12\x0e\n\x06\x63olumn\x18\x03 \x01(\r\x1aU\n\tSourceLoc\x12\x0c\n\x04name\x18\x01 \x01(\t\x12:\n\x06source\x18\x02 \x01(\x0b\x32*.tflite.metrics.ConverterErrorData.FileLoc\x1a\x85\x01\n\x08Location\x12=\n\x04type\x18\x01 \x01(\x0e\x32/.tflite.metrics.ConverterErrorData.LocationType\x12:\n\x04\x63\x61ll\x18\x02 \x03(\x0b\x32,.tflite.metrics.ConverterErrorData.SourceLoc\"\xc5\x01\n\tErrorCode\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x18\n\x14\x45RROR_NEEDS_FLEX_OPS\x10\x01\x12\x1a\n\x16\x45RROR_NEEDS_CUSTOM_OPS\x10\x02\x12%\n!ERROR_UNSUPPORTED_CONTROL_FLOW_V1\x10\x03\x12/\n+ERROR_STATEFUL_PARTITIONED_CALL_IN_FINAL_IR\x10\x04\x12\x1d\n\x18\x45RROR_GPU_NOT_COMPATIBLE\x10\xc8\x01\"J\n\x0cLocationType\x12\x0e\n\nUNKNOWNLOC\x10\x00\x12\x0b\n\x07NAMELOC\x10\x01\x12\x0f\n\x0b\x43\x41LLSITELOC\x10\x02\x12\x0c\n\x08\x46USEDLOC\x10\x03')
|
| 17 |
+
|
| 18 |
+
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
|
| 19 |
+
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tensorflow.lite.python.metrics.converter_error_data_pb2', globals())
|
| 20 |
+
if _descriptor._USE_C_DESCRIPTORS == False:
|
| 21 |
+
|
| 22 |
+
DESCRIPTOR._options = None
|
| 23 |
+
_CONVERTERERRORDATA._serialized_start=78
|
| 24 |
+
_CONVERTERERRORDATA._serialized_end=938
|
| 25 |
+
_CONVERTERERRORDATA_OPERATOR._serialized_start=356
|
| 26 |
+
_CONVERTERERRORDATA_OPERATOR._serialized_end=380
|
| 27 |
+
_CONVERTERERRORDATA_FILELOC._serialized_start=382
|
| 28 |
+
_CONVERTERERRORDATA_FILELOC._serialized_end=439
|
| 29 |
+
_CONVERTERERRORDATA_SOURCELOC._serialized_start=441
|
| 30 |
+
_CONVERTERERRORDATA_SOURCELOC._serialized_end=526
|
| 31 |
+
_CONVERTERERRORDATA_LOCATION._serialized_start=529
|
| 32 |
+
_CONVERTERERRORDATA_LOCATION._serialized_end=662
|
| 33 |
+
_CONVERTERERRORDATA_ERRORCODE._serialized_start=665
|
| 34 |
+
_CONVERTERERRORDATA_ERRORCODE._serialized_end=862
|
| 35 |
+
_CONVERTERERRORDATA_LOCATIONTYPE._serialized_start=864
|
| 36 |
+
_CONVERTERERRORDATA_LOCATIONTYPE._serialized_end=938
|
| 37 |
+
# @@protoc_insertion_point(module_scope)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/metrics.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Python TFLite metrics helper."""
|
| 16 |
+
import os
|
| 17 |
+
from typing import Optional, Text
|
| 18 |
+
|
| 19 |
+
# pylint: disable=g-import-not-at-top
|
| 20 |
+
if not os.path.splitext(__file__)[0].endswith(
|
| 21 |
+
os.path.join('tflite_runtime', 'metrics_portable')):
|
| 22 |
+
# This file is part of tensorflow package.
|
| 23 |
+
from tensorflow.lite.python.metrics import metrics_interface # type: ignore
|
| 24 |
+
else:
|
| 25 |
+
# This file is part of tflite_runtime package.
|
| 26 |
+
from tflite_runtime import metrics_interface # type: ignore
|
| 27 |
+
# pylint: enable=g-import-not-at-top
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class TFLiteMetrics(metrics_interface.TFLiteMetricsInterface):
|
| 31 |
+
"""TFLite metrics helper."""
|
| 32 |
+
|
| 33 |
+
def __init__(self,
|
| 34 |
+
model_hash: Optional[Text] = None,
|
| 35 |
+
model_path: Optional[Text] = None) -> None:
|
| 36 |
+
pass
|
| 37 |
+
|
| 38 |
+
def increase_counter_debugger_creation(self):
|
| 39 |
+
pass
|
| 40 |
+
|
| 41 |
+
def increase_counter_interpreter_creation(self):
|
| 42 |
+
pass
|
| 43 |
+
|
| 44 |
+
def increase_counter_converter_attempt(self):
|
| 45 |
+
pass
|
| 46 |
+
|
| 47 |
+
def increase_counter_converter_success(self):
|
| 48 |
+
pass
|
| 49 |
+
|
| 50 |
+
def set_converter_param(self, name, value):
|
| 51 |
+
pass
|
| 52 |
+
|
| 53 |
+
def set_converter_error(self, error_data):
|
| 54 |
+
pass
|
| 55 |
+
|
| 56 |
+
def set_converter_latency(self, value):
|
| 57 |
+
pass
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class TFLiteConverterMetrics(TFLiteMetrics):
|
| 61 |
+
"""Similar to TFLiteMetrics but specialized for converter."""
|
| 62 |
+
|
| 63 |
+
def __del__(self):
|
| 64 |
+
pass
|
| 65 |
+
|
| 66 |
+
def set_export_required(self):
|
| 67 |
+
pass
|
| 68 |
+
|
| 69 |
+
def export_metrics(self):
|
| 70 |
+
pass
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/metrics_interface.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Python TFLite metrics helper interface."""
|
| 16 |
+
import abc
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class TFLiteMetricsInterface(metaclass=abc.ABCMeta):
|
| 20 |
+
"""Abstract class for TFLiteMetrics."""
|
| 21 |
+
|
| 22 |
+
@abc.abstractmethod
|
| 23 |
+
def increase_counter_debugger_creation(self):
|
| 24 |
+
raise NotImplementedError
|
| 25 |
+
|
| 26 |
+
@abc.abstractmethod
|
| 27 |
+
def increase_counter_interpreter_creation(self):
|
| 28 |
+
raise NotImplementedError
|
| 29 |
+
|
| 30 |
+
@abc.abstractmethod
|
| 31 |
+
def increase_counter_converter_attempt(self):
|
| 32 |
+
raise NotImplementedError
|
| 33 |
+
|
| 34 |
+
@abc.abstractmethod
|
| 35 |
+
def increase_counter_converter_success(self):
|
| 36 |
+
raise NotImplementedError
|
| 37 |
+
|
| 38 |
+
@abc.abstractmethod
|
| 39 |
+
def set_converter_param(self, name, value):
|
| 40 |
+
raise NotImplementedError
|
| 41 |
+
|
| 42 |
+
@abc.abstractmethod
|
| 43 |
+
def set_converter_error(self, error_data):
|
| 44 |
+
raise NotImplementedError
|
| 45 |
+
|
| 46 |
+
@abc.abstractmethod
|
| 47 |
+
def set_converter_latency(self, value):
|
| 48 |
+
raise NotImplementedError
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/wrapper/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/wrapper/metrics_wrapper.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Stub to make pywrap metrics wrapper accessible."""
|
| 16 |
+
|
| 17 |
+
from tensorflow.lite.python import wrap_toco
|
| 18 |
+
from tensorflow.lite.python.metrics import converter_error_data_pb2
|
| 19 |
+
from tensorflow.lite.python.metrics._pywrap_tensorflow_lite_metrics_wrapper import MetricsWrapper # pylint: disable=unused-import
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def retrieve_collected_errors():
|
| 23 |
+
"""Returns and clears the list of collected errors in ErrorCollector.
|
| 24 |
+
|
| 25 |
+
The RetrieveCollectedErrors function in C++ returns a list of serialized proto
|
| 26 |
+
messages. This function will convert them to ConverterErrorData instances.
|
| 27 |
+
|
| 28 |
+
Returns:
|
| 29 |
+
A list of ConverterErrorData.
|
| 30 |
+
"""
|
| 31 |
+
serialized_message_list = wrap_toco.wrapped_retrieve_collected_errors()
|
| 32 |
+
return list(
|
| 33 |
+
map(converter_error_data_pb2.ConverterErrorData.FromString,
|
| 34 |
+
serialized_message_list))
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2017 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 |
+
"""Define tflite op hints (intrinsic operations).
|
| 16 |
+
|
| 17 |
+
This essentially allows defining a TensorFlow API for tflite operations in
|
| 18 |
+
Python with hints on how they are represented in TensorFlow Lite. This basically
|
| 19 |
+
is a form of tflite intrinsic. It wraps a subpart of a TensorFlow execution
|
| 20 |
+
graph and is useful for LSTMs and other complicated TensorFlow constructions
|
| 21 |
+
that are difficult to pattern match in TOCO, but are represented by a single
|
| 22 |
+
accelerated tflite op.
|
| 23 |
+
|
| 24 |
+
Example:
|
| 25 |
+
def tflite_cool_activation(input):
|
| 26 |
+
# A cool activation function.
|
| 27 |
+
custom = tf.lite.OpHint("cool_activation")
|
| 28 |
+
input, = custom.add_inputs(input)
|
| 29 |
+
output = tf.sigmoid(input) * input
|
| 30 |
+
output, = custom.add_outputs(output)
|
| 31 |
+
return output
|
| 32 |
+
|
| 33 |
+
image = tf.compat.v1.placeholder(tf.float32, (1, 16, 16, 1))
|
| 34 |
+
output = tf.identity(tflite_cool_activation(image))
|
| 35 |
+
|
| 36 |
+
session = tf.compat.v1.Session()
|
| 37 |
+
|
| 38 |
+
graphdef_to_convert = tf.lite.experimental.convert_op_hints_to_stubs(session)
|
| 39 |
+
tflite_graph = tf.compat.v1.lite.toco_convert(
|
| 40 |
+
graphdef_to_convert, [image], [output], allow_custom_ops=True)
|
| 41 |
+
with open("/tmp/graph.fb", "wb") as fp:
|
| 42 |
+
fp.write(tflite_graph)
|
| 43 |
+
|
| 44 |
+
How does it work?:
|
| 45 |
+
|
| 46 |
+
OpHint is a helper that you use when defining a vanilla python function.
|
| 47 |
+
It allows you to wrap arguments with tf.identities with some custom attributes.
|
| 48 |
+
These attributes allow you to find the original block of ops that was created.
|
| 49 |
+
For example, if you use cool_activation above you essentially get:
|
| 50 |
+
|
| 51 |
+
a_input = tf.identity()
|
| 52 |
+
result = tf.multiply(tf.sigmoid(a_input), a_input)
|
| 53 |
+
output = tf.identity()
|
| 54 |
+
|
| 55 |
+
a_input, output are identities that have parameters representing
|
| 56 |
+
what argument they are, what the name of the function they should turn into
|
| 57 |
+
in tf lite as well as a guid that uniquely identifies a particular invocation.
|
| 58 |
+
|
| 59 |
+
Once you have built your whole tensorflow graph, you can run it and train it
|
| 60 |
+
as usual, but after you have done that, you need to convert the graph into
|
| 61 |
+
a form that replaces these subgraphs wrapped in identities to stub ops. These
|
| 62 |
+
ops don't actually exist in the normal TensorFlow runtime, but will be
|
| 63 |
+
understood by toco later. The generated TensorFlow Lite flatbuffer file will
|
| 64 |
+
contain a custom operator called "cool_activation". Developer needs to implement
|
| 65 |
+
and register this operator in TensorFlow Lite in order to do inference.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
import collections as _collections
|
| 69 |
+
import copy as _copy
|
| 70 |
+
import json as _json
|
| 71 |
+
import uuid as _uuid
|
| 72 |
+
|
| 73 |
+
from tensorflow.core.framework import attr_value_pb2 as _attr_value_pb2
|
| 74 |
+
from tensorflow.core.framework import graph_pb2 as _graph_pb2
|
| 75 |
+
from tensorflow.core.framework import node_def_pb2 as _node_def_pb2
|
| 76 |
+
from tensorflow.python.framework import dtypes as _dtypes
|
| 77 |
+
from tensorflow.python.framework import ops as _ops
|
| 78 |
+
from tensorflow.python.framework import tensor_util as _tensor_util
|
| 79 |
+
from tensorflow.python.framework.graph_util_impl import _bfs_for_reachable_nodes
|
| 80 |
+
from tensorflow.python.framework.graph_util_impl import _extract_graph_summary
|
| 81 |
+
from tensorflow.python.ops import array_ops as _array_ops
|
| 82 |
+
from tensorflow.python.util import compat as _compat
|
| 83 |
+
from tensorflow.python.util import deprecation as _deprecation
|
| 84 |
+
from tensorflow.python.util.all_util import remove_undocumented
|
| 85 |
+
from tensorflow.python.util.tf_export import tf_export as _tf_export
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
@_tf_export(v1=["lite.OpHint"])
|
| 89 |
+
@_deprecation.deprecated(
|
| 90 |
+
None,
|
| 91 |
+
"Please follow instructions under "
|
| 92 |
+
"https://www.tensorflow.org/lite/convert/operation_fusion for operation"
|
| 93 |
+
"fusion in tflite."
|
| 94 |
+
)
|
| 95 |
+
class OpHint:
|
| 96 |
+
"""A class that helps build tflite function invocations.
|
| 97 |
+
|
| 98 |
+
It allows you to take a bunch of TensorFlow ops and annotate the construction
|
| 99 |
+
such that toco knows how to convert it to tflite. This embeds a pseudo
|
| 100 |
+
function in a TensorFlow graph. This allows embedding high-level API usage
|
| 101 |
+
information in a lower level TensorFlow implementation so that an alternative
|
| 102 |
+
implementation can be substituted later.
|
| 103 |
+
|
| 104 |
+
Essentially, any "input" into this pseudo op is fed into an identity, and
|
| 105 |
+
attributes are added to that input before being used by the constituent ops
|
| 106 |
+
that make up the pseudo op. A similar process is done to any output that
|
| 107 |
+
is to be exported from the current op.
|
| 108 |
+
|
| 109 |
+
"""
|
| 110 |
+
# Attr constants that are used for representation in the GraphDef. These
|
| 111 |
+
# will be used on every Identity op that is involved in a total OpHint.
|
| 112 |
+
|
| 113 |
+
# Name of the OpHint function (cosmetic).
|
| 114 |
+
FUNCTION_NAME_ATTR = "_tflite_function_name"
|
| 115 |
+
# UUID of the function (each OpHint gets a new uuid).
|
| 116 |
+
FUNCTION_UUID_ATTR = "_tflite_function_uuid"
|
| 117 |
+
# The input index of the input (or nothing if it is an output).
|
| 118 |
+
FUNCTION_INPUT_INDEX_ATTR = "_tflite_function_input_index"
|
| 119 |
+
# The output index of the output (or nothing if it is an input).
|
| 120 |
+
FUNCTION_OUTPUT_INDEX_ATTR = "_tflite_function_output_index"
|
| 121 |
+
# An index that orders aggregate arguments. Aggregate arguments are ones
|
| 122 |
+
# that are separate but will be fused horizontally. For example a static LSTM
|
| 123 |
+
# has a lstm cell for each time step. Each one has a separate opHint, but a
|
| 124 |
+
# fused SequentialLSTM will treat this as a single tensor.
|
| 125 |
+
FUNCTION_SORT_INDEX_ATTR = "_tflite_function_sort_index"
|
| 126 |
+
# The way in which multiple parts of the aggregate argument will be joined
|
| 127 |
+
# into a fused operand. Valid options are OpHint.AGGREGATE_FIRST,
|
| 128 |
+
# OpHint.AGGREGATE_LAST, OpHint.AGGREGATE_STACK.
|
| 129 |
+
FUNCTION_AGGREGATE_ATTR = "_tflite_function_aggregate"
|
| 130 |
+
# On fused OpHint stub, the order of inputs that the final LSTM call will
|
| 131 |
+
# have. What this means is that the TensorFlow order might be
|
| 132 |
+
# "foo", "bar", "stuff" and you might want the TF lite op order to be
|
| 133 |
+
# "stuff", "foo", "bar", -1 (where -1 is unused). So you would set this
|
| 134 |
+
# attribute to [2, 0, 1, -1].
|
| 135 |
+
TFLITE_INPUT_INDICES = "_tflite_input_indices"
|
| 136 |
+
# OpHint level.
|
| 137 |
+
FUNCTION_LEVEL_ATTR = "_tflite_ophint_level"
|
| 138 |
+
# Ophint internal mapping, this is for high level Ophint only.
|
| 139 |
+
# This basically contains three kinds of mapping:
|
| 140 |
+
# 1) How parental ophinted inputs map to the first child ophinted inputs;
|
| 141 |
+
# 2) How internal children nodes are connected;
|
| 142 |
+
# 3) How parental ophinted outputs map to the last child ophinted outputs.
|
| 143 |
+
CHILDREN_INPUTS_MAPPINGS = "_tflite_children_ophint_inputs_mapping"
|
| 144 |
+
|
| 145 |
+
# Types of aggregations
|
| 146 |
+
# stack: stacks all ophints with matching tags. i.e. for a static rnn.
|
| 147 |
+
# specifically, this is good for an input or output to a static rnn cell.
|
| 148 |
+
AGGREGATE_STACK = "stack"
|
| 149 |
+
# first: only takes the first output (one with lowest sort index)
|
| 150 |
+
# of matching tags. This is good for the input state to an RNN.
|
| 151 |
+
AGGREGATE_FIRST = "first"
|
| 152 |
+
# aggregation last takes only the last tag (one with highest sort index).
|
| 153 |
+
# This is good for an output value on the last stack item of a
|
| 154 |
+
# static rnn.
|
| 155 |
+
AGGREGATE_LAST = "last"
|
| 156 |
+
|
| 157 |
+
class OpHintArgumentTracker:
|
| 158 |
+
"""Conceptually tracks indices of arguments of "OpHint functions".
|
| 159 |
+
|
| 160 |
+
The inputs and arguments of these functions both use an instance
|
| 161 |
+
of the class so they can have independent numbering.
|
| 162 |
+
"""
|
| 163 |
+
|
| 164 |
+
def __init__(self,
|
| 165 |
+
function_name,
|
| 166 |
+
unique_function_id,
|
| 167 |
+
node_name_prefix,
|
| 168 |
+
attr_name,
|
| 169 |
+
level=1,
|
| 170 |
+
children_inputs_mappings=None):
|
| 171 |
+
"""Initialize ophint argument.
|
| 172 |
+
|
| 173 |
+
Args:
|
| 174 |
+
function_name: Name of the function that this tracks arguments for.
|
| 175 |
+
unique_function_id: UUID of function that this tracks arguments for.
|
| 176 |
+
node_name_prefix: How identities that are created are named.
|
| 177 |
+
attr_name: Name of attribute to use to store the index for this hint.
|
| 178 |
+
i.e. FUNCTION_INPUT_INDEX or FUNCTION_OUTPUT_INDEX
|
| 179 |
+
level: Hierarchical level of the Ophint node, a number.
|
| 180 |
+
children_inputs_mappings: Inputs/Outputs mapping for children hints.
|
| 181 |
+
"""
|
| 182 |
+
|
| 183 |
+
# The global index is the argument index of the op. This is in contrast
|
| 184 |
+
# to the sort index which is the sequence number of a particular instance
|
| 185 |
+
# of a given global index. For example, you may have called add hint
|
| 186 |
+
# twice with the tag "foo". Then the global index will be 0 for both
|
| 187 |
+
# and the sort index will be 0 for the first added and 1 for the second.
|
| 188 |
+
self._function_name = function_name
|
| 189 |
+
self._unique_function_id = unique_function_id
|
| 190 |
+
self._next_global_index = 0 # The absolute global index
|
| 191 |
+
self._used_global_indices = set()
|
| 192 |
+
self._tag_to_global_index = {} # The argument index a given tag maps to
|
| 193 |
+
self._tag_to_next_sort_index = {} # The current index for each tag
|
| 194 |
+
self._node_name_prefix = node_name_prefix
|
| 195 |
+
self._attr_name = attr_name
|
| 196 |
+
self._level = level
|
| 197 |
+
self._children_inputs_mappings = children_inputs_mappings
|
| 198 |
+
|
| 199 |
+
def _get_new_global_index(self, index_override):
|
| 200 |
+
"""Return the next unused argument index in order or use an override.
|
| 201 |
+
|
| 202 |
+
Args:
|
| 203 |
+
index_override: An index to use instead of the next available or None
|
| 204 |
+
to use the next available.
|
| 205 |
+
|
| 206 |
+
Returns:
|
| 207 |
+
A valid global_index to use for the next hint argument.
|
| 208 |
+
|
| 209 |
+
Raises:
|
| 210 |
+
ValueError: If the index_override is already used by another hint.
|
| 211 |
+
"""
|
| 212 |
+
if index_override is None:
|
| 213 |
+
global_index = self._next_global_index
|
| 214 |
+
else:
|
| 215 |
+
if index_override in self._used_global_indices:
|
| 216 |
+
raise ValueError("Index %d was already used by another call to add")
|
| 217 |
+
global_index = index_override
|
| 218 |
+
# Make next_global_index valid
|
| 219 |
+
self._used_global_indices.add(global_index)
|
| 220 |
+
while self._next_global_index in self._used_global_indices:
|
| 221 |
+
self._next_global_index += 1
|
| 222 |
+
return global_index
|
| 223 |
+
|
| 224 |
+
def add(self, arg, tag=None, name=None, aggregate=None,
|
| 225 |
+
index_override=None):
|
| 226 |
+
"""Return a wrapped tensor of an input tensor as an argument.
|
| 227 |
+
|
| 228 |
+
Args:
|
| 229 |
+
arg: A TensorFlow tensor that should be considered an argument.
|
| 230 |
+
tag: String tag to identify arguments that should be packed.
|
| 231 |
+
name: Name of argument. This is included in the Identity hint op names.
|
| 232 |
+
aggregate: Strategy to aggregate.
|
| 233 |
+
Acceptable values are OpHint.AGGREGATE_FIRST, OpHint.AGGREGATE_LAST,
|
| 234 |
+
and OpHint.AGGREGATE_STACK.
|
| 235 |
+
Note, aggregate is only valid if tag is specified.
|
| 236 |
+
index_override: Specify what input/output index should this be in the
|
| 237 |
+
final stub. i.e. add(arg0, index=1); add(arg1, index=0) will make the
|
| 238 |
+
final stub be as stub_func(inputs[arg1, arg0], outputs=[]) rather than
|
| 239 |
+
the default call order based ordering.
|
| 240 |
+
|
| 241 |
+
Returns:
|
| 242 |
+
A tensor representing the wrapped argument.
|
| 243 |
+
|
| 244 |
+
Raises:
|
| 245 |
+
ValueError: When indices are not consistent.
|
| 246 |
+
"""
|
| 247 |
+
|
| 248 |
+
# Find the appropriate index
|
| 249 |
+
if tag is None:
|
| 250 |
+
if aggregate is not None:
|
| 251 |
+
raise ValueError("You must specify `tag` if using aggregate.")
|
| 252 |
+
global_index = self._get_new_global_index(index_override)
|
| 253 |
+
sort_index = None
|
| 254 |
+
else:
|
| 255 |
+
if aggregate is None:
|
| 256 |
+
raise ValueError("You must specify `aggregate` if using tag.")
|
| 257 |
+
if tag not in self._tag_to_global_index:
|
| 258 |
+
self._tag_to_global_index[tag] = (
|
| 259 |
+
self._get_new_global_index(index_override))
|
| 260 |
+
self._tag_to_next_sort_index[tag] = 0
|
| 261 |
+
elif (index_override and
|
| 262 |
+
index_override != self._tag_to_global_index[tag]):
|
| 263 |
+
raise ValueError(
|
| 264 |
+
"Tag %r was called with two indices %r and %r" %
|
| 265 |
+
(tag, index_override, self._tag_to_global_index[tag]))
|
| 266 |
+
global_index = self._tag_to_global_index[tag]
|
| 267 |
+
sort_index = self._tag_to_next_sort_index[tag]
|
| 268 |
+
self._tag_to_next_sort_index[tag] += 1
|
| 269 |
+
|
| 270 |
+
uuid = self._unique_function_id
|
| 271 |
+
name = "%s-%s-%s-%r-%r-%s" % (self._node_name_prefix, self._function_name,
|
| 272 |
+
uuid, global_index, sort_index, name)
|
| 273 |
+
|
| 274 |
+
identity_op = _array_ops.identity(arg, name=name)
|
| 275 |
+
|
| 276 |
+
# pylint: disable=protected-access
|
| 277 |
+
identity_op.op._set_attr(
|
| 278 |
+
OpHint.FUNCTION_NAME_ATTR,
|
| 279 |
+
_attr_value_pb2.AttrValue(
|
| 280 |
+
s=_compat.as_bytes(self._function_name)))
|
| 281 |
+
identity_op.op._set_attr(
|
| 282 |
+
OpHint.FUNCTION_UUID_ATTR,
|
| 283 |
+
_attr_value_pb2.AttrValue(
|
| 284 |
+
s=_compat.as_bytes(self._unique_function_id)))
|
| 285 |
+
identity_op.op._set_attr(
|
| 286 |
+
self._attr_name, _attr_value_pb2.AttrValue(i=global_index))
|
| 287 |
+
identity_op.op._set_attr(OpHint.FUNCTION_LEVEL_ATTR,
|
| 288 |
+
_attr_value_pb2.AttrValue(i=self._level))
|
| 289 |
+
if self._children_inputs_mappings:
|
| 290 |
+
identity_op.op._set_attr(
|
| 291 |
+
OpHint.CHILDREN_INPUTS_MAPPINGS,
|
| 292 |
+
_attr_value_pb2.AttrValue(
|
| 293 |
+
s=_compat.as_bytes(_json.dumps(
|
| 294 |
+
self._children_inputs_mappings))))
|
| 295 |
+
|
| 296 |
+
if sort_index is not None:
|
| 297 |
+
identity_op.op._set_attr(
|
| 298 |
+
OpHint.FUNCTION_SORT_INDEX_ATTR,
|
| 299 |
+
_attr_value_pb2.AttrValue(i=sort_index))
|
| 300 |
+
if aggregate is not None:
|
| 301 |
+
identity_op.op._set_attr(
|
| 302 |
+
OpHint.FUNCTION_AGGREGATE_ATTR,
|
| 303 |
+
_attr_value_pb2.AttrValue(s=_compat.as_bytes((aggregate))))
|
| 304 |
+
# pylint: enable=protected-access
|
| 305 |
+
return identity_op
|
| 306 |
+
|
| 307 |
+
def __init__(self,
|
| 308 |
+
function_name,
|
| 309 |
+
level=1,
|
| 310 |
+
children_inputs_mappings=None,
|
| 311 |
+
**kwargs):
|
| 312 |
+
"""Create a OpHint.
|
| 313 |
+
|
| 314 |
+
Args:
|
| 315 |
+
function_name: Name of the function (the custom op name in tflite)
|
| 316 |
+
level: OpHint level.
|
| 317 |
+
children_inputs_mappings: Children OpHint inputs/outputs mapping.
|
| 318 |
+
children_inputs_mappings should like below:
|
| 319 |
+
"parent_first_child_input":
|
| 320 |
+
[{"parent_input_index": num, "child_input_index": num}, ...]
|
| 321 |
+
"parent_last_child_output":
|
| 322 |
+
[{"parent_output_index": num, "child_output_index": num}, ...]
|
| 323 |
+
"internal_children_input_output":
|
| 324 |
+
[{"child_input_index": num, "child_output_index": num}, ...]
|
| 325 |
+
**kwargs: Keyword arguments of any constant attributes for the function.
|
| 326 |
+
"""
|
| 327 |
+
self._function_name = function_name
|
| 328 |
+
self._level = level
|
| 329 |
+
if self._level == 1:
|
| 330 |
+
assert children_inputs_mappings is None
|
| 331 |
+
else:
|
| 332 |
+
assert isinstance(children_inputs_mappings, dict)
|
| 333 |
+
self._children_inputs_mappings = children_inputs_mappings
|
| 334 |
+
if self._children_inputs_mappings is not None:
|
| 335 |
+
self._validate_children_inputs_mappings(self._children_inputs_mappings)
|
| 336 |
+
self._unique_function_id = _uuid.uuid1().hex
|
| 337 |
+
self._attrs_to_store_later = kwargs
|
| 338 |
+
self._stored_attrs = False
|
| 339 |
+
self._inputs = OpHint.OpHintArgumentTracker(
|
| 340 |
+
self._function_name, self._unique_function_id, "InputHint",
|
| 341 |
+
OpHint.FUNCTION_INPUT_INDEX_ATTR, level, self._children_inputs_mappings)
|
| 342 |
+
self._outputs = OpHint.OpHintArgumentTracker(
|
| 343 |
+
self._function_name, self._unique_function_id, "OutputHint",
|
| 344 |
+
OpHint.FUNCTION_OUTPUT_INDEX_ATTR, level,
|
| 345 |
+
self._children_inputs_mappings)
|
| 346 |
+
|
| 347 |
+
def _validate_children_inputs_mappings(self, children_inputs_mappings):
|
| 348 |
+
"""Validate children inputs mappings is in the right format.
|
| 349 |
+
|
| 350 |
+
Args:
|
| 351 |
+
children_inputs_mappings: the Children ophint inputs/outputs mapping.
|
| 352 |
+
"""
|
| 353 |
+
assert isinstance(children_inputs_mappings, dict)
|
| 354 |
+
assert "parent_first_child_input" in children_inputs_mappings
|
| 355 |
+
assert "parent_last_child_output" in children_inputs_mappings
|
| 356 |
+
assert "internal_children_input_output" in children_inputs_mappings
|
| 357 |
+
|
| 358 |
+
# validate parent_first_child_input.
|
| 359 |
+
|
| 360 |
+
def assert_dictlist_has_keys(dictlist, keys):
|
| 361 |
+
for dikt in dictlist:
|
| 362 |
+
assert isinstance(dikt, dict)
|
| 363 |
+
for key in keys:
|
| 364 |
+
assert key in dikt
|
| 365 |
+
|
| 366 |
+
assert_dictlist_has_keys(
|
| 367 |
+
children_inputs_mappings["parent_first_child_input"],
|
| 368 |
+
["parent_ophint_input_index", "first_child_ophint_input_index"])
|
| 369 |
+
assert_dictlist_has_keys(
|
| 370 |
+
children_inputs_mappings["parent_last_child_output"],
|
| 371 |
+
["parent_output_index", "child_output_index"])
|
| 372 |
+
assert_dictlist_has_keys(
|
| 373 |
+
children_inputs_mappings["internal_children_input_output"],
|
| 374 |
+
["child_input_index", "child_output_index"])
|
| 375 |
+
|
| 376 |
+
def _setattr(self, dest_op, name, value):
|
| 377 |
+
tensor_value = _ops.convert_to_tensor(value)
|
| 378 |
+
# pylint: disable=protected-access
|
| 379 |
+
dest_op.op._set_attr(name, _attr_value_pb2.AttrValue(
|
| 380 |
+
tensor=tensor_value.op.node_def.attr["value"].tensor))
|
| 381 |
+
# pylint: enable=protected-access
|
| 382 |
+
|
| 383 |
+
def add_input(self, *args, **kwargs):
|
| 384 |
+
"""Add a wrapped input argument to the hint.
|
| 385 |
+
|
| 386 |
+
Args:
|
| 387 |
+
*args: The input tensor.
|
| 388 |
+
**kwargs:
|
| 389 |
+
"name" label
|
| 390 |
+
"tag" a tag to group multiple arguments that will be aggregated. I.e.
|
| 391 |
+
a string like 'cool_input'. Basically multiple inputs can be added
|
| 392 |
+
to the same hint for parallel operations that will eventually be
|
| 393 |
+
combined. An example would be static_rnn which creates multiple copies
|
| 394 |
+
of state or inputs.
|
| 395 |
+
"aggregate" aggregation strategy that is valid only for tag non None.
|
| 396 |
+
Acceptable values are OpHint.AGGREGATE_FIRST, OpHint.AGGREGATE_LAST,
|
| 397 |
+
and OpHint.AGGREGATE_STACK.
|
| 398 |
+
"index_override" The global index to use. This corresponds to the
|
| 399 |
+
argument order in the final stub that will be generated.
|
| 400 |
+
Returns:
|
| 401 |
+
The wrapped input tensor.
|
| 402 |
+
"""
|
| 403 |
+
return self._inputs.add(*args, **kwargs)
|
| 404 |
+
|
| 405 |
+
def add_output(self, *args, **kwargs):
|
| 406 |
+
"""Add a wrapped output argument to the hint.
|
| 407 |
+
|
| 408 |
+
Args:
|
| 409 |
+
*args: The output tensor.
|
| 410 |
+
**kwargs:
|
| 411 |
+
"name" label
|
| 412 |
+
"tag" a tag to group multiple arguments that will be aggregated. I.e.
|
| 413 |
+
a string like 'cool_input'. Basically multiple inputs can be added
|
| 414 |
+
to the same hint for parallel operations that will eventually be
|
| 415 |
+
combined. An example would be static_rnn which creates multiple copies
|
| 416 |
+
of state or inputs.
|
| 417 |
+
"aggregate" aggregation strategy that is valid only for tag non None.
|
| 418 |
+
Acceptable values are OpHint.AGGREGATE_FIRST, OpHint.AGGREGATE_LAST,
|
| 419 |
+
and OpHint.AGGREGATE_STACK.
|
| 420 |
+
"index_override" The global index to use. This corresponds to the
|
| 421 |
+
argument order in the final stub that will be generated.
|
| 422 |
+
Returns:
|
| 423 |
+
The wrapped output tensor.
|
| 424 |
+
"""
|
| 425 |
+
return self._outputs.add(*args, **kwargs)
|
| 426 |
+
|
| 427 |
+
def add_inputs(self, *args, **kwargs):
|
| 428 |
+
"""Add a sequence of inputs to the function invocation.
|
| 429 |
+
|
| 430 |
+
Args:
|
| 431 |
+
*args: List of inputs to be converted (should be Tf.Tensor).
|
| 432 |
+
**kwargs: This allows 'names' which should be a list of names.
|
| 433 |
+
|
| 434 |
+
Returns:
|
| 435 |
+
Wrapped inputs (identity standins that have additional metadata). These
|
| 436 |
+
are also are also tf.Tensor's.
|
| 437 |
+
"""
|
| 438 |
+
if "names" in kwargs:
|
| 439 |
+
return [
|
| 440 |
+
self._inputs.add(arg, name=name)
|
| 441 |
+
for arg, name in zip(args, kwargs["names"])
|
| 442 |
+
]
|
| 443 |
+
else:
|
| 444 |
+
return [self._inputs.add(arg) for arg in args]
|
| 445 |
+
|
| 446 |
+
def add_outputs(self, *args, **kwargs):
|
| 447 |
+
"""Add a sequence of outputs to the function invocation.
|
| 448 |
+
|
| 449 |
+
Args:
|
| 450 |
+
*args: List of outputs to be converted (should be tf.Tensor).
|
| 451 |
+
**kwargs: See
|
| 452 |
+
|
| 453 |
+
Returns:
|
| 454 |
+
Wrapped outputs (identity standins that have additional metadata). These
|
| 455 |
+
are also tf.Tensor's.
|
| 456 |
+
"""
|
| 457 |
+
if "names" in kwargs:
|
| 458 |
+
return [
|
| 459 |
+
self._outputs.add(arg, name=name)
|
| 460 |
+
for arg, name in zip(args, kwargs["names"])
|
| 461 |
+
]
|
| 462 |
+
else:
|
| 463 |
+
return [self._outputs.add(arg) for arg in args]
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
class _LiteOperand:
|
| 467 |
+
"""Abstract operand for a tflite hint function._dynamic_rnn_loop.
|
| 468 |
+
|
| 469 |
+
This is a base class that handles representing arguments to an OpHint.
|
| 470 |
+
It also is able to serialize operands to the stubbed graph_def.
|
| 471 |
+
Child classes are responsible for being able to
|
| 472 |
+
store information about the hint identity operators. They are also responsible
|
| 473 |
+
for knowing how to serialize to output graphdefs.
|
| 474 |
+
|
| 475 |
+
Typically this will be implemented by holding one or more identity nodes
|
| 476 |
+
that were previously discovered as hints.
|
| 477 |
+
"""
|
| 478 |
+
|
| 479 |
+
def aggregate_and_return_name_for_input(self, out_graphdef):
|
| 480 |
+
"""This adds the node(s) to out_graphdef and returns the input node name.
|
| 481 |
+
|
| 482 |
+
Args:
|
| 483 |
+
out_graphdef: A graphdef that is ready to have this input added.
|
| 484 |
+
|
| 485 |
+
Returns:
|
| 486 |
+
The output that the stub should use as an input for this operand.
|
| 487 |
+
|
| 488 |
+
Raises:
|
| 489 |
+
RuntimeError: if the method is not implemented.
|
| 490 |
+
"""
|
| 491 |
+
del out_graphdef
|
| 492 |
+
raise RuntimeError("Unimplemented abstract method.")
|
| 493 |
+
|
| 494 |
+
def aggregate_and_return_name_for_output(self, fused_op_name, output_index,
|
| 495 |
+
out_graphdef):
|
| 496 |
+
"""Add node(s) to graph representing output operands and returns type.
|
| 497 |
+
|
| 498 |
+
Args:
|
| 499 |
+
fused_op_name: name of the fused op stub name.
|
| 500 |
+
output_index: Output index that we are currently processing from stub.
|
| 501 |
+
out_graphdef: The destination graphdef we are currently building up.
|
| 502 |
+
|
| 503 |
+
Returns:
|
| 504 |
+
The datatype of this identity.
|
| 505 |
+
|
| 506 |
+
Raises:
|
| 507 |
+
RuntimeError: if the method is not implemented.
|
| 508 |
+
"""
|
| 509 |
+
del fused_op_name, output_index, out_graphdef
|
| 510 |
+
raise RuntimeError("Unimplemented abstract method.")
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
class _LiteSingleOperand(_LiteOperand):
|
| 514 |
+
"""A simple operand that is non-aggregated (i.e. most hints)."""
|
| 515 |
+
|
| 516 |
+
def __init__(self, node):
|
| 517 |
+
_LiteOperand.__init__(self)
|
| 518 |
+
self.node = node
|
| 519 |
+
self.name = _tensor_name_base(node.name)
|
| 520 |
+
|
| 521 |
+
def flatten(self):
|
| 522 |
+
return [self.name]
|
| 523 |
+
|
| 524 |
+
def aggregate_and_return_name_for_input(self, out_graphdef):
|
| 525 |
+
return self.name
|
| 526 |
+
|
| 527 |
+
def aggregate_and_return_name_for_output(self, fused_op_name, index,
|
| 528 |
+
out_graphdef):
|
| 529 |
+
output_node = _copy.deepcopy(self.node)
|
| 530 |
+
del output_node.input[:]
|
| 531 |
+
output_node.input.append(_tensorflow_output_name(fused_op_name, index))
|
| 532 |
+
out_graphdef.node.extend([output_node])
|
| 533 |
+
return self.node.attr["type"].i
|
| 534 |
+
|
| 535 |
+
def __str__(self):
|
| 536 |
+
return str(self.name)
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
class _LiteAggregateOperand(_LiteOperand):
|
| 540 |
+
"""An operand for a tflite hint function that is aggregated from many.
|
| 541 |
+
|
| 542 |
+
For example, an LSTM is a grid of operators that are all related. Inputs
|
| 543 |
+
going into them may need to be fused, so they should all be tracked as
|
| 544 |
+
related arguments.
|
| 545 |
+
"""
|
| 546 |
+
|
| 547 |
+
def __init__(self, aggregation):
|
| 548 |
+
_LiteOperand.__init__(self)
|
| 549 |
+
self.aggregation = aggregation
|
| 550 |
+
self.names = {}
|
| 551 |
+
self.nodes = {}
|
| 552 |
+
self.flattened = None
|
| 553 |
+
|
| 554 |
+
def add(self, sort, node):
|
| 555 |
+
self.names[sort] = _tensor_name_base(node.name)
|
| 556 |
+
self.nodes[sort] = node
|
| 557 |
+
|
| 558 |
+
def flatten_nodes(self):
|
| 559 |
+
"""Return a list of all the node protos in aggregation sorted order."""
|
| 560 |
+
if not self.flattened:
|
| 561 |
+
self.flattened = [None] * len(self.nodes)
|
| 562 |
+
for idx, node in self.nodes.items():
|
| 563 |
+
self.flattened[idx] = node
|
| 564 |
+
for n in self.nodes:
|
| 565 |
+
if n is None:
|
| 566 |
+
raise RuntimeError("Aggregate was missing argument.")
|
| 567 |
+
if self.aggregation == OpHint.AGGREGATE_FIRST:
|
| 568 |
+
self.flattened = self.flattened[:1]
|
| 569 |
+
elif self.aggregation == OpHint.AGGREGATE_LAST:
|
| 570 |
+
self.flattened = self.flattened[-1:]
|
| 571 |
+
elif self.aggregation == OpHint.AGGREGATE_STACK:
|
| 572 |
+
pass
|
| 573 |
+
else:
|
| 574 |
+
raise ValueError("Invalid aggregation type %r specified" %
|
| 575 |
+
self.aggregation)
|
| 576 |
+
return self.flattened
|
| 577 |
+
|
| 578 |
+
def flatten(self):
|
| 579 |
+
"""Return a list of all node names in aggregation sorted sorter."""
|
| 580 |
+
return [_tensor_name_base(x.name) for x in self.flatten_nodes()]
|
| 581 |
+
|
| 582 |
+
def aggregate_and_return_name_for_input(self, out_graphdef):
|
| 583 |
+
"""This adds the nodes to out_graphdef and returns an aggregated output.
|
| 584 |
+
|
| 585 |
+
In particular, if you have 4 inputs to a hint stub, this will be the
|
| 586 |
+
node that you can use as an output. I.e. you have 4 timesteps from a
|
| 587 |
+
static rnn, then a fused UnidirectionalLSTM will expect 1 input with
|
| 588 |
+
all 4 time steps. So here we make a pack and return the output name of
|
| 589 |
+
that pack.
|
| 590 |
+
|
| 591 |
+
Args:
|
| 592 |
+
out_graphdef: A graphdef that is ready to have this input added.
|
| 593 |
+
|
| 594 |
+
Returns:
|
| 595 |
+
The name of a pack that aggregates this node.
|
| 596 |
+
"""
|
| 597 |
+
flattened = self.flatten_nodes()
|
| 598 |
+
if (self.aggregation == OpHint.AGGREGATE_FIRST) or (
|
| 599 |
+
self.aggregation == OpHint.AGGREGATE_LAST):
|
| 600 |
+
assert len(flattened) == 1
|
| 601 |
+
if len(flattened) == 1 and self.aggregation != OpHint.AGGREGATE_STACK:
|
| 602 |
+
return _tensor_name_base(flattened[0].name)
|
| 603 |
+
else:
|
| 604 |
+
new_node = _node_def_pb2.NodeDef()
|
| 605 |
+
new_node.op = "Pack"
|
| 606 |
+
new_node.name = "OpHintStack-%s" % flattened[0].name
|
| 607 |
+
new_node.attr["N"].i = len(flattened)
|
| 608 |
+
new_node.attr["T"].type = flattened[0].attr["T"].type
|
| 609 |
+
for discrete in flattened:
|
| 610 |
+
new_node.input.append(_tensor_name_base(discrete.name))
|
| 611 |
+
out_graphdef.node.extend([new_node])
|
| 612 |
+
return new_node.name
|
| 613 |
+
|
| 614 |
+
def aggregate_and_return_name_for_output(self, fused_op_name, output_index,
|
| 615 |
+
out_graphdef):
|
| 616 |
+
"""This adds to `out_graphdef` all the unaggregated outputs.
|
| 617 |
+
|
| 618 |
+
I.e. we are outputting from a fused stub, but we need to make it compatible
|
| 619 |
+
with the unfused original graph so we insert an unpack. Ideally in a later
|
| 620 |
+
stage the unpack -> pack sequences will be removed.
|
| 621 |
+
|
| 622 |
+
Args:
|
| 623 |
+
fused_op_name: The name of the stub we are in the process of fusing.
|
| 624 |
+
output_index: The output output_index this object represents.
|
| 625 |
+
out_graphdef: The graphdef we are in the process of buildings
|
| 626 |
+
|
| 627 |
+
Returns:
|
| 628 |
+
The type of the aggregated output (so we can finish building the stub
|
| 629 |
+
op).
|
| 630 |
+
"""
|
| 631 |
+
flattened = self.flatten_nodes()
|
| 632 |
+
if (self.aggregation == OpHint.AGGREGATE_FIRST) or (
|
| 633 |
+
self.aggregation == OpHint.AGGREGATE_LAST):
|
| 634 |
+
assert len(flattened) == 1
|
| 635 |
+
if len(flattened) == 1 and self.aggregation != OpHint.AGGREGATE_STACK:
|
| 636 |
+
temp_op = _LiteSingleOperand(flattened[0])
|
| 637 |
+
return temp_op.aggregate_and_return_name_for_output(
|
| 638 |
+
fused_op_name, output_index, out_graphdef)
|
| 639 |
+
else:
|
| 640 |
+
stack_node = _node_def_pb2.NodeDef()
|
| 641 |
+
stack_node.op = "Unpack"
|
| 642 |
+
stack_node.name = "OpHintUnstack-%s" % flattened[0].name
|
| 643 |
+
stack_node.attr["num"].i = len(flattened)
|
| 644 |
+
output_type = flattened[0].attr["T"].type
|
| 645 |
+
stack_node.attr["T"].type = output_type
|
| 646 |
+
stack_node.input.append(
|
| 647 |
+
_tensorflow_output_name(fused_op_name, output_index))
|
| 648 |
+
out_graphdef.node.extend([stack_node])
|
| 649 |
+
|
| 650 |
+
for idx, discrete in enumerate(flattened):
|
| 651 |
+
output_node = _copy.deepcopy(discrete)
|
| 652 |
+
del output_node.input[:]
|
| 653 |
+
output_node.input.append(_tensorflow_output_name(stack_node.name, idx))
|
| 654 |
+
out_graphdef.node.extend([output_node])
|
| 655 |
+
|
| 656 |
+
return output_type
|
| 657 |
+
|
| 658 |
+
def __str__(self):
|
| 659 |
+
s = "\t\t\tAGGREGATE %s\n" % self.aggregation
|
| 660 |
+
for sort, val in self.names.iteritems():
|
| 661 |
+
s += "\t\t\t%d: %s\n" % (sort, val)
|
| 662 |
+
return s
|
| 663 |
+
|
| 664 |
+
|
| 665 |
+
class _LiteFuncCall:
|
| 666 |
+
"""Represent a TensorFlow Lite custom function.
|
| 667 |
+
|
| 668 |
+
This is uses to accumulate found hints in the graphdef into a single
|
| 669 |
+
conceptual unit.
|
| 670 |
+
|
| 671 |
+
Attributes:
|
| 672 |
+
inputs: inputs to the op (hash from index # to argument)
|
| 673 |
+
outputs: outputs to the op (hash from index # to argument)
|
| 674 |
+
function_name: the tflite custom op name to use
|
| 675 |
+
uuid: a unique call id for this particular call (i.e. multiple function
|
| 676 |
+
calls would have the same function_name but different uuids.
|
| 677 |
+
params: A param name to key value for op constant data. I.e. for axis on a
|
| 678 |
+
reduction, strides on a convolution, etc.
|
| 679 |
+
level: Level of the OpHint.
|
| 680 |
+
children_inputs_mappings: If the Ophint has children, children inputs
|
| 681 |
+
mappings indicate how their inputs & outputs are mapped.
|
| 682 |
+
"""
|
| 683 |
+
|
| 684 |
+
def __init__(self):
|
| 685 |
+
self.inputs = {}
|
| 686 |
+
self.outputs = {}
|
| 687 |
+
self.function_name = None
|
| 688 |
+
self.uuid = None
|
| 689 |
+
self.params = {}
|
| 690 |
+
self.level = -1
|
| 691 |
+
self.children_inputs_mappings = {}
|
| 692 |
+
|
| 693 |
+
def flattened_inputs_and_outputs(self):
|
| 694 |
+
"""Return a list of inputs and outputs in a flattened format.
|
| 695 |
+
|
| 696 |
+
Returns:
|
| 697 |
+
Tuple of (inputs, outputs). where input and output i a list of names.
|
| 698 |
+
"""
|
| 699 |
+
|
| 700 |
+
def _flatten(input_or_output_dict):
|
| 701 |
+
flattened_items = []
|
| 702 |
+
for item in input_or_output_dict.values():
|
| 703 |
+
flattened_items.extend(item.flatten())
|
| 704 |
+
return flattened_items
|
| 705 |
+
|
| 706 |
+
return _flatten(self.inputs), _flatten(self.outputs)
|
| 707 |
+
|
| 708 |
+
def __str__(self):
|
| 709 |
+
|
| 710 |
+
def format_args(items):
|
| 711 |
+
s = ""
|
| 712 |
+
for idx, item in items.iteritems():
|
| 713 |
+
s += ("\t\t%d:\n" % idx) + str(item)
|
| 714 |
+
return s
|
| 715 |
+
|
| 716 |
+
inputs_str = "\tInputs\n" + format_args(self.inputs)
|
| 717 |
+
outputs_str = "\tOutputs\n" + format_args(self.outputs)
|
| 718 |
+
|
| 719 |
+
return (
|
| 720 |
+
"tflite function %s call %s level %d "
|
| 721 |
+
"\n\tinputs:\n\t\t%s\n\toutputs:\n\t\t%s" %
|
| 722 |
+
(self.function_name, self.uuid, self.level, inputs_str, outputs_str))
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
def _find_all_hints_in_nodes(nodes):
|
| 726 |
+
"""Look at the all the input nodes and return a list of LiteFuncCall objs.
|
| 727 |
+
|
| 728 |
+
Args:
|
| 729 |
+
nodes: A TensorFlow graph_def to look for LiteFuncCalls.
|
| 730 |
+
|
| 731 |
+
Returns:
|
| 732 |
+
a list of `LifeFuncCall` objects in the form
|
| 733 |
+
|
| 734 |
+
"""
|
| 735 |
+
func_calls = _collections.defaultdict(_LiteFuncCall)
|
| 736 |
+
|
| 737 |
+
for node in nodes:
|
| 738 |
+
attr = node.attr
|
| 739 |
+
# This is an op hint if it has a FUNCTION_UUID_ATTR, otherwise skip
|
| 740 |
+
if (OpHint.FUNCTION_UUID_ATTR not in attr or
|
| 741 |
+
not attr[OpHint.FUNCTION_UUID_ATTR].s):
|
| 742 |
+
continue
|
| 743 |
+
uuid = attr[OpHint.FUNCTION_UUID_ATTR].s
|
| 744 |
+
|
| 745 |
+
# Start building function
|
| 746 |
+
call_def = func_calls[uuid]
|
| 747 |
+
call_def.uuid = uuid
|
| 748 |
+
call_def.function_name = attr[OpHint.FUNCTION_NAME_ATTR].s
|
| 749 |
+
call_def.level = attr[OpHint.FUNCTION_LEVEL_ATTR].i
|
| 750 |
+
# Get sorting and aggregation information
|
| 751 |
+
|
| 752 |
+
sort = (
|
| 753 |
+
attr[OpHint.FUNCTION_SORT_INDEX_ATTR].i
|
| 754 |
+
if OpHint.FUNCTION_SORT_INDEX_ATTR in attr else None)
|
| 755 |
+
if sort == -1:
|
| 756 |
+
sort = None
|
| 757 |
+
aggregation = None
|
| 758 |
+
if OpHint.FUNCTION_AGGREGATE_ATTR in attr:
|
| 759 |
+
aggregation = _compat.as_text(attr[OpHint.FUNCTION_AGGREGATE_ATTR].s)
|
| 760 |
+
|
| 761 |
+
if OpHint.CHILDREN_INPUTS_MAPPINGS in attr:
|
| 762 |
+
call_def.children_inputs_mappings = _json.loads(
|
| 763 |
+
_compat.as_text(attr[OpHint.CHILDREN_INPUTS_MAPPINGS].s))
|
| 764 |
+
|
| 765 |
+
# Add the input or output
|
| 766 |
+
def put_operand(stuff, index, sort, operand, aggregation):
|
| 767 |
+
"""Add a given index into the function structure."""
|
| 768 |
+
if sort is None:
|
| 769 |
+
stuff[index] = _LiteSingleOperand(operand)
|
| 770 |
+
else:
|
| 771 |
+
if index not in stuff:
|
| 772 |
+
stuff[index] = _LiteAggregateOperand(aggregation)
|
| 773 |
+
stuff[index].add(sort, operand)
|
| 774 |
+
|
| 775 |
+
if OpHint.FUNCTION_INPUT_INDEX_ATTR in attr:
|
| 776 |
+
put_operand(call_def.inputs, attr[OpHint.FUNCTION_INPUT_INDEX_ATTR].i,
|
| 777 |
+
sort, node, aggregation)
|
| 778 |
+
if OpHint.FUNCTION_OUTPUT_INDEX_ATTR in attr:
|
| 779 |
+
put_operand(call_def.outputs, attr[OpHint.FUNCTION_OUTPUT_INDEX_ATTR].i,
|
| 780 |
+
sort, node, aggregation)
|
| 781 |
+
|
| 782 |
+
# Remember attributes
|
| 783 |
+
for a in attr:
|
| 784 |
+
if a.startswith("_tflite_attr_"):
|
| 785 |
+
call_def.params[a.replace("_tflite_attr_,", "")] = attr[a].tensor
|
| 786 |
+
|
| 787 |
+
return func_calls
|
| 788 |
+
|
| 789 |
+
|
| 790 |
+
def _extract_topology_sequence_mapping(nodes):
|
| 791 |
+
return dict(
|
| 792 |
+
(_tensor_name_base(node.name), idx) for idx, node in enumerate(nodes))
|
| 793 |
+
|
| 794 |
+
|
| 795 |
+
def _find_children_hints_in_while_loop(function_def, nodes_mapping):
|
| 796 |
+
"""Find children hints and all nodes inside the while loop.
|
| 797 |
+
|
| 798 |
+
Args:
|
| 799 |
+
function_def: Function def of the while loop.
|
| 800 |
+
nodes_mapping: While loop input_arg : real node name.
|
| 801 |
+
|
| 802 |
+
Returns:
|
| 803 |
+
Ordered children hints and all re-mapped nodes inside the while loop.
|
| 804 |
+
"""
|
| 805 |
+
new_nodes = []
|
| 806 |
+
|
| 807 |
+
# Make nodes inside function def inputs point to the real nodes.
|
| 808 |
+
for node in function_def.node_def:
|
| 809 |
+
for i, _ in enumerate(node.input):
|
| 810 |
+
if node.input[i] in nodes_mapping:
|
| 811 |
+
node.input[i] = nodes_mapping[node.input[i]]
|
| 812 |
+
new_nodes.append(_copy.deepcopy(node))
|
| 813 |
+
name_to_seq_num = _extract_topology_sequence_mapping(function_def.node_def)
|
| 814 |
+
children_hints = _find_all_hints_in_nodes(new_nodes)
|
| 815 |
+
children_hints_q = []
|
| 816 |
+
# Ordered by the outputs.
|
| 817 |
+
for hint in children_hints.values():
|
| 818 |
+
_, output_names = hint.flattened_inputs_and_outputs()
|
| 819 |
+
seq = name_to_seq_num[output_names[0]]
|
| 820 |
+
for output_name in output_names:
|
| 821 |
+
seq = min(seq, name_to_seq_num[output_name])
|
| 822 |
+
children_hints_q.append((seq, hint))
|
| 823 |
+
children_hints_q.sort(key=lambda tup: tup[0])
|
| 824 |
+
ordered_children_hints = [x[1] for x in children_hints_q]
|
| 825 |
+
return ordered_children_hints, new_nodes
|
| 826 |
+
|
| 827 |
+
|
| 828 |
+
def _find_children_hints(call, graph_def):
|
| 829 |
+
"""Find all children hints.
|
| 830 |
+
|
| 831 |
+
For a given OpHint, we find all children hints inside it, we also copy all the
|
| 832 |
+
nodes inside function defs (if applicable) to the original graph_def, they are
|
| 833 |
+
returned in a list as well.
|
| 834 |
+
|
| 835 |
+
Args:
|
| 836 |
+
call: Parent OpHint that contains children ophints.
|
| 837 |
+
graph_def: Original graph def.
|
| 838 |
+
|
| 839 |
+
Returns:
|
| 840 |
+
Ordered children hints inside the parent ophint; new graph def that contains
|
| 841 |
+
nodes inside function defs (if applicable); nodes inside function defs.
|
| 842 |
+
"""
|
| 843 |
+
name_to_input_name, _, _ = _extract_graph_summary(graph_def)
|
| 844 |
+
input_names, output_names = call.flattened_inputs_and_outputs()
|
| 845 |
+
|
| 846 |
+
reachable_by_input = _bfs_for_reachable_nodes(input_names, name_to_input_name)
|
| 847 |
+
reachable_by_output = _bfs_for_reachable_nodes(output_names,
|
| 848 |
+
name_to_input_name)
|
| 849 |
+
output_nodes_set = set(output_names)
|
| 850 |
+
children_hints = []
|
| 851 |
+
out = _graph_pb2.GraphDef()
|
| 852 |
+
out.library.CopyFrom(graph_def.library)
|
| 853 |
+
out.versions.CopyFrom(graph_def.versions)
|
| 854 |
+
function_def_nodes = set()
|
| 855 |
+
for node in graph_def.node:
|
| 856 |
+
out.node.extend([_copy.deepcopy(node)])
|
| 857 |
+
n = _tensor_name_base(node.name)
|
| 858 |
+
if n in reachable_by_output:
|
| 859 |
+
if n not in reachable_by_input and n not in output_nodes_set:
|
| 860 |
+
# special handle for while loop function def.
|
| 861 |
+
if node.op == "While" or node.op == "StatelessWhile":
|
| 862 |
+
body_name = node.attr["body"].func.name
|
| 863 |
+
inputs_outside_loop = node.input
|
| 864 |
+
for function_def in graph_def.library.function:
|
| 865 |
+
if function_def.signature.name == body_name:
|
| 866 |
+
function_inputs = function_def.signature.input_arg
|
| 867 |
+
assert len(inputs_outside_loop) == len(function_inputs)
|
| 868 |
+
nodes_mapping = {}
|
| 869 |
+
for i, function_input in enumerate(function_inputs):
|
| 870 |
+
nodes_mapping[function_input.name] = inputs_outside_loop[i]
|
| 871 |
+
(children_hints_in_loop,
|
| 872 |
+
new_nodes) = _find_children_hints_in_while_loop(
|
| 873 |
+
function_def, nodes_mapping)
|
| 874 |
+
function_def_nodes.update([x.name for x in new_nodes])
|
| 875 |
+
children_hints.extend(children_hints_in_loop)
|
| 876 |
+
out.node.extend(new_nodes)
|
| 877 |
+
|
| 878 |
+
return children_hints, out, function_def_nodes
|
| 879 |
+
|
| 880 |
+
|
| 881 |
+
def _tensor_name_base(full_tensor_name):
|
| 882 |
+
"""Removes the device assignment code from a tensor.
|
| 883 |
+
|
| 884 |
+
e.g. _tensor_name_base("foo:3") => "foo"
|
| 885 |
+
|
| 886 |
+
Args:
|
| 887 |
+
full_tensor_name: A tensor name that is annotated with a device placement
|
| 888 |
+
(this is what tensor flow introspection gives).
|
| 889 |
+
|
| 890 |
+
Returns:
|
| 891 |
+
A name without any device assignment.
|
| 892 |
+
"""
|
| 893 |
+
if full_tensor_name.startswith("^"):
|
| 894 |
+
return full_tensor_name[1:]
|
| 895 |
+
return full_tensor_name.split(":")[0]
|
| 896 |
+
|
| 897 |
+
|
| 898 |
+
def _tensorflow_output_name(tensor_name, output_index):
|
| 899 |
+
return tensor_name if output_index == 0 else "%s:%d" % (tensor_name,
|
| 900 |
+
output_index)
|
| 901 |
+
|
| 902 |
+
|
| 903 |
+
def _check_subgraph_closed(n, reachable_by_input, input_nodes_set,
|
| 904 |
+
name_to_input_name):
|
| 905 |
+
"""Checks to make sure node only connects to predecessor graph through inputs.
|
| 906 |
+
|
| 907 |
+
Args:
|
| 908 |
+
n: Node to check
|
| 909 |
+
reachable_by_input: Nodes that are reachable by all inputs of subgraph
|
| 910 |
+
input_nodes_set: The set of nodes that are "inputs".
|
| 911 |
+
name_to_input_name: Maps from name to the list of inputs.
|
| 912 |
+
|
| 913 |
+
Raises:
|
| 914 |
+
TypeError: If the given node uses items past inputs directly.
|
| 915 |
+
"""
|
| 916 |
+
next_to_visit = [n]
|
| 917 |
+
visited = set()
|
| 918 |
+
while next_to_visit:
|
| 919 |
+
current_node = next_to_visit.pop()
|
| 920 |
+
visited.add(current_node)
|
| 921 |
+
if (current_node in reachable_by_input and
|
| 922 |
+
current_node not in input_nodes_set):
|
| 923 |
+
raise TypeError("Node %s uses input %s not in input_nodes." %
|
| 924 |
+
(n, current_node))
|
| 925 |
+
if current_node not in input_nodes_set:
|
| 926 |
+
next_to_visit += [
|
| 927 |
+
input_node for input_node in name_to_input_name[current_node]
|
| 928 |
+
if input_node not in visited
|
| 929 |
+
]
|
| 930 |
+
|
| 931 |
+
|
| 932 |
+
def _convert_single_op_hint_to_stub(call,
|
| 933 |
+
graph_def,
|
| 934 |
+
function_def_nodes=None,
|
| 935 |
+
is_last_run=True):
|
| 936 |
+
"""Given a graph_def, converts `call` into a stub and returns a new graph_def.
|
| 937 |
+
|
| 938 |
+
Args:
|
| 939 |
+
call: A single function call to be converted.
|
| 940 |
+
graph_def: A graph_def to use as input (that has call obviously).
|
| 941 |
+
function_def_nodes: Nodes inside the function def those are not connected to
|
| 942 |
+
the graph.
|
| 943 |
+
is_last_run: Whether it is the last run for a given pass (for OpHint has
|
| 944 |
+
children).
|
| 945 |
+
|
| 946 |
+
Returns:
|
| 947 |
+
A new transformed graph-def that has call as a stub (single op).
|
| 948 |
+
|
| 949 |
+
Note: after this process, the graph_def can no longer be loaded into
|
| 950 |
+
the tensorflow runtime, so all future manipulations are done in graph_def
|
| 951 |
+
level.
|
| 952 |
+
"""
|
| 953 |
+
if function_def_nodes is None:
|
| 954 |
+
function_def_nodes = set()
|
| 955 |
+
name_to_input_name, name_to_node, name_to_seq_num = _extract_graph_summary(
|
| 956 |
+
graph_def)
|
| 957 |
+
input_names, output_names = call.flattened_inputs_and_outputs()
|
| 958 |
+
|
| 959 |
+
reachable_by_input = _bfs_for_reachable_nodes(input_names, name_to_input_name)
|
| 960 |
+
reachable_by_output = _bfs_for_reachable_nodes(output_names,
|
| 961 |
+
name_to_input_name)
|
| 962 |
+
output_nodes_set = set(output_names)
|
| 963 |
+
nodes_after_fuse = []
|
| 964 |
+
nodes_deleted_by_fuse = set()
|
| 965 |
+
# Classify each node. We want to keep everything reachable by input, but
|
| 966 |
+
# we don't know if things that are not reachable by output or input (things
|
| 967 |
+
# after fusing).
|
| 968 |
+
for node in graph_def.node:
|
| 969 |
+
n = _tensor_name_base(node.name)
|
| 970 |
+
if n in reachable_by_output:
|
| 971 |
+
if n not in reachable_by_input and n not in output_nodes_set:
|
| 972 |
+
nodes_deleted_by_fuse.add(n)
|
| 973 |
+
elif n not in reachable_by_input and n not in function_def_nodes:
|
| 974 |
+
# n is a node that after all the fusings, so keep it.
|
| 975 |
+
nodes_after_fuse.append(n)
|
| 976 |
+
else:
|
| 977 |
+
# In the last run, n is a node that is randomly in the graph but not
|
| 978 |
+
# connected to the chain of dependencies, we will delete n, otherwise
|
| 979 |
+
# we keep them.
|
| 980 |
+
if not is_last_run:
|
| 981 |
+
nodes_after_fuse.append(n)
|
| 982 |
+
|
| 983 |
+
# Make a new graphdef with all the pre-input and input nodes
|
| 984 |
+
out = _graph_pb2.GraphDef()
|
| 985 |
+
reachable_by_input_sorted = sorted(
|
| 986 |
+
list(reachable_by_input), key=lambda n: name_to_seq_num[n])
|
| 987 |
+
for node in reachable_by_input_sorted:
|
| 988 |
+
out.node.extend([_copy.deepcopy(name_to_node[node])])
|
| 989 |
+
|
| 990 |
+
# Create any stacks to aggregate arguments into to a single input
|
| 991 |
+
# i.e. for static_rnn's.
|
| 992 |
+
sorted_input_indices = list(call.inputs.keys())
|
| 993 |
+
sorted_input_indices.sort()
|
| 994 |
+
sorted_output_indices = list(call.outputs.keys())
|
| 995 |
+
sorted_output_indices.sort()
|
| 996 |
+
new_node = _node_def_pb2.NodeDef()
|
| 997 |
+
# Delegate to each operand to produce the proper new input for this stub node.
|
| 998 |
+
# In particular, an aggregate input will now be a Pack of some previously
|
| 999 |
+
# non-fused things.
|
| 1000 |
+
|
| 1001 |
+
optional_input_node = _node_def_pb2.NodeDef()
|
| 1002 |
+
optional_input_node.name = "Const" + str(_uuid.uuid1().hex)
|
| 1003 |
+
optional_input_node.op = "Const"
|
| 1004 |
+
optional_input_node.attr["dtype"].CopyFrom(
|
| 1005 |
+
_attr_value_pb2.AttrValue(type=_dtypes.float32.as_datatype_enum))
|
| 1006 |
+
optional_input_node.attr["value"].CopyFrom(
|
| 1007 |
+
_attr_value_pb2.AttrValue(
|
| 1008 |
+
tensor=_tensor_util.make_tensor_proto([-1], _dtypes.float32, [1])))
|
| 1009 |
+
out.node.extend([optional_input_node])
|
| 1010 |
+
|
| 1011 |
+
max_index = max(sorted_input_indices) + 1
|
| 1012 |
+
for cur_index in range(max_index):
|
| 1013 |
+
if cur_index in sorted_input_indices:
|
| 1014 |
+
inputs = call.inputs[cur_index]
|
| 1015 |
+
input_name = inputs.aggregate_and_return_name_for_input(out)
|
| 1016 |
+
new_node.input.append(input_name)
|
| 1017 |
+
else:
|
| 1018 |
+
new_node.input.append(optional_input_node.name)
|
| 1019 |
+
|
| 1020 |
+
new_node.attr[OpHint.TFLITE_INPUT_INDICES].list.i.extend(sorted_input_indices)
|
| 1021 |
+
|
| 1022 |
+
# Create the function
|
| 1023 |
+
new_node.op = call.function_name
|
| 1024 |
+
new_node.name = call.uuid
|
| 1025 |
+
out.node.extend([new_node])
|
| 1026 |
+
|
| 1027 |
+
# Now call each output argument to give them a chance to make the proper
|
| 1028 |
+
# output type and add it to our new_node.
|
| 1029 |
+
output_dtypes = []
|
| 1030 |
+
max_output_index = max(sorted_output_indices) + 1
|
| 1031 |
+
for cur_index in range(max_output_index):
|
| 1032 |
+
if cur_index in sorted_output_indices:
|
| 1033 |
+
output = call.outputs[cur_index]
|
| 1034 |
+
output_dtype = (
|
| 1035 |
+
output.aggregate_and_return_name_for_output(new_node.name, cur_index,
|
| 1036 |
+
out))
|
| 1037 |
+
else:
|
| 1038 |
+
output_dtype = optional_input_node.attr["type"].i
|
| 1039 |
+
output_dtypes.append(output_dtype)
|
| 1040 |
+
new_node.attr["_output_types"].list.type[:] = output_dtypes
|
| 1041 |
+
new_node.attr["_output_quantized"].b = False
|
| 1042 |
+
|
| 1043 |
+
# Add post output nodes that do not depend on the outputs
|
| 1044 |
+
for n in nodes_after_fuse:
|
| 1045 |
+
should_keep = True
|
| 1046 |
+
for input_name in name_to_input_name[n]:
|
| 1047 |
+
if input_name in nodes_deleted_by_fuse:
|
| 1048 |
+
should_keep = False
|
| 1049 |
+
if should_keep:
|
| 1050 |
+
out.node.extend([_copy.deepcopy(name_to_node[n])])
|
| 1051 |
+
|
| 1052 |
+
# Misc. graph_def data that needs copying.
|
| 1053 |
+
out.library.CopyFrom(graph_def.library)
|
| 1054 |
+
out.versions.CopyFrom(graph_def.versions)
|
| 1055 |
+
|
| 1056 |
+
return out
|
| 1057 |
+
|
| 1058 |
+
|
| 1059 |
+
def _remove_one_redundant_stack_unstack(in_graph_def):
|
| 1060 |
+
"""Removes a stack->unstack pattern from in_graph_def in a returned graph.
|
| 1061 |
+
|
| 1062 |
+
Args:
|
| 1063 |
+
in_graph_def: Graph def to use as input.
|
| 1064 |
+
|
| 1065 |
+
Returns:
|
| 1066 |
+
Simplified tuple (graph_def, changed_something) where changed_something
|
| 1067 |
+
is true if anything was done.
|
| 1068 |
+
"""
|
| 1069 |
+
name_to_input_name, name_to_node, name_to_seq_num = _extract_graph_summary(
|
| 1070 |
+
in_graph_def)
|
| 1071 |
+
del name_to_seq_num
|
| 1072 |
+
|
| 1073 |
+
do_generic_pack_unpack = True
|
| 1074 |
+
|
| 1075 |
+
out = _graph_pb2.GraphDef()
|
| 1076 |
+
out.library.CopyFrom(in_graph_def.library)
|
| 1077 |
+
out.versions.CopyFrom(in_graph_def.versions)
|
| 1078 |
+
for n in in_graph_def.node:
|
| 1079 |
+
node_name = _tensor_name_base(n.name)
|
| 1080 |
+
if not node_name.startswith("OpHintStack") and not n.op.startswith("Pack"):
|
| 1081 |
+
continue
|
| 1082 |
+
next_to_visit = [node_name]
|
| 1083 |
+
visited = set()
|
| 1084 |
+
|
| 1085 |
+
unpack_nodes = set()
|
| 1086 |
+
pack_node = node_name
|
| 1087 |
+
|
| 1088 |
+
# Find a pattern of unstack connected to a stack (with identities
|
| 1089 |
+
# in between.
|
| 1090 |
+
matches_pattern = True
|
| 1091 |
+
is_hint_created_stack = False
|
| 1092 |
+
while next_to_visit:
|
| 1093 |
+
current_node_name = next_to_visit[0]
|
| 1094 |
+
visited.add(current_node_name)
|
| 1095 |
+
del next_to_visit[0]
|
| 1096 |
+
node = name_to_node[current_node_name]
|
| 1097 |
+
is_op_hint_stack = node.name.startswith("OpHintStack")
|
| 1098 |
+
is_op_hint_unstack = node.name.startswith("OpHintUnstack")
|
| 1099 |
+
if (node.op == "Identity" or is_op_hint_stack or
|
| 1100 |
+
(do_generic_pack_unpack and node.op == "Pack")):
|
| 1101 |
+
is_hint_created_stack |= is_op_hint_stack
|
| 1102 |
+
next_to_visit += [
|
| 1103 |
+
input_node for input_node in name_to_input_name[current_node_name]
|
| 1104 |
+
if input_node not in visited
|
| 1105 |
+
]
|
| 1106 |
+
elif (is_op_hint_unstack or
|
| 1107 |
+
(do_generic_pack_unpack and node.op == "Unpack")):
|
| 1108 |
+
unpack_nodes.add(node.name)
|
| 1109 |
+
is_hint_created_stack &= is_op_hint_unstack
|
| 1110 |
+
else:
|
| 1111 |
+
matches_pattern = False
|
| 1112 |
+
break
|
| 1113 |
+
visited.add(node.name)
|
| 1114 |
+
|
| 1115 |
+
if matches_pattern and len(unpack_nodes) == 1:
|
| 1116 |
+
pack_node = node_name
|
| 1117 |
+
|
| 1118 |
+
# Check to see if anyone depends on the intermediate identity or the
|
| 1119 |
+
# Unstacked form
|
| 1120 |
+
no_external_dependency = True
|
| 1121 |
+
for other_n in in_graph_def.node:
|
| 1122 |
+
if other_n.name in visited:
|
| 1123 |
+
continue
|
| 1124 |
+
for input_tensor in name_to_input_name[other_n.name]:
|
| 1125 |
+
input_op = _tensor_name_base(input_tensor)
|
| 1126 |
+
if input_op in visited and input_op != pack_node:
|
| 1127 |
+
no_external_dependency = False
|
| 1128 |
+
# Proceed with the substitution if the stack/unstack pair was created
|
| 1129 |
+
# through hints, or that it was not, but nobody is consuming things
|
| 1130 |
+
# between the stack and unstack.
|
| 1131 |
+
if is_hint_created_stack or no_external_dependency:
|
| 1132 |
+
end = unpack_nodes.pop()
|
| 1133 |
+
end_input = name_to_node[end].input[0]
|
| 1134 |
+
# All nodes that depend on the final stack need to be redone to use
|
| 1135 |
+
for other_n in in_graph_def.node:
|
| 1136 |
+
node_name = _tensor_name_base(other_n.name)
|
| 1137 |
+
if node_name not in visited:
|
| 1138 |
+
new_node = _copy.deepcopy(other_n)
|
| 1139 |
+
new_node.input[:] = [
|
| 1140 |
+
(end_input if stripped == pack_node else non_stripped)
|
| 1141 |
+
for stripped, non_stripped in zip(name_to_input_name[node_name],
|
| 1142 |
+
new_node.input[:])
|
| 1143 |
+
]
|
| 1144 |
+
out.node.extend([new_node])
|
| 1145 |
+
return out, True
|
| 1146 |
+
return in_graph_def, False
|
| 1147 |
+
|
| 1148 |
+
|
| 1149 |
+
def _remove_redundant_stack_unstack(graph_def):
|
| 1150 |
+
curr = graph_def
|
| 1151 |
+
del graph_def
|
| 1152 |
+
changed_stuff = True
|
| 1153 |
+
while changed_stuff:
|
| 1154 |
+
curr, changed_stuff = _remove_one_redundant_stack_unstack(curr)
|
| 1155 |
+
return curr
|
| 1156 |
+
|
| 1157 |
+
|
| 1158 |
+
def _get_correct_mapping(original_index, nodes):
|
| 1159 |
+
# Special handle for the index is -1 case.
|
| 1160 |
+
# If it is -1, return the last index.
|
| 1161 |
+
if original_index == -1:
|
| 1162 |
+
node_indices = nodes.keys()
|
| 1163 |
+
node_indices = sorted(node_indices)
|
| 1164 |
+
return node_indices[-1]
|
| 1165 |
+
return original_index
|
| 1166 |
+
|
| 1167 |
+
|
| 1168 |
+
def _convert_op_hints_to_stubs_helper(
|
| 1169 |
+
graph_def, write_callback=lambda sess, graph_def: None):
|
| 1170 |
+
"""Converts a graph_def to a new graph_def where all op hints are stubbed.
|
| 1171 |
+
|
| 1172 |
+
Args:
|
| 1173 |
+
graph_def: A graph def that we should convert.
|
| 1174 |
+
write_callback: A function pointer that can be used to write intermediate
|
| 1175 |
+
steps of graph transformation (optional).
|
| 1176 |
+
|
| 1177 |
+
Returns:
|
| 1178 |
+
A new stubbed graph_def.
|
| 1179 |
+
"""
|
| 1180 |
+
hints = _find_all_hints_in_nodes(graph_def.node)
|
| 1181 |
+
|
| 1182 |
+
hints_q = []
|
| 1183 |
+
for hint in hints.values():
|
| 1184 |
+
hints_q.append((hint.level, hint.uuid))
|
| 1185 |
+
|
| 1186 |
+
hints_q.sort(key=lambda tup: tup[0])
|
| 1187 |
+
for i in range(len(hints_q) - 1, -1, -1):
|
| 1188 |
+
level, hint_uuid = hints_q[i]
|
| 1189 |
+
|
| 1190 |
+
curr_graph_def = graph_def
|
| 1191 |
+
del graph_def # prevent using graph_def again (common source of error)
|
| 1192 |
+
for i in range(len(hints_q) - 1, -1, -1):
|
| 1193 |
+
level, hint_uuid = hints_q[i]
|
| 1194 |
+
if level >= 2:
|
| 1195 |
+
children_hints, curr_graph_def, function_def_nodes = _find_children_hints(
|
| 1196 |
+
hints[hint_uuid], curr_graph_def)
|
| 1197 |
+
# pylint: disable=superfluous-parens
|
| 1198 |
+
assert (len(children_hints) > 0) # pylint: disable=g-explicit-length-test
|
| 1199 |
+
# pylint: enable=superfluous-parens
|
| 1200 |
+
|
| 1201 |
+
# Re-wire the children hints inputs/outputs, so latter child's inputs
|
| 1202 |
+
# connect to previous child node's outputs.
|
| 1203 |
+
children_inputs_mappings = hints[hint_uuid].children_inputs_mappings
|
| 1204 |
+
for j, child_hint in enumerate(children_hints):
|
| 1205 |
+
if j == 0:
|
| 1206 |
+
for mapping in children_inputs_mappings["parent_first_child_input"]:
|
| 1207 |
+
parent_input_index = _get_correct_mapping(
|
| 1208 |
+
mapping["parent_ophint_input_index"], hints[hint_uuid].inputs)
|
| 1209 |
+
child_input_index = _get_correct_mapping(
|
| 1210 |
+
mapping["first_child_ophint_input_index"], child_hint.inputs)
|
| 1211 |
+
child_hint.inputs[child_input_index] = hints[hint_uuid].inputs[
|
| 1212 |
+
parent_input_index]
|
| 1213 |
+
else:
|
| 1214 |
+
for mapping in children_inputs_mappings[
|
| 1215 |
+
"internal_children_input_output"]:
|
| 1216 |
+
input_index = _get_correct_mapping(mapping["child_input_index"],
|
| 1217 |
+
child_hint.inputs)
|
| 1218 |
+
output_index = _get_correct_mapping(mapping["child_output_index"],
|
| 1219 |
+
children_hints[j - 1].outputs)
|
| 1220 |
+
child_hint.inputs[input_index] = children_hints[
|
| 1221 |
+
j - 1].outputs[output_index]
|
| 1222 |
+
if j == len(children_hints) - 1:
|
| 1223 |
+
for mapping in children_inputs_mappings["parent_last_child_output"]:
|
| 1224 |
+
parent_output_index = _get_correct_mapping(
|
| 1225 |
+
mapping["parent_output_index"], hints[hint_uuid].outputs)
|
| 1226 |
+
child_output_index = _get_correct_mapping(
|
| 1227 |
+
mapping["child_output_index"], child_hint.outputs)
|
| 1228 |
+
child_hint.outputs[child_output_index] = hints[hint_uuid].outputs[
|
| 1229 |
+
parent_output_index]
|
| 1230 |
+
|
| 1231 |
+
for j, child_hint in enumerate(children_hints):
|
| 1232 |
+
curr_graph_def = _convert_single_op_hint_to_stub(
|
| 1233 |
+
child_hint, curr_graph_def, function_def_nodes,
|
| 1234 |
+
j == len(children_hints) - 1)
|
| 1235 |
+
else:
|
| 1236 |
+
curr_graph_def = _convert_single_op_hint_to_stub(hints[hint_uuid],
|
| 1237 |
+
curr_graph_def)
|
| 1238 |
+
write_callback(curr_graph_def, "initial")
|
| 1239 |
+
# The stubbing process can create stacks/unstacks in the case of LSTMs
|
| 1240 |
+
# remove them.
|
| 1241 |
+
curr_graph_def = _remove_redundant_stack_unstack(curr_graph_def)
|
| 1242 |
+
return curr_graph_def
|
| 1243 |
+
|
| 1244 |
+
|
| 1245 |
+
def find_all_hinted_output_nodes(session=None, graph_def=None):
|
| 1246 |
+
"""Find all Ophints output nodes in the graph.
|
| 1247 |
+
|
| 1248 |
+
This is used to get all the output nodes those are ophinted, it is important
|
| 1249 |
+
for operation like convert_variables_to_constants keep all ophints structure.
|
| 1250 |
+
Note: only one of session or graph_def should be used, not both.
|
| 1251 |
+
Why this can be useful? Some TensorFlow ops (e.g. bidirectional rnn), can
|
| 1252 |
+
generate multiple outputs for unfused subgraph. If not all output nodes are
|
| 1253 |
+
consumed, graph optimization can potentially drop the unused nodes and cause
|
| 1254 |
+
ophints in an invalid states (due to missing ophinted output nodes). So it's
|
| 1255 |
+
important for us to find all those hinted output nodes and make sure they're
|
| 1256 |
+
not discarded away.
|
| 1257 |
+
|
| 1258 |
+
Args:
|
| 1259 |
+
session: A TensorFlow session that contains the graph to convert.
|
| 1260 |
+
graph_def: A graph def that we should convert.
|
| 1261 |
+
|
| 1262 |
+
Returns:
|
| 1263 |
+
A list of OpHints output nodes.
|
| 1264 |
+
Raises:
|
| 1265 |
+
ValueError: If both session and graph_def are provided.
|
| 1266 |
+
"""
|
| 1267 |
+
if session is not None and graph_def is not None:
|
| 1268 |
+
raise ValueError("Provide only one of session and graph_def.")
|
| 1269 |
+
hinted_outputs_nodes = []
|
| 1270 |
+
if session is not None:
|
| 1271 |
+
hints = _find_all_hints_in_nodes(session.graph_def.node)
|
| 1272 |
+
elif graph_def is not None:
|
| 1273 |
+
hints = _find_all_hints_in_nodes(graph_def.node)
|
| 1274 |
+
for hint in hints.values():
|
| 1275 |
+
_, output_nodes = hint.flattened_inputs_and_outputs()
|
| 1276 |
+
hinted_outputs_nodes.extend(output_nodes)
|
| 1277 |
+
return hinted_outputs_nodes
|
| 1278 |
+
|
| 1279 |
+
|
| 1280 |
+
def is_ophint_converted(graph_def):
|
| 1281 |
+
if graph_def is None:
|
| 1282 |
+
raise ValueError("Must provide the graph_def.")
|
| 1283 |
+
ophint_converted = False
|
| 1284 |
+
for node in graph_def.node:
|
| 1285 |
+
attr = node.attr
|
| 1286 |
+
if OpHint.FUNCTION_INPUT_INDEX_ATTR in attr:
|
| 1287 |
+
ophint_converted = True
|
| 1288 |
+
break
|
| 1289 |
+
return ophint_converted
|
| 1290 |
+
|
| 1291 |
+
|
| 1292 |
+
@_tf_export(v1=["lite.experimental.convert_op_hints_to_stubs"])
|
| 1293 |
+
@_deprecation.deprecated(
|
| 1294 |
+
None,
|
| 1295 |
+
"Please follow instructions under "
|
| 1296 |
+
"https://www.tensorflow.org/lite/convert/operation_fusion for operation"
|
| 1297 |
+
"fusion in tflite."
|
| 1298 |
+
)
|
| 1299 |
+
def convert_op_hints_to_stubs(session=None,
|
| 1300 |
+
graph_def=None,
|
| 1301 |
+
write_callback=lambda graph_def, comments: None):
|
| 1302 |
+
"""Converts a graphdef with LiteOp hints into stub operations.
|
| 1303 |
+
|
| 1304 |
+
This is used to prepare for toco conversion of complex intrinsic usages.
|
| 1305 |
+
Note: only one of session or graph_def should be used, not both.
|
| 1306 |
+
|
| 1307 |
+
Args:
|
| 1308 |
+
session: A TensorFlow session that contains the graph to convert.
|
| 1309 |
+
graph_def: A graph def that we should convert.
|
| 1310 |
+
write_callback: A function pointer that can be used to write intermediate
|
| 1311 |
+
steps of graph transformation (optional).
|
| 1312 |
+
|
| 1313 |
+
Returns:
|
| 1314 |
+
A new graphdef with all ops contained in OpHints being replaced by
|
| 1315 |
+
a single op call with the right parameters.
|
| 1316 |
+
Raises:
|
| 1317 |
+
ValueError: If both session and graph_def are provided.
|
| 1318 |
+
"""
|
| 1319 |
+
|
| 1320 |
+
if session is not None and graph_def is not None:
|
| 1321 |
+
raise ValueError("Provide only one of session and graph_def.")
|
| 1322 |
+
|
| 1323 |
+
if session is not None:
|
| 1324 |
+
return _convert_op_hints_to_stubs_helper(session.graph_def, write_callback)
|
| 1325 |
+
elif graph_def is not None:
|
| 1326 |
+
return _convert_op_hints_to_stubs_helper(graph_def, write_callback)
|
| 1327 |
+
else:
|
| 1328 |
+
raise ValueError("Must specify session or graph_def as input.")
|
| 1329 |
+
|
| 1330 |
+
|
| 1331 |
+
_allowed_symbols = [
|
| 1332 |
+
"OpHint",
|
| 1333 |
+
"convert_op_hints_to_stubs",
|
| 1334 |
+
"convert_op_hints_to_stubs_new",
|
| 1335 |
+
"find_all_hinted_output_nodes",
|
| 1336 |
+
"is_ophint_converted",
|
| 1337 |
+
]
|
| 1338 |
+
remove_undocumented(__name__, _allowed_symbols)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/optimize/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/optimize/_pywrap_tensorflow_lite_calibration_wrapper.pyi
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 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 |
+
|
| 16 |
+
from typing import Callable
|
| 17 |
+
|
| 18 |
+
from typing import overload
|
| 19 |
+
|
| 20 |
+
class CalibrationWrapper:
|
| 21 |
+
def __init__(self, arg0: object, arg1: list[str], arg2: list[Callable[[int],None]]) -> None: ...
|
| 22 |
+
def Calibrate(self) -> object: ...
|
| 23 |
+
@overload
|
| 24 |
+
def FeedTensor(self, arg0: object, arg1: str) -> object: ...
|
| 25 |
+
@overload
|
| 26 |
+
def FeedTensor(self, arg0: object) -> object: ...
|
| 27 |
+
@overload
|
| 28 |
+
def Prepare(self, arg0: object, arg1: str) -> object: ...
|
| 29 |
+
@overload
|
| 30 |
+
def Prepare(self, arg0: object) -> object: ...
|
| 31 |
+
@overload
|
| 32 |
+
def Prepare(self, arg0: str) -> object: ...
|
| 33 |
+
@overload
|
| 34 |
+
def Prepare(self) -> object: ...
|
| 35 |
+
@overload
|
| 36 |
+
def QuantizeModel(self, arg0: int, arg1: int, arg2: bool, arg3: int, arg4: int, arg5: bool) -> object: ...
|
| 37 |
+
@overload
|
| 38 |
+
def QuantizeModel(self, arg0: int, arg1: int, arg2: bool, arg3: str) -> object: ...
|
| 39 |
+
|
| 40 |
+
def AddIntermediateTensors(arg0: object) -> object: ...
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/optimize/calibrator.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
"""Python wrapper for post training quantization with calibration."""
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
from tensorflow.lite.python.convert_phase import Component
|
| 19 |
+
from tensorflow.lite.python.convert_phase import convert_phase
|
| 20 |
+
from tensorflow.lite.python.convert_phase import SubComponent
|
| 21 |
+
from tensorflow.lite.python.interpreter import Interpreter
|
| 22 |
+
from tensorflow.python.framework import dtypes
|
| 23 |
+
from tensorflow.python.util.lazy_loader import LazyLoader
|
| 24 |
+
|
| 25 |
+
# Lazy load since some of the performance benchmark skylark rules
|
| 26 |
+
# break dependencies. Must use double quotes to match code internal rewrite
|
| 27 |
+
# rule.
|
| 28 |
+
_calibration_wrapper = LazyLoader(
|
| 29 |
+
"_calibration_wrapper",
|
| 30 |
+
globals(),
|
| 31 |
+
(
|
| 32 |
+
"tensorflow.lite.python.optimize."
|
| 33 |
+
"_pywrap_tensorflow_lite_calibration_wrapper"
|
| 34 |
+
),
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def add_intermediate_tensors(model_content):
|
| 39 |
+
"""Adds intermediate tensors to fused op if needed."""
|
| 40 |
+
return _calibration_wrapper.AddIntermediateTensors(model_content)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class Calibrator:
|
| 44 |
+
"""Calibrates a floating point model and then quantizes it.
|
| 45 |
+
|
| 46 |
+
This is an internal class, not a public interface.
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
def __init__(
|
| 50 |
+
self,
|
| 51 |
+
model_content,
|
| 52 |
+
custom_op_registerers_by_name=None,
|
| 53 |
+
custom_op_registerers_by_func=None,
|
| 54 |
+
):
|
| 55 |
+
"""Constructor.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
model_content: Content of a TF-Lite Flatbuffer file.
|
| 59 |
+
custom_op_registerers_by_name: List of str (symbol names) that take a
|
| 60 |
+
pointer to a MutableOpResolver and register custom ops.
|
| 61 |
+
custom_op_registerers_by_func: List of functions that take a pointer to a
|
| 62 |
+
MutableOpResolver and register custom ops.
|
| 63 |
+
|
| 64 |
+
Raises:
|
| 65 |
+
ValueError: If the calibrator was unable to open the model.
|
| 66 |
+
"""
|
| 67 |
+
if not model_content:
|
| 68 |
+
raise ValueError("`model_content` must be specified.")
|
| 69 |
+
if custom_op_registerers_by_name is None:
|
| 70 |
+
custom_op_registerers_by_name = []
|
| 71 |
+
if custom_op_registerers_by_func is None:
|
| 72 |
+
custom_op_registerers_by_func = []
|
| 73 |
+
try:
|
| 74 |
+
self._calibrator = _calibration_wrapper.CalibrationWrapper(
|
| 75 |
+
model_content,
|
| 76 |
+
custom_op_registerers_by_name,
|
| 77 |
+
custom_op_registerers_by_func,
|
| 78 |
+
)
|
| 79 |
+
self._model_content = model_content
|
| 80 |
+
except Exception as e:
|
| 81 |
+
raise ValueError("Failed to parse the model: %s." % e)
|
| 82 |
+
if not self._calibrator:
|
| 83 |
+
raise ValueError("Failed to parse the model.")
|
| 84 |
+
self._interpreter = None
|
| 85 |
+
|
| 86 |
+
def _create_input_array_from_dict(self, signature_key, inputs):
|
| 87 |
+
input_array = []
|
| 88 |
+
signature_runner = self._interpreter.get_signature_runner(signature_key)
|
| 89 |
+
input_details = sorted(
|
| 90 |
+
signature_runner.get_input_details().items(),
|
| 91 |
+
key=lambda item: item[1]["index"],
|
| 92 |
+
)
|
| 93 |
+
for input_name, _ in input_details:
|
| 94 |
+
input_array.append(inputs[input_name])
|
| 95 |
+
return input_array
|
| 96 |
+
|
| 97 |
+
def _feed_tensors(self, dataset_gen, resize_input):
|
| 98 |
+
"""Feed tensors to the calibrator."""
|
| 99 |
+
initialized = {}
|
| 100 |
+
|
| 101 |
+
for sample in dataset_gen():
|
| 102 |
+
if isinstance(sample, tuple):
|
| 103 |
+
if not isinstance(sample[1], dict):
|
| 104 |
+
raise ValueError(
|
| 105 |
+
"You need to provide either a dictionary with input "
|
| 106 |
+
"names and values in the second argument in the "
|
| 107 |
+
"tuple"
|
| 108 |
+
)
|
| 109 |
+
# Convert signature based inputs to the tensor index based data.
|
| 110 |
+
if self._interpreter is None:
|
| 111 |
+
self._interpreter = Interpreter(model_content=self._model_content)
|
| 112 |
+
signature_key = sample[0]
|
| 113 |
+
input_array = self._create_input_array_from_dict(
|
| 114 |
+
signature_key, sample[1]
|
| 115 |
+
)
|
| 116 |
+
elif isinstance(sample, dict):
|
| 117 |
+
# Convert signature based inputs to the tensor index based data.
|
| 118 |
+
if self._interpreter is None:
|
| 119 |
+
self._interpreter = Interpreter(model_content=self._model_content)
|
| 120 |
+
signature_key = None
|
| 121 |
+
input_array = self._create_input_array_from_dict(None, sample)
|
| 122 |
+
elif isinstance(sample, list):
|
| 123 |
+
signature_key = None
|
| 124 |
+
input_array = sample
|
| 125 |
+
else:
|
| 126 |
+
raise ValueError(
|
| 127 |
+
"You need to provide either a dictionary with input "
|
| 128 |
+
"names and values, a tuple with signature key and a "
|
| 129 |
+
"dictionary with input names and values, or an array "
|
| 130 |
+
"with input values in the order of input tensors of "
|
| 131 |
+
"the graph in the representative_dataset function. "
|
| 132 |
+
"Unsupported value from dataset: {}.".format(sample)
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
if signature_key not in initialized:
|
| 136 |
+
initialized[signature_key] = True
|
| 137 |
+
if resize_input:
|
| 138 |
+
if signature_key is not None:
|
| 139 |
+
self._calibrator.Prepare(
|
| 140 |
+
[list(s.shape) for s in input_array], signature_key
|
| 141 |
+
)
|
| 142 |
+
else:
|
| 143 |
+
self._calibrator.Prepare([list(s.shape) for s in input_array])
|
| 144 |
+
else:
|
| 145 |
+
if signature_key is not None:
|
| 146 |
+
self._calibrator.Prepare(signature_key)
|
| 147 |
+
else:
|
| 148 |
+
self._calibrator.Prepare()
|
| 149 |
+
if signature_key is not None:
|
| 150 |
+
self._calibrator.FeedTensor(input_array, signature_key)
|
| 151 |
+
else:
|
| 152 |
+
self._calibrator.FeedTensor(input_array)
|
| 153 |
+
|
| 154 |
+
@convert_phase(
|
| 155 |
+
Component.OPTIMIZE_TFLITE_MODEL,
|
| 156 |
+
SubComponent.QUANTIZE_USING_DEPRECATED_QUANTIZER,
|
| 157 |
+
)
|
| 158 |
+
def calibrate_and_quantize(
|
| 159 |
+
self,
|
| 160 |
+
dataset_gen,
|
| 161 |
+
input_type,
|
| 162 |
+
output_type,
|
| 163 |
+
allow_float,
|
| 164 |
+
activations_type=dtypes.int8,
|
| 165 |
+
bias_type=dtypes.int32,
|
| 166 |
+
resize_input=True,
|
| 167 |
+
disable_per_channel=False,
|
| 168 |
+
):
|
| 169 |
+
"""Calibrates the model with specified generator and then quantizes it.
|
| 170 |
+
|
| 171 |
+
The input shapes of the calibrator are resized with the calibration data if
|
| 172 |
+
`resize_input` is set.
|
| 173 |
+
|
| 174 |
+
Returns:
|
| 175 |
+
A quantized model.
|
| 176 |
+
|
| 177 |
+
Args:
|
| 178 |
+
dataset_gen: A generator that generates calibration samples.
|
| 179 |
+
input_type: A tf.dtype representing the desired real-value input type.
|
| 180 |
+
output_type: A tf.dtype representing the desired real-value output type.
|
| 181 |
+
allow_float: A boolean. False if the resulting model cannot perform float
|
| 182 |
+
computation, useful when targeting an integer-only backend. If False, an
|
| 183 |
+
error will be thrown if an operation cannot be quantized, otherwise the
|
| 184 |
+
model will fallback to float ops.
|
| 185 |
+
activations_type: A tf.dtype representing the desired type for
|
| 186 |
+
activations.
|
| 187 |
+
bias_type: A tf.dtype representing the desired type for bias.
|
| 188 |
+
resize_input: A boolean. True if the shape of the sample data is different
|
| 189 |
+
from the input.
|
| 190 |
+
disable_per_channel: A boolean. True if disabling per-channel
|
| 191 |
+
quantization.
|
| 192 |
+
"""
|
| 193 |
+
self._feed_tensors(dataset_gen, resize_input)
|
| 194 |
+
return self._calibrator.QuantizeModel(
|
| 195 |
+
np.dtype(input_type.as_numpy_dtype()).num,
|
| 196 |
+
np.dtype(output_type.as_numpy_dtype()).num,
|
| 197 |
+
allow_float,
|
| 198 |
+
np.dtype(activations_type.as_numpy_dtype()).num,
|
| 199 |
+
np.dtype(bias_type.as_numpy_dtype()).num,
|
| 200 |
+
disable_per_channel,
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
@convert_phase(
|
| 204 |
+
Component.OPTIMIZE_TFLITE_MODEL,
|
| 205 |
+
SubComponent.QUANTIZE_USING_DEPRECATED_QUANTIZER,
|
| 206 |
+
)
|
| 207 |
+
def calibrate_and_quantize_single(
|
| 208 |
+
self,
|
| 209 |
+
dataset_gen,
|
| 210 |
+
input_type,
|
| 211 |
+
output_type,
|
| 212 |
+
allow_float,
|
| 213 |
+
op_output_name,
|
| 214 |
+
resize_input=True,
|
| 215 |
+
):
|
| 216 |
+
"""Calibrates the model with specified generator and then quantizes it.
|
| 217 |
+
|
| 218 |
+
Only the single op with output op_output_name will be quantized.
|
| 219 |
+
The input shapes of the calibrator are resized with the calibration data.
|
| 220 |
+
|
| 221 |
+
Returns:
|
| 222 |
+
A quantized model.
|
| 223 |
+
|
| 224 |
+
Args:
|
| 225 |
+
dataset_gen: A generator that generates calibration samples.
|
| 226 |
+
input_type: A tf.dtype representing the desired real-value input type.
|
| 227 |
+
output_type: A tf.dtype representing the desired real-value output type.
|
| 228 |
+
allow_float: A boolean. False if the resulting model cannot perform float
|
| 229 |
+
computation, useful when targeting an integer-only backend. If False, an
|
| 230 |
+
error will be thrown if an operation cannot be quantized, otherwise the
|
| 231 |
+
model will fallback to float ops.
|
| 232 |
+
op_output_name: A string, only this op will be quantized.
|
| 233 |
+
resize_input: A boolean. True if the shape of the sample data is different
|
| 234 |
+
from the input.
|
| 235 |
+
"""
|
| 236 |
+
self._feed_tensors(dataset_gen, resize_input)
|
| 237 |
+
return self._calibrator.QuantizeModel(
|
| 238 |
+
np.dtype(input_type.as_numpy_dtype()).num,
|
| 239 |
+
np.dtype(output_type.as_numpy_dtype()).num,
|
| 240 |
+
allow_float,
|
| 241 |
+
op_output_name,
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
@convert_phase(Component.OPTIMIZE_TFLITE_MODEL, SubComponent.CALIBRATE)
|
| 245 |
+
def calibrate(self, dataset_gen):
|
| 246 |
+
"""Calibrates the model with specified generator.
|
| 247 |
+
|
| 248 |
+
Returns:
|
| 249 |
+
A model with min and max calibration stats.
|
| 250 |
+
|
| 251 |
+
Args:
|
| 252 |
+
dataset_gen: A generator that generates calibration samples.
|
| 253 |
+
"""
|
| 254 |
+
self._feed_tensors(dataset_gen, resize_input=True)
|
| 255 |
+
return self._calibrator.Calibrate()
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/schema_py_generated.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/schema_util.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Schema utilities to get builtin code from operator code."""
|
| 16 |
+
|
| 17 |
+
from tensorflow.python.util import all_util
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def get_builtin_code_from_operator_code(opcode):
|
| 21 |
+
"""Return the builtin code of the given operator code.
|
| 22 |
+
|
| 23 |
+
The following method is introduced to resolve op builtin code shortage
|
| 24 |
+
problem. The new builtin operator will be assigned to the extended builtin
|
| 25 |
+
code field in the flatbuffer schema. Those methods helps to hide builtin code
|
| 26 |
+
details.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
opcode: Operator code.
|
| 30 |
+
|
| 31 |
+
Returns:
|
| 32 |
+
The builtin code of the given operator code.
|
| 33 |
+
"""
|
| 34 |
+
# Access BuiltinCode() method first if available.
|
| 35 |
+
if hasattr(opcode, 'BuiltinCode') and callable(opcode.BuiltinCode):
|
| 36 |
+
return max(opcode.BuiltinCode(), opcode.DeprecatedBuiltinCode())
|
| 37 |
+
|
| 38 |
+
return max(opcode.builtinCode, opcode.deprecatedBuiltinCode)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
_allowed_symbols = [
|
| 42 |
+
'get_builtin_code_from_operator_code',
|
| 43 |
+
]
|
| 44 |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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2018 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 |
+
"""Python command line interface for converting TF models to TFLite models."""
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
import warnings
|
| 21 |
+
|
| 22 |
+
from absl import app
|
| 23 |
+
import tensorflow as tf # pylint: disable=unused-import
|
| 24 |
+
|
| 25 |
+
from tensorflow.lite.python import lite
|
| 26 |
+
from tensorflow.lite.python.convert import register_custom_opdefs
|
| 27 |
+
from tensorflow.lite.toco import toco_flags_pb2 as _toco_flags_pb2
|
| 28 |
+
from tensorflow.lite.toco.logging import gen_html
|
| 29 |
+
from tensorflow.python import tf2
|
| 30 |
+
from tensorflow.python.framework import dtypes
|
| 31 |
+
from tensorflow.python.platform import gfile
|
| 32 |
+
from tensorflow.python.util import keras_deps
|
| 33 |
+
|
| 34 |
+
# Needed to enable TF2 by default.
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _parse_array(values, type_fn=str):
|
| 38 |
+
if values is not None:
|
| 39 |
+
return [type_fn(val) for val in values.split(",") if val]
|
| 40 |
+
return None
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _parse_set(values):
|
| 44 |
+
if values is not None:
|
| 45 |
+
return set([item for item in values.split(",") if item])
|
| 46 |
+
return None
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _parse_inference_type(value, flag):
|
| 50 |
+
"""Converts the inference type to the value of the constant.
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
value: str representing the inference type.
|
| 54 |
+
flag: str representing the flag name.
|
| 55 |
+
|
| 56 |
+
Returns:
|
| 57 |
+
tf.dtype.
|
| 58 |
+
|
| 59 |
+
Raises:
|
| 60 |
+
ValueError: Unsupported value.
|
| 61 |
+
"""
|
| 62 |
+
if value == "FLOAT":
|
| 63 |
+
return dtypes.float32
|
| 64 |
+
if value == "INT8":
|
| 65 |
+
return dtypes.int8
|
| 66 |
+
if value == "UINT8" or value == "QUANTIZED_UINT8":
|
| 67 |
+
return dtypes.uint8
|
| 68 |
+
raise ValueError(
|
| 69 |
+
"Unsupported value for `{}` flag. Expected FLOAT, INT8, UINT8, or "
|
| 70 |
+
"QUANTIZED_UINT8 instead got {}.".format(flag, value))
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class _ParseBooleanFlag(argparse.Action):
|
| 74 |
+
"""Helper class to parse boolean flag that optionally accepts truth value."""
|
| 75 |
+
|
| 76 |
+
def __init__(self, option_strings, dest, nargs=None, **kwargs):
|
| 77 |
+
if nargs != "?":
|
| 78 |
+
# This should never happen. This class is only used once below with
|
| 79 |
+
# nargs="?".
|
| 80 |
+
raise ValueError(
|
| 81 |
+
"This parser only supports nargs='?' (0 or 1 additional arguments)")
|
| 82 |
+
super(_ParseBooleanFlag, self).__init__(
|
| 83 |
+
option_strings, dest, nargs=nargs, **kwargs)
|
| 84 |
+
|
| 85 |
+
def __call__(self, parser, namespace, values, option_string=None):
|
| 86 |
+
if values is None:
|
| 87 |
+
# Handling `--boolean_flag`.
|
| 88 |
+
# Without additional arguments, it implies true.
|
| 89 |
+
flag_value = True
|
| 90 |
+
elif values.lower() == "true":
|
| 91 |
+
# Handling `--boolean_flag=true`.
|
| 92 |
+
# (Case insensitive after the equal sign)
|
| 93 |
+
flag_value = True
|
| 94 |
+
elif values.lower() == "false":
|
| 95 |
+
# Handling `--boolean_flag=false`.
|
| 96 |
+
# (Case insensitive after the equal sign)
|
| 97 |
+
flag_value = False
|
| 98 |
+
else:
|
| 99 |
+
raise ValueError("Invalid argument to --{}. Must use flag alone,"
|
| 100 |
+
" or specify true/false.".format(self.dest))
|
| 101 |
+
setattr(namespace, self.dest, flag_value)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _get_tflite_converter(flags):
|
| 105 |
+
"""Makes a TFLiteConverter object based on the flags provided.
|
| 106 |
+
|
| 107 |
+
Args:
|
| 108 |
+
flags: argparse.Namespace object containing TFLite flags.
|
| 109 |
+
|
| 110 |
+
Returns:
|
| 111 |
+
TFLiteConverter object.
|
| 112 |
+
|
| 113 |
+
Raises:
|
| 114 |
+
ValueError: Invalid flags.
|
| 115 |
+
"""
|
| 116 |
+
# Parse input and output arrays.
|
| 117 |
+
input_arrays = _parse_array(flags.input_arrays)
|
| 118 |
+
input_shapes = None
|
| 119 |
+
if flags.input_shapes:
|
| 120 |
+
input_shapes_list = [
|
| 121 |
+
_parse_array(shape, type_fn=int)
|
| 122 |
+
for shape in flags.input_shapes.split(":")
|
| 123 |
+
]
|
| 124 |
+
input_shapes = dict(list(zip(input_arrays, input_shapes_list)))
|
| 125 |
+
output_arrays = _parse_array(flags.output_arrays)
|
| 126 |
+
|
| 127 |
+
converter_kwargs = {
|
| 128 |
+
"input_arrays": input_arrays,
|
| 129 |
+
"input_shapes": input_shapes,
|
| 130 |
+
"output_arrays": output_arrays
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
# Create TFLiteConverter.
|
| 134 |
+
if flags.graph_def_file:
|
| 135 |
+
converter_fn = lite.TFLiteConverter.from_frozen_graph
|
| 136 |
+
converter_kwargs["graph_def_file"] = flags.graph_def_file
|
| 137 |
+
elif flags.saved_model_dir:
|
| 138 |
+
converter_fn = lite.TFLiteConverter.from_saved_model
|
| 139 |
+
converter_kwargs["saved_model_dir"] = flags.saved_model_dir
|
| 140 |
+
converter_kwargs["tag_set"] = _parse_set(flags.saved_model_tag_set)
|
| 141 |
+
converter_kwargs["signature_key"] = flags.saved_model_signature_key
|
| 142 |
+
elif flags.keras_model_file:
|
| 143 |
+
converter_fn = lite.TFLiteConverter.from_keras_model_file
|
| 144 |
+
converter_kwargs["model_file"] = flags.keras_model_file
|
| 145 |
+
else:
|
| 146 |
+
raise ValueError("--graph_def_file, --saved_model_dir, or "
|
| 147 |
+
"--keras_model_file must be specified.")
|
| 148 |
+
|
| 149 |
+
return converter_fn(**converter_kwargs)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _convert_tf1_model(flags):
|
| 153 |
+
"""Calls function to convert the TensorFlow 1.X model into a TFLite model.
|
| 154 |
+
|
| 155 |
+
Args:
|
| 156 |
+
flags: argparse.Namespace object.
|
| 157 |
+
|
| 158 |
+
Raises:
|
| 159 |
+
ValueError: Invalid flags.
|
| 160 |
+
"""
|
| 161 |
+
# Register custom opdefs before converter object creation.
|
| 162 |
+
if flags.custom_opdefs:
|
| 163 |
+
register_custom_opdefs(_parse_array(flags.custom_opdefs))
|
| 164 |
+
|
| 165 |
+
# Create converter.
|
| 166 |
+
converter = _get_tflite_converter(flags)
|
| 167 |
+
if flags.inference_type:
|
| 168 |
+
converter.inference_type = _parse_inference_type(flags.inference_type,
|
| 169 |
+
"inference_type")
|
| 170 |
+
if flags.inference_input_type:
|
| 171 |
+
converter.inference_input_type = _parse_inference_type(
|
| 172 |
+
flags.inference_input_type, "inference_input_type")
|
| 173 |
+
if flags.output_format:
|
| 174 |
+
converter.output_format = _toco_flags_pb2.FileFormat.Value(
|
| 175 |
+
flags.output_format)
|
| 176 |
+
|
| 177 |
+
if flags.mean_values and flags.std_dev_values:
|
| 178 |
+
input_arrays = converter.get_input_arrays()
|
| 179 |
+
std_dev_values = _parse_array(flags.std_dev_values, type_fn=float)
|
| 180 |
+
|
| 181 |
+
# In quantized inference, mean_value has to be integer so that the real
|
| 182 |
+
# value 0.0 is exactly representable.
|
| 183 |
+
if converter.inference_type == dtypes.float32:
|
| 184 |
+
mean_values = _parse_array(flags.mean_values, type_fn=float)
|
| 185 |
+
else:
|
| 186 |
+
mean_values = _parse_array(flags.mean_values, type_fn=int)
|
| 187 |
+
quant_stats = list(zip(mean_values, std_dev_values))
|
| 188 |
+
if ((not flags.input_arrays and len(input_arrays) > 1) or
|
| 189 |
+
(len(input_arrays) != len(quant_stats))):
|
| 190 |
+
raise ValueError("Mismatching --input_arrays, --std_dev_values, and "
|
| 191 |
+
"--mean_values. The flags must have the same number of "
|
| 192 |
+
"items. The current input arrays are '{0}'. "
|
| 193 |
+
"--input_arrays must be present when specifying "
|
| 194 |
+
"--std_dev_values and --mean_values with multiple input "
|
| 195 |
+
"tensors in order to map between names and "
|
| 196 |
+
"values.".format(",".join(input_arrays)))
|
| 197 |
+
converter.quantized_input_stats = dict(list(zip(input_arrays, quant_stats)))
|
| 198 |
+
if (flags.default_ranges_min is not None) and (flags.default_ranges_max is
|
| 199 |
+
not None):
|
| 200 |
+
converter.default_ranges_stats = (flags.default_ranges_min,
|
| 201 |
+
flags.default_ranges_max)
|
| 202 |
+
|
| 203 |
+
if flags.drop_control_dependency:
|
| 204 |
+
converter.drop_control_dependency = flags.drop_control_dependency
|
| 205 |
+
if flags.reorder_across_fake_quant:
|
| 206 |
+
converter.reorder_across_fake_quant = flags.reorder_across_fake_quant
|
| 207 |
+
if flags.change_concat_input_ranges:
|
| 208 |
+
converter.change_concat_input_ranges = (
|
| 209 |
+
flags.change_concat_input_ranges == "TRUE")
|
| 210 |
+
|
| 211 |
+
if flags.allow_custom_ops:
|
| 212 |
+
converter.allow_custom_ops = flags.allow_custom_ops
|
| 213 |
+
|
| 214 |
+
if flags.target_ops:
|
| 215 |
+
ops_set_options = lite.OpsSet.get_options()
|
| 216 |
+
converter.target_spec.supported_ops = set()
|
| 217 |
+
for option in flags.target_ops.split(","):
|
| 218 |
+
if option not in ops_set_options:
|
| 219 |
+
raise ValueError("Invalid value for --target_ops. Options: "
|
| 220 |
+
"{0}".format(",".join(ops_set_options)))
|
| 221 |
+
converter.target_spec.supported_ops.add(lite.OpsSet(option))
|
| 222 |
+
|
| 223 |
+
if flags.experimental_select_user_tf_ops:
|
| 224 |
+
if lite.OpsSet.SELECT_TF_OPS not in converter.target_spec.supported_ops:
|
| 225 |
+
raise ValueError("--experimental_select_user_tf_ops can only be set if "
|
| 226 |
+
"--target_ops contains SELECT_TF_OPS.")
|
| 227 |
+
user_op_set = set()
|
| 228 |
+
for op_name in flags.experimental_select_user_tf_ops.split(","):
|
| 229 |
+
user_op_set.add(op_name)
|
| 230 |
+
converter.target_spec.experimental_select_user_tf_ops = list(user_op_set)
|
| 231 |
+
|
| 232 |
+
if flags.post_training_quantize:
|
| 233 |
+
converter.optimizations = [lite.Optimize.DEFAULT]
|
| 234 |
+
if converter.inference_type != dtypes.float32:
|
| 235 |
+
print("--post_training_quantize quantizes a graph of inference_type "
|
| 236 |
+
"FLOAT. Overriding inference_type to FLOAT.")
|
| 237 |
+
converter.inference_type = dtypes.float32
|
| 238 |
+
|
| 239 |
+
if flags.quantize_to_float16:
|
| 240 |
+
converter.target_spec.supported_types = [dtypes.float16]
|
| 241 |
+
if not flags.post_training_quantize:
|
| 242 |
+
print("--quantize_to_float16 will only take effect with the "
|
| 243 |
+
"--post_training_quantize flag enabled.")
|
| 244 |
+
|
| 245 |
+
if flags.dump_graphviz_dir:
|
| 246 |
+
converter.dump_graphviz_dir = flags.dump_graphviz_dir
|
| 247 |
+
if flags.dump_graphviz_video:
|
| 248 |
+
converter.dump_graphviz_vode = flags.dump_graphviz_video
|
| 249 |
+
if flags.conversion_summary_dir:
|
| 250 |
+
converter.conversion_summary_dir = flags.conversion_summary_dir
|
| 251 |
+
|
| 252 |
+
converter.experimental_new_converter = flags.experimental_new_converter
|
| 253 |
+
|
| 254 |
+
if flags.experimental_new_quantizer is not None:
|
| 255 |
+
converter.experimental_new_quantizer = flags.experimental_new_quantizer
|
| 256 |
+
|
| 257 |
+
# Convert model.
|
| 258 |
+
output_data = converter.convert()
|
| 259 |
+
with gfile.GFile(flags.output_file, "wb") as f:
|
| 260 |
+
f.write(output_data)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def _convert_tf2_model(flags):
|
| 264 |
+
"""Calls function to convert the TensorFlow 2.0 model into a TFLite model.
|
| 265 |
+
|
| 266 |
+
Args:
|
| 267 |
+
flags: argparse.Namespace object.
|
| 268 |
+
|
| 269 |
+
Raises:
|
| 270 |
+
ValueError: Unsupported file format.
|
| 271 |
+
"""
|
| 272 |
+
# Load the model.
|
| 273 |
+
if flags.saved_model_dir:
|
| 274 |
+
converter = lite.TFLiteConverterV2.from_saved_model(
|
| 275 |
+
flags.saved_model_dir,
|
| 276 |
+
signature_keys=_parse_array(flags.saved_model_signature_key),
|
| 277 |
+
tags=_parse_set(flags.saved_model_tag_set))
|
| 278 |
+
elif flags.keras_model_file:
|
| 279 |
+
model = keras_deps.get_load_model_function()(flags.keras_model_file)
|
| 280 |
+
converter = lite.TFLiteConverterV2.from_keras_model(model)
|
| 281 |
+
|
| 282 |
+
converter.experimental_new_converter = flags.experimental_new_converter
|
| 283 |
+
|
| 284 |
+
if flags.experimental_new_quantizer is not None:
|
| 285 |
+
converter.experimental_new_quantizer = flags.experimental_new_quantizer
|
| 286 |
+
|
| 287 |
+
# Convert the model.
|
| 288 |
+
tflite_model = converter.convert()
|
| 289 |
+
with gfile.GFile(flags.output_file, "wb") as f:
|
| 290 |
+
f.write(tflite_model)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def _check_tf1_flags(flags, unparsed):
|
| 294 |
+
"""Checks the parsed and unparsed flags to ensure they are valid in 1.X.
|
| 295 |
+
|
| 296 |
+
Raises an error if previously support unparsed flags are found. Raises an
|
| 297 |
+
error for parsed flags that don't meet the required conditions.
|
| 298 |
+
|
| 299 |
+
Args:
|
| 300 |
+
flags: argparse.Namespace object containing TFLite flags.
|
| 301 |
+
unparsed: List of unparsed flags.
|
| 302 |
+
|
| 303 |
+
Raises:
|
| 304 |
+
ValueError: Invalid flags.
|
| 305 |
+
"""
|
| 306 |
+
|
| 307 |
+
# Check unparsed flags for common mistakes based on previous TOCO.
|
| 308 |
+
def _get_message_unparsed(flag, orig_flag, new_flag):
|
| 309 |
+
if flag.startswith(orig_flag):
|
| 310 |
+
return "\n Use {0} instead of {1}".format(new_flag, orig_flag)
|
| 311 |
+
return ""
|
| 312 |
+
|
| 313 |
+
if unparsed:
|
| 314 |
+
output = ""
|
| 315 |
+
for flag in unparsed:
|
| 316 |
+
output += _get_message_unparsed(flag, "--input_file", "--graph_def_file")
|
| 317 |
+
output += _get_message_unparsed(flag, "--savedmodel_directory",
|
| 318 |
+
"--saved_model_dir")
|
| 319 |
+
output += _get_message_unparsed(flag, "--std_value", "--std_dev_values")
|
| 320 |
+
output += _get_message_unparsed(flag, "--batch_size", "--input_shapes")
|
| 321 |
+
output += _get_message_unparsed(flag, "--dump_graphviz",
|
| 322 |
+
"--dump_graphviz_dir")
|
| 323 |
+
if output:
|
| 324 |
+
raise ValueError(output)
|
| 325 |
+
|
| 326 |
+
# Check that flags are valid.
|
| 327 |
+
if flags.graph_def_file and (not flags.input_arrays or
|
| 328 |
+
not flags.output_arrays):
|
| 329 |
+
raise ValueError("--input_arrays and --output_arrays are required with "
|
| 330 |
+
"--graph_def_file")
|
| 331 |
+
|
| 332 |
+
if flags.input_shapes:
|
| 333 |
+
if not flags.input_arrays:
|
| 334 |
+
raise ValueError("--input_shapes must be used with --input_arrays")
|
| 335 |
+
if flags.input_shapes.count(":") != flags.input_arrays.count(","):
|
| 336 |
+
raise ValueError("--input_shapes and --input_arrays must have the same "
|
| 337 |
+
"number of items")
|
| 338 |
+
|
| 339 |
+
if flags.std_dev_values or flags.mean_values:
|
| 340 |
+
if bool(flags.std_dev_values) != bool(flags.mean_values):
|
| 341 |
+
raise ValueError("--std_dev_values and --mean_values must be used "
|
| 342 |
+
"together")
|
| 343 |
+
if flags.std_dev_values.count(",") != flags.mean_values.count(","):
|
| 344 |
+
raise ValueError("--std_dev_values, --mean_values must have the same "
|
| 345 |
+
"number of items")
|
| 346 |
+
|
| 347 |
+
if (flags.default_ranges_min is None) != (flags.default_ranges_max is None):
|
| 348 |
+
raise ValueError("--default_ranges_min and --default_ranges_max must be "
|
| 349 |
+
"used together")
|
| 350 |
+
|
| 351 |
+
if flags.dump_graphviz_video and not flags.dump_graphviz_dir:
|
| 352 |
+
raise ValueError("--dump_graphviz_video must be used with "
|
| 353 |
+
"--dump_graphviz_dir")
|
| 354 |
+
|
| 355 |
+
if flags.custom_opdefs and not flags.experimental_new_converter:
|
| 356 |
+
raise ValueError("--custom_opdefs must be used with "
|
| 357 |
+
"--experimental_new_converter")
|
| 358 |
+
if flags.custom_opdefs and not flags.allow_custom_ops:
|
| 359 |
+
raise ValueError("--custom_opdefs must be used with --allow_custom_ops")
|
| 360 |
+
if (flags.experimental_select_user_tf_ops and
|
| 361 |
+
not flags.experimental_new_converter):
|
| 362 |
+
raise ValueError("--experimental_select_user_tf_ops must be used with "
|
| 363 |
+
"--experimental_new_converter")
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def _check_tf2_flags(flags):
|
| 367 |
+
"""Checks the parsed and unparsed flags to ensure they are valid in 2.X.
|
| 368 |
+
|
| 369 |
+
Args:
|
| 370 |
+
flags: argparse.Namespace object containing TFLite flags.
|
| 371 |
+
|
| 372 |
+
Raises:
|
| 373 |
+
ValueError: Invalid flags.
|
| 374 |
+
"""
|
| 375 |
+
if not flags.keras_model_file and not flags.saved_model_dir:
|
| 376 |
+
raise ValueError("one of the arguments --saved_model_dir "
|
| 377 |
+
"--keras_model_file is required")
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def _get_tf1_flags(parser):
|
| 381 |
+
"""Returns ArgumentParser for tflite_convert for TensorFlow 1.X.
|
| 382 |
+
|
| 383 |
+
Args:
|
| 384 |
+
parser: ArgumentParser
|
| 385 |
+
"""
|
| 386 |
+
# Input file flags.
|
| 387 |
+
input_file_group = parser.add_mutually_exclusive_group(required=True)
|
| 388 |
+
input_file_group.add_argument(
|
| 389 |
+
"--graph_def_file",
|
| 390 |
+
type=str,
|
| 391 |
+
help="Full filepath of file containing frozen TensorFlow GraphDef.")
|
| 392 |
+
input_file_group.add_argument(
|
| 393 |
+
"--saved_model_dir",
|
| 394 |
+
type=str,
|
| 395 |
+
help="Full filepath of directory containing the SavedModel.")
|
| 396 |
+
input_file_group.add_argument(
|
| 397 |
+
"--keras_model_file",
|
| 398 |
+
type=str,
|
| 399 |
+
help="Full filepath of HDF5 file containing tf.Keras model.")
|
| 400 |
+
|
| 401 |
+
# Model format flags.
|
| 402 |
+
parser.add_argument(
|
| 403 |
+
"--output_format",
|
| 404 |
+
type=str.upper,
|
| 405 |
+
choices=["TFLITE", "GRAPHVIZ_DOT"],
|
| 406 |
+
help="Output file format.")
|
| 407 |
+
parser.add_argument(
|
| 408 |
+
"--inference_type",
|
| 409 |
+
type=str.upper,
|
| 410 |
+
default="FLOAT",
|
| 411 |
+
help=("Target data type of real-number arrays in the output file. "
|
| 412 |
+
"Must be either FLOAT, INT8 or UINT8."))
|
| 413 |
+
parser.add_argument(
|
| 414 |
+
"--inference_input_type",
|
| 415 |
+
type=str.upper,
|
| 416 |
+
help=("Target data type of real-number input arrays. Allows for a "
|
| 417 |
+
"different type for input arrays in the case of quantization. "
|
| 418 |
+
"Must be either FLOAT, INT8 or UINT8."))
|
| 419 |
+
|
| 420 |
+
# Input and output arrays flags.
|
| 421 |
+
parser.add_argument(
|
| 422 |
+
"--input_arrays",
|
| 423 |
+
type=str,
|
| 424 |
+
help="Names of the input arrays, comma-separated.")
|
| 425 |
+
parser.add_argument(
|
| 426 |
+
"--input_shapes",
|
| 427 |
+
type=str,
|
| 428 |
+
help="Shapes corresponding to --input_arrays, colon-separated.")
|
| 429 |
+
parser.add_argument(
|
| 430 |
+
"--output_arrays",
|
| 431 |
+
type=str,
|
| 432 |
+
help="Names of the output arrays, comma-separated.")
|
| 433 |
+
|
| 434 |
+
# SavedModel related flags.
|
| 435 |
+
parser.add_argument(
|
| 436 |
+
"--saved_model_tag_set",
|
| 437 |
+
type=str,
|
| 438 |
+
help=("Comma-separated set of tags identifying the MetaGraphDef within "
|
| 439 |
+
"the SavedModel to analyze. All tags must be present. In order to "
|
| 440 |
+
"pass in an empty tag set, pass in \"\". (default \"serve\")"))
|
| 441 |
+
parser.add_argument(
|
| 442 |
+
"--saved_model_signature_key",
|
| 443 |
+
type=str,
|
| 444 |
+
help=("Key identifying the SignatureDef containing inputs and outputs. "
|
| 445 |
+
"(default DEFAULT_SERVING_SIGNATURE_DEF_KEY)"))
|
| 446 |
+
|
| 447 |
+
# Quantization flags.
|
| 448 |
+
parser.add_argument(
|
| 449 |
+
"--std_dev_values",
|
| 450 |
+
type=str,
|
| 451 |
+
help=("Standard deviation of training data for each input tensor, "
|
| 452 |
+
"comma-separated floats. Used for quantized input tensors. "
|
| 453 |
+
"(default None)"))
|
| 454 |
+
parser.add_argument(
|
| 455 |
+
"--mean_values",
|
| 456 |
+
type=str,
|
| 457 |
+
help=("Mean of training data for each input tensor, comma-separated "
|
| 458 |
+
"floats. Used for quantized input tensors. (default None)"))
|
| 459 |
+
parser.add_argument(
|
| 460 |
+
"--default_ranges_min",
|
| 461 |
+
type=float,
|
| 462 |
+
help=("Default value for min bound of min/max range values used for all "
|
| 463 |
+
"arrays without a specified range, Intended for experimenting with "
|
| 464 |
+
"quantization via \"dummy quantization\". (default None)"))
|
| 465 |
+
parser.add_argument(
|
| 466 |
+
"--default_ranges_max",
|
| 467 |
+
type=float,
|
| 468 |
+
help=("Default value for max bound of min/max range values used for all "
|
| 469 |
+
"arrays without a specified range, Intended for experimenting with "
|
| 470 |
+
"quantization via \"dummy quantization\". (default None)"))
|
| 471 |
+
# quantize_weights is DEPRECATED.
|
| 472 |
+
parser.add_argument(
|
| 473 |
+
"--quantize_weights",
|
| 474 |
+
dest="post_training_quantize",
|
| 475 |
+
action="store_true",
|
| 476 |
+
help=argparse.SUPPRESS)
|
| 477 |
+
parser.add_argument(
|
| 478 |
+
"--post_training_quantize",
|
| 479 |
+
dest="post_training_quantize",
|
| 480 |
+
action="store_true",
|
| 481 |
+
help=(
|
| 482 |
+
"Boolean indicating whether to quantize the weights of the "
|
| 483 |
+
"converted float model. Model size will be reduced and there will "
|
| 484 |
+
"be latency improvements (at the cost of accuracy). (default False)"))
|
| 485 |
+
parser.add_argument(
|
| 486 |
+
"--quantize_to_float16",
|
| 487 |
+
dest="quantize_to_float16",
|
| 488 |
+
action="store_true",
|
| 489 |
+
help=("Boolean indicating whether to quantize weights to fp16 instead of "
|
| 490 |
+
"the default int8 when post-training quantization "
|
| 491 |
+
"(--post_training_quantize) is enabled. (default False)"))
|
| 492 |
+
# Graph manipulation flags.
|
| 493 |
+
parser.add_argument(
|
| 494 |
+
"--drop_control_dependency",
|
| 495 |
+
action="store_true",
|
| 496 |
+
help=("Boolean indicating whether to drop control dependencies silently. "
|
| 497 |
+
"This is due to TensorFlow not supporting control dependencies. "
|
| 498 |
+
"(default True)"))
|
| 499 |
+
parser.add_argument(
|
| 500 |
+
"--reorder_across_fake_quant",
|
| 501 |
+
action="store_true",
|
| 502 |
+
help=("Boolean indicating whether to reorder FakeQuant nodes in "
|
| 503 |
+
"unexpected locations. Used when the location of the FakeQuant "
|
| 504 |
+
"nodes is preventing graph transformations necessary to convert "
|
| 505 |
+
"the graph. Results in a graph that differs from the quantized "
|
| 506 |
+
"training graph, potentially causing differing arithmetic "
|
| 507 |
+
"behavior. (default False)"))
|
| 508 |
+
# Usage for this flag is --change_concat_input_ranges=true or
|
| 509 |
+
# --change_concat_input_ranges=false in order to make it clear what the flag
|
| 510 |
+
# is set to. This keeps the usage consistent with other usages of the flag
|
| 511 |
+
# where the default is different. The default value here is False.
|
| 512 |
+
parser.add_argument(
|
| 513 |
+
"--change_concat_input_ranges",
|
| 514 |
+
type=str.upper,
|
| 515 |
+
choices=["TRUE", "FALSE"],
|
| 516 |
+
help=("Boolean to change behavior of min/max ranges for inputs and "
|
| 517 |
+
"outputs of the concat operator for quantized models. Changes the "
|
| 518 |
+
"ranges of concat operator overlap when true. (default False)"))
|
| 519 |
+
|
| 520 |
+
# Permitted ops flags.
|
| 521 |
+
parser.add_argument(
|
| 522 |
+
"--allow_custom_ops",
|
| 523 |
+
action=_ParseBooleanFlag,
|
| 524 |
+
nargs="?",
|
| 525 |
+
help=("Boolean indicating whether to allow custom operations. When false "
|
| 526 |
+
"any unknown operation is an error. When true, custom ops are "
|
| 527 |
+
"created for any op that is unknown. The developer will need to "
|
| 528 |
+
"provide these to the TensorFlow Lite runtime with a custom "
|
| 529 |
+
"resolver. (default False)"))
|
| 530 |
+
parser.add_argument(
|
| 531 |
+
"--custom_opdefs",
|
| 532 |
+
type=str,
|
| 533 |
+
help=("String representing a list of custom ops OpDefs delineated with "
|
| 534 |
+
"commas that are included in the GraphDef. Required when using "
|
| 535 |
+
"custom operations with --experimental_new_converter."))
|
| 536 |
+
parser.add_argument(
|
| 537 |
+
"--target_ops",
|
| 538 |
+
type=str,
|
| 539 |
+
help=("Experimental flag, subject to change. Set of OpsSet options "
|
| 540 |
+
"indicating which converter to use. Options: {0}. One or more "
|
| 541 |
+
"option may be specified. (default set([OpsSet.TFLITE_BUILTINS]))"
|
| 542 |
+
"".format(",".join(lite.OpsSet.get_options()))))
|
| 543 |
+
parser.add_argument(
|
| 544 |
+
"--experimental_select_user_tf_ops",
|
| 545 |
+
type=str,
|
| 546 |
+
help=("Experimental flag, subject to change. Comma separated list of "
|
| 547 |
+
"user's defined TensorFlow operators required in the runtime."))
|
| 548 |
+
|
| 549 |
+
# Logging flags.
|
| 550 |
+
parser.add_argument(
|
| 551 |
+
"--dump_graphviz_dir",
|
| 552 |
+
type=str,
|
| 553 |
+
help=("Full filepath of folder to dump the graphs at various stages of "
|
| 554 |
+
"processing GraphViz .dot files. Preferred over --output_format="
|
| 555 |
+
"GRAPHVIZ_DOT in order to keep the requirements of the output "
|
| 556 |
+
"file."))
|
| 557 |
+
parser.add_argument(
|
| 558 |
+
"--dump_graphviz_video",
|
| 559 |
+
action="store_true",
|
| 560 |
+
help=("Boolean indicating whether to dump the graph after every graph "
|
| 561 |
+
"transformation"))
|
| 562 |
+
parser.add_argument(
|
| 563 |
+
"--conversion_summary_dir",
|
| 564 |
+
type=str,
|
| 565 |
+
help=("Full filepath to store the conversion logs, which includes "
|
| 566 |
+
"graphviz of the model before/after the conversion, an HTML report "
|
| 567 |
+
"and the conversion proto buffers. This will only be generated "
|
| 568 |
+
"when passing --experimental_new_converter"))
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
def _get_tf2_flags(parser):
|
| 572 |
+
"""Returns ArgumentParser for tflite_convert for TensorFlow 2.0.
|
| 573 |
+
|
| 574 |
+
Args:
|
| 575 |
+
parser: ArgumentParser
|
| 576 |
+
"""
|
| 577 |
+
# Input file flags.
|
| 578 |
+
input_file_group = parser.add_mutually_exclusive_group()
|
| 579 |
+
input_file_group.add_argument(
|
| 580 |
+
"--saved_model_dir",
|
| 581 |
+
type=str,
|
| 582 |
+
help="Full path of the directory containing the SavedModel.")
|
| 583 |
+
input_file_group.add_argument(
|
| 584 |
+
"--keras_model_file",
|
| 585 |
+
type=str,
|
| 586 |
+
help="Full filepath of HDF5 file containing tf.Keras model.")
|
| 587 |
+
# SavedModel related flags.
|
| 588 |
+
parser.add_argument(
|
| 589 |
+
"--saved_model_tag_set",
|
| 590 |
+
type=str,
|
| 591 |
+
help=("Comma-separated set of tags identifying the MetaGraphDef within "
|
| 592 |
+
"the SavedModel to analyze. All tags must be present. In order to "
|
| 593 |
+
"pass in an empty tag set, pass in \"\". (default \"serve\")"))
|
| 594 |
+
parser.add_argument(
|
| 595 |
+
"--saved_model_signature_key",
|
| 596 |
+
type=str,
|
| 597 |
+
help=("Key identifying the SignatureDef containing inputs and outputs. "
|
| 598 |
+
"(default DEFAULT_SERVING_SIGNATURE_DEF_KEY)"))
|
| 599 |
+
|
| 600 |
+
# Enables 1.X converter in 2.X.
|
| 601 |
+
parser.add_argument(
|
| 602 |
+
"--enable_v1_converter",
|
| 603 |
+
action="store_true",
|
| 604 |
+
help=("Enables the TensorFlow V1 converter in 2.0"))
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
def _get_parser(use_v2_converter):
|
| 608 |
+
"""Returns an ArgumentParser for tflite_convert.
|
| 609 |
+
|
| 610 |
+
Args:
|
| 611 |
+
use_v2_converter: Indicates which converter to return.
|
| 612 |
+
Return: ArgumentParser.
|
| 613 |
+
"""
|
| 614 |
+
parser = argparse.ArgumentParser(
|
| 615 |
+
description=("Command line tool to run TensorFlow Lite Converter."))
|
| 616 |
+
|
| 617 |
+
# Output file flag.
|
| 618 |
+
parser.add_argument(
|
| 619 |
+
"--output_file",
|
| 620 |
+
type=str,
|
| 621 |
+
help="Full filepath of the output file.",
|
| 622 |
+
required=True)
|
| 623 |
+
|
| 624 |
+
if use_v2_converter:
|
| 625 |
+
_get_tf2_flags(parser)
|
| 626 |
+
else:
|
| 627 |
+
_get_tf1_flags(parser)
|
| 628 |
+
|
| 629 |
+
parser.add_argument(
|
| 630 |
+
"--experimental_new_converter",
|
| 631 |
+
action=_ParseBooleanFlag,
|
| 632 |
+
nargs="?",
|
| 633 |
+
default=True,
|
| 634 |
+
help=("Experimental flag, subject to change. Enables MLIR-based "
|
| 635 |
+
"conversion instead of TOCO conversion. (default True)"))
|
| 636 |
+
|
| 637 |
+
parser.add_argument(
|
| 638 |
+
"--experimental_new_quantizer",
|
| 639 |
+
action=_ParseBooleanFlag,
|
| 640 |
+
nargs="?",
|
| 641 |
+
help=("Experimental flag, subject to change. Enables MLIR-based "
|
| 642 |
+
"quantizer instead of flatbuffer conversion. (default True)"))
|
| 643 |
+
return parser
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
def run_main(_):
|
| 647 |
+
"""Main in tflite_convert.py."""
|
| 648 |
+
use_v2_converter = tf2.enabled()
|
| 649 |
+
parser = _get_parser(use_v2_converter)
|
| 650 |
+
tflite_flags, unparsed = parser.parse_known_args(args=sys.argv[1:])
|
| 651 |
+
|
| 652 |
+
# If the user is running TensorFlow 2.X but has passed in enable_v1_converter
|
| 653 |
+
# then parse the flags again with the 1.X converter flags.
|
| 654 |
+
if tf2.enabled() and tflite_flags.enable_v1_converter:
|
| 655 |
+
use_v2_converter = False
|
| 656 |
+
parser = _get_parser(use_v2_converter)
|
| 657 |
+
tflite_flags, unparsed = parser.parse_known_args(args=sys.argv[1:])
|
| 658 |
+
|
| 659 |
+
# Checks if the flags are valid.
|
| 660 |
+
try:
|
| 661 |
+
if use_v2_converter:
|
| 662 |
+
_check_tf2_flags(tflite_flags)
|
| 663 |
+
else:
|
| 664 |
+
_check_tf1_flags(tflite_flags, unparsed)
|
| 665 |
+
except ValueError as e:
|
| 666 |
+
parser.print_usage()
|
| 667 |
+
file_name = os.path.basename(sys.argv[0])
|
| 668 |
+
sys.stderr.write("{0}: error: {1}\n".format(file_name, str(e)))
|
| 669 |
+
sys.exit(1)
|
| 670 |
+
|
| 671 |
+
# Convert the model according to the user provided flag.
|
| 672 |
+
if use_v2_converter:
|
| 673 |
+
_convert_tf2_model(tflite_flags)
|
| 674 |
+
else:
|
| 675 |
+
try:
|
| 676 |
+
_convert_tf1_model(tflite_flags)
|
| 677 |
+
finally:
|
| 678 |
+
if tflite_flags.conversion_summary_dir:
|
| 679 |
+
if tflite_flags.experimental_new_converter:
|
| 680 |
+
gen_html.gen_conversion_log_html(tflite_flags.conversion_summary_dir,
|
| 681 |
+
tflite_flags.post_training_quantize,
|
| 682 |
+
tflite_flags.output_file)
|
| 683 |
+
else:
|
| 684 |
+
warnings.warn(
|
| 685 |
+
"Conversion summary will only be generated when enabling"
|
| 686 |
+
" the new converter via --experimental_new_converter. ")
|
| 687 |
+
|
| 688 |
+
|
| 689 |
+
def main():
|
| 690 |
+
app.run(main=run_main, argv=sys.argv[:1])
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
if __name__ == "__main__":
|
| 694 |
+
main()
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/tflite_keras_util.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 16 |
+
"""Keras functions required by TensorFlow Lite.
|
| 17 |
+
|
| 18 |
+
The functions defined in this library have been copied over from Keras in order
|
| 19 |
+
to remove the dependency from TensorFlow Lite to Keras. The functions which
|
| 20 |
+
could not be copied over are accessed using the dependency inversion principle.
|
| 21 |
+
(for details, refer to tensorflow/python/util/keras_deps.py).
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
import copy
|
| 25 |
+
|
| 26 |
+
from tensorflow.python.eager import def_function
|
| 27 |
+
from tensorflow.python.util import keras_deps
|
| 28 |
+
from tensorflow.python.util import nest
|
| 29 |
+
from tensorflow.python.util.compat import collections_abc
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _enforce_names_consistency(specs):
|
| 33 |
+
"""Enforces that either all specs have names or none do."""
|
| 34 |
+
|
| 35 |
+
def _has_name(spec):
|
| 36 |
+
return hasattr(spec, 'name') and spec.name is not None
|
| 37 |
+
|
| 38 |
+
def _clear_name(spec):
|
| 39 |
+
spec = copy.deepcopy(spec)
|
| 40 |
+
if hasattr(spec, 'name'):
|
| 41 |
+
spec._name = None # pylint:disable=protected-access
|
| 42 |
+
return spec
|
| 43 |
+
|
| 44 |
+
flat_specs = nest.flatten(specs)
|
| 45 |
+
name_inconsistency = (
|
| 46 |
+
any(_has_name(s) for s in flat_specs) and
|
| 47 |
+
not all(_has_name(s) for s in flat_specs))
|
| 48 |
+
|
| 49 |
+
if name_inconsistency:
|
| 50 |
+
specs = nest.map_structure(_clear_name, specs)
|
| 51 |
+
return specs
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def model_input_signature(model, keep_original_batch_size=False):
|
| 55 |
+
"""Inspect model to get its input signature.
|
| 56 |
+
|
| 57 |
+
The model's input signature is a list with a single (possibly-nested) object.
|
| 58 |
+
This is due to the Keras-enforced restriction that tensor inputs must be
|
| 59 |
+
passed in as the first argument.
|
| 60 |
+
|
| 61 |
+
For example, a model with input {'feature1': <Tensor>, 'feature2': <Tensor>}
|
| 62 |
+
will have input signature: [{'feature1': TensorSpec, 'feature2': TensorSpec}]
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
model: Keras Model object.
|
| 66 |
+
keep_original_batch_size: A boolean indicating whether we want to keep using
|
| 67 |
+
the original batch size or set it to None. Default is `False`, which means
|
| 68 |
+
that the batch dim of the returned input signature will always be set to
|
| 69 |
+
`None`.
|
| 70 |
+
|
| 71 |
+
Returns:
|
| 72 |
+
A list containing either a single TensorSpec or an object with nested
|
| 73 |
+
TensorSpecs. This list does not contain the `training` argument.
|
| 74 |
+
"""
|
| 75 |
+
if hasattr(model, 'save_spec'):
|
| 76 |
+
input_specs = model.save_spec(dynamic_batch=not keep_original_batch_size)
|
| 77 |
+
if input_specs is None:
|
| 78 |
+
return None
|
| 79 |
+
# The model's save spec returns (args, kwargs). Extract the first input arg
|
| 80 |
+
# to use as the input spec.
|
| 81 |
+
# TODO(b/188105669): Add support for multiple tensor arguments.
|
| 82 |
+
input_specs = input_specs[0][0]
|
| 83 |
+
else:
|
| 84 |
+
input_specs = model._get_save_spec( # pylint: disable=protected-access
|
| 85 |
+
dynamic_batch=not keep_original_batch_size)
|
| 86 |
+
if input_specs is None:
|
| 87 |
+
return None
|
| 88 |
+
input_specs = _enforce_names_consistency(input_specs)
|
| 89 |
+
# Return a list with a single element as the model's input signature.
|
| 90 |
+
if isinstance(input_specs,
|
| 91 |
+
collections_abc.Sequence) and len(input_specs) == 1:
|
| 92 |
+
# Note that the isinstance check filters out single-element dictionaries,
|
| 93 |
+
# which should also be wrapped as a single-element list.
|
| 94 |
+
return input_specs
|
| 95 |
+
else:
|
| 96 |
+
return [input_specs]
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def raise_model_input_error(model):
|
| 100 |
+
raise ValueError(
|
| 101 |
+
'Model {} cannot be saved because the input shapes have not been '
|
| 102 |
+
'set. Usually, input shapes are automatically determined from calling'
|
| 103 |
+
' `.fit()` or `.predict()`. To manually set the shapes, call '
|
| 104 |
+
'`model.build(input_shape)`.'.format(model))
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _create_pseudo_names(tensors, prefix):
|
| 108 |
+
"""Creates pseudo {input | output} names for subclassed Models.
|
| 109 |
+
|
| 110 |
+
Warning: this function should only be used to define default
|
| 111 |
+
names for `Metics` and `SavedModel`. No other use cases should
|
| 112 |
+
rely on a `Model`'s input or output names.
|
| 113 |
+
|
| 114 |
+
Example with dict:
|
| 115 |
+
|
| 116 |
+
`{'a': [x1, x2], 'b': x3}` becomes:
|
| 117 |
+
`['a_1', 'a_2', 'b']`
|
| 118 |
+
|
| 119 |
+
Example with list:
|
| 120 |
+
|
| 121 |
+
`[x, y]` becomes:
|
| 122 |
+
`['output_1', 'output_2']`
|
| 123 |
+
|
| 124 |
+
Args:
|
| 125 |
+
tensors: `Model`'s outputs or inputs.
|
| 126 |
+
prefix: 'output_' for outputs, 'input_' for inputs.
|
| 127 |
+
|
| 128 |
+
Returns:
|
| 129 |
+
Flattened list of pseudo names.
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
def one_index(ele):
|
| 133 |
+
# Start with "output_1" instead of "output_0".
|
| 134 |
+
if isinstance(ele, int):
|
| 135 |
+
return ele + 1
|
| 136 |
+
return ele
|
| 137 |
+
|
| 138 |
+
flat_paths = list(nest.yield_flat_paths(tensors))
|
| 139 |
+
flat_paths = nest.map_structure(one_index, flat_paths)
|
| 140 |
+
names = []
|
| 141 |
+
for path in flat_paths:
|
| 142 |
+
if not path:
|
| 143 |
+
name = prefix + '1' # Single output.
|
| 144 |
+
else:
|
| 145 |
+
name = '_'.join(str(p) for p in path)
|
| 146 |
+
if isinstance(path[0], int):
|
| 147 |
+
name = prefix + name
|
| 148 |
+
names.append(name)
|
| 149 |
+
return names
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def create_pseudo_output_names(outputs):
|
| 153 |
+
"""Create pseudo output names for a subclassed Model."""
|
| 154 |
+
return _create_pseudo_names(outputs, prefix='output_')
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def trace_model_call(model, input_signature=None):
|
| 158 |
+
"""Trace the model call to create a tf.function for exporting a Keras model.
|
| 159 |
+
|
| 160 |
+
Args:
|
| 161 |
+
model: A Keras model.
|
| 162 |
+
input_signature: optional, a list of tf.TensorSpec objects specifying the
|
| 163 |
+
inputs to the model.
|
| 164 |
+
|
| 165 |
+
Returns:
|
| 166 |
+
A tf.function wrapping the model's call function with input signatures set.
|
| 167 |
+
|
| 168 |
+
Raises:
|
| 169 |
+
ValueError: if input signature cannot be inferred from the model.
|
| 170 |
+
"""
|
| 171 |
+
if input_signature is None:
|
| 172 |
+
if isinstance(model.call, def_function.Function):
|
| 173 |
+
input_signature = model.call.input_signature
|
| 174 |
+
|
| 175 |
+
if input_signature is None:
|
| 176 |
+
input_signature = model_input_signature(model)
|
| 177 |
+
|
| 178 |
+
if input_signature is None:
|
| 179 |
+
raise_model_input_error(model)
|
| 180 |
+
|
| 181 |
+
@def_function.function(input_signature=input_signature, autograph=False)
|
| 182 |
+
def _wrapped_model(*args):
|
| 183 |
+
"""A concrete tf.function that wraps the model's call function."""
|
| 184 |
+
# When given a single input, Keras models will call the model on the tensor
|
| 185 |
+
# rather than a list consisting of the single tensor.
|
| 186 |
+
inputs = args[0] if len(input_signature) == 1 else list(args)
|
| 187 |
+
|
| 188 |
+
with keras_deps.get_call_context_function()().enter(
|
| 189 |
+
model, inputs=inputs, build_graph=False, training=False, saving=True):
|
| 190 |
+
outputs = model(inputs, training=False)
|
| 191 |
+
|
| 192 |
+
return outputs
|
| 193 |
+
|
| 194 |
+
return _wrapped_model
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/util.py
ADDED
|
@@ -0,0 +1,1070 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
"""Functions used by multiple converter files."""
|
| 16 |
+
|
| 17 |
+
import copy
|
| 18 |
+
import datetime
|
| 19 |
+
import sys
|
| 20 |
+
|
| 21 |
+
from absl import logging
|
| 22 |
+
import flatbuffers
|
| 23 |
+
|
| 24 |
+
from tensorflow.core.protobuf import config_pb2 as _config_pb2
|
| 25 |
+
from tensorflow.core.protobuf import meta_graph_pb2 as _meta_graph_pb2
|
| 26 |
+
from tensorflow.lite.python import conversion_metadata_schema_py_generated as conversion_metadata_fb
|
| 27 |
+
from tensorflow.lite.python import schema_py_generated as schema_fb
|
| 28 |
+
from tensorflow.lite.python import schema_util
|
| 29 |
+
from tensorflow.lite.python import tflite_keras_util as _tflite_keras_util
|
| 30 |
+
from tensorflow.lite.python.op_hint import convert_op_hints_to_stubs
|
| 31 |
+
from tensorflow.lite.python.op_hint import find_all_hinted_output_nodes
|
| 32 |
+
from tensorflow.lite.tools import flatbuffer_utils
|
| 33 |
+
from tensorflow.python.eager import function
|
| 34 |
+
from tensorflow.python.framework import convert_to_constants as _convert_to_constants
|
| 35 |
+
from tensorflow.python.framework import dtypes
|
| 36 |
+
from tensorflow.python.framework import error_interpolation as _error_interpolation
|
| 37 |
+
from tensorflow.python.grappler import tf_optimizer
|
| 38 |
+
from tensorflow.python.training.saver import export_meta_graph as _export_meta_graph
|
| 39 |
+
|
| 40 |
+
# The field name of conversion metadata in the flatbuffer file.
|
| 41 |
+
CONVERSION_METADATA_FIELD_NAME = "CONVERSION_METADATA"
|
| 42 |
+
|
| 43 |
+
# Keras functions used by TFLite
|
| 44 |
+
model_input_signature = _tflite_keras_util.model_input_signature
|
| 45 |
+
trace_model_call = _tflite_keras_util.trace_model_call
|
| 46 |
+
|
| 47 |
+
# Jax functions used by TFLite
|
| 48 |
+
# pylint: disable=g-import-not-at-top
|
| 49 |
+
# pylint: disable=unused-import
|
| 50 |
+
try:
|
| 51 |
+
from jax import xla_computation as _xla_computation
|
| 52 |
+
except ImportError:
|
| 53 |
+
_xla_computation = None
|
| 54 |
+
# pylint: enable=g-import-not-at-top
|
| 55 |
+
# pylint: enable=unused-import
|
| 56 |
+
|
| 57 |
+
# Defined as per TFLite schema
|
| 58 |
+
_MAP_TFLITE_ENUM_TO_TF_TYPES = {
|
| 59 |
+
0: dtypes.float32,
|
| 60 |
+
1: dtypes.float16,
|
| 61 |
+
2: dtypes.int32,
|
| 62 |
+
3: dtypes.uint8,
|
| 63 |
+
4: dtypes.int64,
|
| 64 |
+
5: dtypes.string,
|
| 65 |
+
6: dtypes.bool,
|
| 66 |
+
7: dtypes.int16,
|
| 67 |
+
8: dtypes.complex64,
|
| 68 |
+
9: dtypes.int8,
|
| 69 |
+
10: dtypes.float64,
|
| 70 |
+
11: dtypes.complex128,
|
| 71 |
+
16: dtypes.uint32,
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
_TFLITE_FILE_IDENTIFIER = b"TFL3"
|
| 75 |
+
|
| 76 |
+
_MAP_QUANT_TO_IO_TYPES = {
|
| 77 |
+
dtypes.int8: {dtypes.int8, dtypes.uint8},
|
| 78 |
+
dtypes.int16: {dtypes.int16},
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _convert_tflite_enum_type_to_tf_type(tflite_enum_type):
|
| 83 |
+
"""Converts tflite enum type (eg: 0) to tf type (eg: tf.float32).
|
| 84 |
+
|
| 85 |
+
Args:
|
| 86 |
+
tflite_enum_type: tflite enum type (eg: 0, that corresponds to float32)
|
| 87 |
+
|
| 88 |
+
Raises:
|
| 89 |
+
ValueError: If an invalid tflite enum type is provided.
|
| 90 |
+
|
| 91 |
+
Returns:
|
| 92 |
+
tf type (eg: tf.float32)
|
| 93 |
+
"""
|
| 94 |
+
tf_type = _MAP_TFLITE_ENUM_TO_TF_TYPES.get(tflite_enum_type)
|
| 95 |
+
if tf_type is None:
|
| 96 |
+
raise ValueError(
|
| 97 |
+
"Unsupported enum {}. The valid map of enum to tf types is : {}"
|
| 98 |
+
.format(tflite_enum_type, _MAP_TFLITE_ENUM_TO_TF_TYPES))
|
| 99 |
+
return tf_type
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def get_tf_type_name(tf_type):
|
| 103 |
+
"""Converts tf.dtype (eg: tf.float32) to str (eg: "tf.float32")."""
|
| 104 |
+
return "tf." + tf_type.name if tf_type else None
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def get_tensor_name(tensor):
|
| 108 |
+
"""Returns name of the input tensor.
|
| 109 |
+
|
| 110 |
+
Args:
|
| 111 |
+
tensor: tf.Tensor
|
| 112 |
+
|
| 113 |
+
Returns:
|
| 114 |
+
str
|
| 115 |
+
"""
|
| 116 |
+
parts = tensor.name.split(":")
|
| 117 |
+
if len(parts) > 2:
|
| 118 |
+
raise ValueError("Tensor name invalid. Expect 0 or 1 colon, got {0}".format(
|
| 119 |
+
len(parts) - 1))
|
| 120 |
+
|
| 121 |
+
# To be consistent with the tensor naming scheme in tensorflow, we need
|
| 122 |
+
# drop the ':0' suffix for the first tensor.
|
| 123 |
+
if len(parts) > 1 and parts[1] != "0":
|
| 124 |
+
return tensor.name
|
| 125 |
+
return parts[0]
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def get_tensors_from_tensor_names(graph, tensor_names):
|
| 129 |
+
"""Gets the Tensors associated with the `tensor_names` in the provided graph.
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
graph: TensorFlow Graph.
|
| 133 |
+
tensor_names: List of strings that represent names of tensors in the graph.
|
| 134 |
+
|
| 135 |
+
Returns:
|
| 136 |
+
A list of Tensor objects in the same order the names are provided.
|
| 137 |
+
|
| 138 |
+
Raises:
|
| 139 |
+
ValueError:
|
| 140 |
+
tensor_names contains an invalid tensor name.
|
| 141 |
+
"""
|
| 142 |
+
# Get the list of all of the tensors.
|
| 143 |
+
tensor_name_to_tensor = {}
|
| 144 |
+
for op in graph.get_operations():
|
| 145 |
+
for tensor in op.values():
|
| 146 |
+
tensor_name_to_tensor[get_tensor_name(tensor)] = tensor
|
| 147 |
+
|
| 148 |
+
# Get the tensors associated with tensor_names.
|
| 149 |
+
tensors = []
|
| 150 |
+
invalid_tensors = []
|
| 151 |
+
for name in tensor_names:
|
| 152 |
+
if not isinstance(name, str):
|
| 153 |
+
raise ValueError("Invalid type for a tensor name in the provided graph. "
|
| 154 |
+
"Expected type for a tensor name is 'str', instead got "
|
| 155 |
+
"type '{}' for tensor name '{}'".format(
|
| 156 |
+
type(name), name))
|
| 157 |
+
|
| 158 |
+
tensor = tensor_name_to_tensor.get(name)
|
| 159 |
+
if tensor is None:
|
| 160 |
+
invalid_tensors.append(name)
|
| 161 |
+
else:
|
| 162 |
+
tensors.append(tensor)
|
| 163 |
+
|
| 164 |
+
# Throw ValueError if any user input names are not valid tensors.
|
| 165 |
+
if invalid_tensors:
|
| 166 |
+
raise ValueError("Invalid tensors '{}' were found.".format(
|
| 167 |
+
",".join(invalid_tensors)))
|
| 168 |
+
return tensors
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def set_tensor_shapes(tensors, shapes):
|
| 172 |
+
"""Sets Tensor shape for each tensor if the shape is defined.
|
| 173 |
+
|
| 174 |
+
Args:
|
| 175 |
+
tensors: TensorFlow tensor.Tensor.
|
| 176 |
+
shapes: Dict of strings representing input tensor names to list of
|
| 177 |
+
integers representing input shapes (e.g., {"foo": : [1, 16, 16, 3]}).
|
| 178 |
+
|
| 179 |
+
Raises:
|
| 180 |
+
ValueError:
|
| 181 |
+
`shapes` contains an invalid tensor.
|
| 182 |
+
`shapes` contains an invalid shape for a valid tensor.
|
| 183 |
+
"""
|
| 184 |
+
if shapes:
|
| 185 |
+
tensor_names_to_tensor = {
|
| 186 |
+
get_tensor_name(tensor): tensor for tensor in tensors
|
| 187 |
+
}
|
| 188 |
+
for name, shape in shapes.items():
|
| 189 |
+
if name not in tensor_names_to_tensor:
|
| 190 |
+
raise ValueError("Invalid tensor \'{}\' found in tensor shapes "
|
| 191 |
+
"map.".format(name))
|
| 192 |
+
if shape is not None:
|
| 193 |
+
tensor = tensor_names_to_tensor[name]
|
| 194 |
+
try:
|
| 195 |
+
tensor.set_shape(shape)
|
| 196 |
+
except ValueError as error:
|
| 197 |
+
message = ("The shape of tensor '{0}' cannot be changed from {1} to "
|
| 198 |
+
"{2}. {3}".format(name, tensor.shape, shape, str(error)))
|
| 199 |
+
raise ValueError(message)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def get_grappler_config(optimizers_list):
|
| 203 |
+
"""Creates a tf.compat.v1.ConfigProto for configuring Grappler.
|
| 204 |
+
|
| 205 |
+
Args:
|
| 206 |
+
optimizers_list: List of strings that represents the list of optimizers.
|
| 207 |
+
|
| 208 |
+
Returns:
|
| 209 |
+
tf.ConfigProto.
|
| 210 |
+
"""
|
| 211 |
+
config = _config_pb2.ConfigProto()
|
| 212 |
+
rewrite_options = config.graph_options.rewrite_options
|
| 213 |
+
for optimizer in optimizers_list:
|
| 214 |
+
rewrite_options.optimizers.append(optimizer)
|
| 215 |
+
return config
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def run_graph_optimizations(graph_def,
|
| 219 |
+
input_arrays,
|
| 220 |
+
output_arrays,
|
| 221 |
+
config,
|
| 222 |
+
graph=None):
|
| 223 |
+
"""Apply standard TensorFlow optimizations to the graph_def.
|
| 224 |
+
|
| 225 |
+
Args:
|
| 226 |
+
graph_def: Frozen GraphDef to be optimized.
|
| 227 |
+
input_arrays: List of arrays that are considered inputs of the graph.
|
| 228 |
+
output_arrays: List of arrays that are considered outputs of the graph.
|
| 229 |
+
config: tf.ConfigProto.
|
| 230 |
+
graph: TensorFlow Graph. Required when Eager mode is enabled. (default None)
|
| 231 |
+
|
| 232 |
+
Returns:
|
| 233 |
+
A new, optimized GraphDef.
|
| 234 |
+
"""
|
| 235 |
+
meta_graph = _export_meta_graph(graph_def=graph_def, graph=graph)
|
| 236 |
+
|
| 237 |
+
signature = _meta_graph_pb2.SignatureDef()
|
| 238 |
+
for array in input_arrays:
|
| 239 |
+
signature.inputs[array.name].name = array.name
|
| 240 |
+
signature.inputs[array.name].dtype = array.dtype.as_datatype_enum
|
| 241 |
+
signature.inputs[array.name].tensor_shape.CopyFrom(array.shape.as_proto())
|
| 242 |
+
|
| 243 |
+
for array in output_arrays:
|
| 244 |
+
signature.outputs[array.name].name = array.name
|
| 245 |
+
signature.outputs[array.name].dtype = array.dtype.as_datatype_enum
|
| 246 |
+
signature.outputs[array.name].tensor_shape.CopyFrom(array.shape.as_proto())
|
| 247 |
+
|
| 248 |
+
meta_graph.signature_def["not_used_key"].CopyFrom(signature)
|
| 249 |
+
|
| 250 |
+
# We need to add a collection called 'train_op' so that grappler
|
| 251 |
+
# knows what the outputs are.
|
| 252 |
+
fetch_collection = _meta_graph_pb2.CollectionDef()
|
| 253 |
+
for array in input_arrays + output_arrays:
|
| 254 |
+
fetch_collection.node_list.value.append(array.name)
|
| 255 |
+
meta_graph.collection_def["train_op"].CopyFrom(fetch_collection)
|
| 256 |
+
|
| 257 |
+
return tf_optimizer.OptimizeGraph(config, meta_graph)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def _convert_op_hints_if_present(sess, graph_def, output_tensors,
|
| 261 |
+
hinted_outputs_nodes):
|
| 262 |
+
if is_frozen_graph(sess):
|
| 263 |
+
raise ValueError("Try to convert op hints, needs unfrozen graph.")
|
| 264 |
+
output_arrays = [get_tensor_name(tensor) for tensor in output_tensors]
|
| 265 |
+
graph_def = _convert_to_constants.convert_variables_to_constants(
|
| 266 |
+
sess, graph_def, output_arrays + hinted_outputs_nodes)
|
| 267 |
+
graph_def = convert_op_hints_to_stubs(graph_def=graph_def)
|
| 268 |
+
return graph_def
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def freeze_graph(sess, input_tensors, output_tensors):
|
| 272 |
+
"""Returns a frozen GraphDef.
|
| 273 |
+
|
| 274 |
+
Runs a Grappler pass and freezes a graph with Variables in it. Otherwise the
|
| 275 |
+
existing GraphDef is returned. The Grappler pass is only run on models that
|
| 276 |
+
are frozen in order to inline the functions in the graph.
|
| 277 |
+
If OpHints is present, it will try to convert the OpHint graph.
|
| 278 |
+
|
| 279 |
+
Args:
|
| 280 |
+
sess: TensorFlow Session.
|
| 281 |
+
input_tensors: List of input tensors.
|
| 282 |
+
output_tensors: List of output tensors (only .name is used from this).
|
| 283 |
+
|
| 284 |
+
Returns:
|
| 285 |
+
Frozen GraphDef.
|
| 286 |
+
"""
|
| 287 |
+
# Runs a Grappler pass in order to inline any functions in the graph.
|
| 288 |
+
# Asides from inlining any simple function, Grappler will also try to lower
|
| 289 |
+
# while loop into switch merge representation which is undesired for Ophints,
|
| 290 |
+
# so we simply remove those attributes to prevent Grappler from doing so.
|
| 291 |
+
graph_def = _convert_to_constants.disable_lower_using_switch_merge(
|
| 292 |
+
sess.graph_def)
|
| 293 |
+
config = get_grappler_config(["function"])
|
| 294 |
+
graph_def = run_graph_optimizations(
|
| 295 |
+
graph_def, input_tensors, output_tensors, config, graph=sess.graph)
|
| 296 |
+
|
| 297 |
+
# If ophints are present, just convert them.
|
| 298 |
+
hinted_outputs_nodes = find_all_hinted_output_nodes(sess)
|
| 299 |
+
if hinted_outputs_nodes:
|
| 300 |
+
return _convert_op_hints_if_present(sess, graph_def, output_tensors,
|
| 301 |
+
hinted_outputs_nodes)
|
| 302 |
+
|
| 303 |
+
if not is_frozen_graph(sess):
|
| 304 |
+
output_node_names = [tensor.name.split(":")[0] for tensor in output_tensors]
|
| 305 |
+
return _convert_to_constants.convert_variables_to_constants(
|
| 306 |
+
sess, graph_def, output_node_names
|
| 307 |
+
)
|
| 308 |
+
else:
|
| 309 |
+
return sess.graph_def
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def is_frozen_graph(sess):
|
| 313 |
+
"""Determines if the graph is frozen.
|
| 314 |
+
|
| 315 |
+
Determines if a graph has previously been frozen by checking for any
|
| 316 |
+
operations of type Variable*. If variables are found, the graph is not frozen.
|
| 317 |
+
|
| 318 |
+
Args:
|
| 319 |
+
sess: TensorFlow Session.
|
| 320 |
+
|
| 321 |
+
Returns:
|
| 322 |
+
Bool.
|
| 323 |
+
"""
|
| 324 |
+
for op in sess.graph.get_operations():
|
| 325 |
+
if op.type.startswith("Variable") or op.type.endswith("VariableOp"):
|
| 326 |
+
return False
|
| 327 |
+
return True
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def build_debug_info_func(original_graph):
|
| 331 |
+
"""Returns a method to retrieve the `GraphDebugInfo` from the original graph.
|
| 332 |
+
|
| 333 |
+
Args:
|
| 334 |
+
original_graph: The original `Graph` containing all the op stack traces.
|
| 335 |
+
|
| 336 |
+
Returns:
|
| 337 |
+
A function which retrieves the stack traces from the original graph and
|
| 338 |
+
converts them to a `GraphDebugInfo` for a given set of nodes.
|
| 339 |
+
"""
|
| 340 |
+
|
| 341 |
+
def f(original_nodes):
|
| 342 |
+
"""Function to create `GraphDebugInfo` for the given `original_nodes`."""
|
| 343 |
+
if not original_graph:
|
| 344 |
+
return None
|
| 345 |
+
# For the given nodes, gets all the op definitions in the original graph.
|
| 346 |
+
useful_ops = []
|
| 347 |
+
for func, name in original_nodes:
|
| 348 |
+
try:
|
| 349 |
+
if not func:
|
| 350 |
+
useful_ops.append((func, original_graph.get_operation_by_name(name)))
|
| 351 |
+
else:
|
| 352 |
+
sub_func = original_graph._get_function(func) # pylint: disable=protected-access
|
| 353 |
+
if isinstance(sub_func, function.AtomicFunction): # pylint: disable=protected-access
|
| 354 |
+
useful_ops.append(
|
| 355 |
+
(func, sub_func.graph.get_operation_by_name(name)))
|
| 356 |
+
else:
|
| 357 |
+
sys.stderr.write(
|
| 358 |
+
"Use '@tf.function' or '@defun' to decorate the function.\n")
|
| 359 |
+
continue
|
| 360 |
+
except KeyError:
|
| 361 |
+
# New node created by graph optimizer. No stack trace from source code.
|
| 362 |
+
continue
|
| 363 |
+
# Convert all the op definitions to stack traces in terms of GraphDebugInfo.
|
| 364 |
+
return _error_interpolation.create_graph_debug_info_def(useful_ops)
|
| 365 |
+
|
| 366 |
+
return f
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def convert_debug_info_func(saved_debug_info):
|
| 370 |
+
"""Returns a method to retrieve the `GraphDebugInfo` from the original graph.
|
| 371 |
+
|
| 372 |
+
Args:
|
| 373 |
+
saved_debug_info: The `GraphDebugInfo` containing all the debug info.
|
| 374 |
+
|
| 375 |
+
Returns:
|
| 376 |
+
A function which retrieves the stack traces from the original graph and
|
| 377 |
+
converts them to a `GraphDebugInfo` for a given set of nodes.
|
| 378 |
+
"""
|
| 379 |
+
|
| 380 |
+
def f(original_nodes):
|
| 381 |
+
"""Function to create `GraphDebugInfo` for the given `original_nodes`."""
|
| 382 |
+
del original_nodes
|
| 383 |
+
return saved_debug_info
|
| 384 |
+
|
| 385 |
+
return f
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def get_debug_info(nodes_to_debug_info_func, converted_graph):
|
| 389 |
+
"""Returns the debug info for the original nodes in the `converted_graph`.
|
| 390 |
+
|
| 391 |
+
Args:
|
| 392 |
+
nodes_to_debug_info_func: The method to collect the op debug info for the
|
| 393 |
+
nodes.
|
| 394 |
+
converted_graph: A `GraphDef` after optimization and transformation.
|
| 395 |
+
|
| 396 |
+
Returns:
|
| 397 |
+
`GraphDebugInfo` for all the original nodes in `converted_graph`.
|
| 398 |
+
"""
|
| 399 |
+
if not nodes_to_debug_info_func:
|
| 400 |
+
return None
|
| 401 |
+
|
| 402 |
+
# Collect all the debug info nodes from the converted_graph
|
| 403 |
+
original_nodes = set()
|
| 404 |
+
for node in converted_graph.node:
|
| 405 |
+
debug_nodes = node.experimental_debug_info.original_node_names
|
| 406 |
+
debug_funcs = node.experimental_debug_info.original_func_names
|
| 407 |
+
# If the `original_node_names` are empty, uses the node name directly.
|
| 408 |
+
if not debug_nodes:
|
| 409 |
+
original_nodes.add(("", node.name))
|
| 410 |
+
else:
|
| 411 |
+
for i in range(len(debug_nodes)):
|
| 412 |
+
debug_func = "" if i >= len(debug_funcs) else debug_funcs[i]
|
| 413 |
+
original_nodes.add((debug_func, debug_nodes[i]))
|
| 414 |
+
|
| 415 |
+
# Convert the nodes to the debug info proto object.
|
| 416 |
+
return nodes_to_debug_info_func(original_nodes)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def convert_bytes_to_c_source(data,
|
| 420 |
+
array_name,
|
| 421 |
+
max_line_width=80,
|
| 422 |
+
include_guard=None,
|
| 423 |
+
include_path=None,
|
| 424 |
+
use_tensorflow_license=False):
|
| 425 |
+
"""Returns strings representing a C constant array containing `data`.
|
| 426 |
+
|
| 427 |
+
Args:
|
| 428 |
+
data: Byte array that will be converted into a C constant.
|
| 429 |
+
array_name: String to use as the variable name for the constant array.
|
| 430 |
+
max_line_width: The longest line length, for formatting purposes.
|
| 431 |
+
include_guard: Name to use for the include guard macro definition.
|
| 432 |
+
include_path: Optional path to include in the source file.
|
| 433 |
+
use_tensorflow_license: Whether to include the standard TensorFlow Apache2
|
| 434 |
+
license in the generated files.
|
| 435 |
+
|
| 436 |
+
Returns:
|
| 437 |
+
Text that can be compiled as a C source file to link in the data as a
|
| 438 |
+
literal array of values.
|
| 439 |
+
Text that can be used as a C header file to reference the literal array.
|
| 440 |
+
"""
|
| 441 |
+
|
| 442 |
+
starting_pad = " "
|
| 443 |
+
array_lines = []
|
| 444 |
+
array_line = starting_pad
|
| 445 |
+
for value in bytearray(data):
|
| 446 |
+
if (len(array_line) + 4) > max_line_width:
|
| 447 |
+
array_lines.append(array_line + "\n")
|
| 448 |
+
array_line = starting_pad
|
| 449 |
+
array_line += " 0x%02x," % (value,)
|
| 450 |
+
if len(array_line) > len(starting_pad):
|
| 451 |
+
array_lines.append(array_line + "\n")
|
| 452 |
+
array_values = "".join(array_lines)
|
| 453 |
+
|
| 454 |
+
if include_guard is None:
|
| 455 |
+
include_guard = "TENSORFLOW_LITE_UTIL_" + array_name.upper() + "_DATA_H_"
|
| 456 |
+
|
| 457 |
+
if include_path is not None:
|
| 458 |
+
include_line = "#include \"{include_path}\"\n".format(
|
| 459 |
+
include_path=include_path)
|
| 460 |
+
else:
|
| 461 |
+
include_line = ""
|
| 462 |
+
|
| 463 |
+
if use_tensorflow_license:
|
| 464 |
+
license_text = """
|
| 465 |
+
/* Copyright {year} The TensorFlow Authors. All Rights Reserved.
|
| 466 |
+
|
| 467 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 468 |
+
you may not use this file except in compliance with the License.
|
| 469 |
+
You may obtain a copy of the License at
|
| 470 |
+
|
| 471 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 472 |
+
|
| 473 |
+
Unless required by applicable law or agreed to in writing, software
|
| 474 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 475 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 476 |
+
See the License for the specific language governing permissions and
|
| 477 |
+
limitations under the License.
|
| 478 |
+
==============================================================================*/
|
| 479 |
+
""".format(year=datetime.date.today().year)
|
| 480 |
+
else:
|
| 481 |
+
license_text = ""
|
| 482 |
+
|
| 483 |
+
source_template = """{license_text}
|
| 484 |
+
// This is a TensorFlow Lite model file that has been converted into a C data
|
| 485 |
+
// array using the tensorflow.lite.util.convert_bytes_to_c_source() function.
|
| 486 |
+
// This form is useful for compiling into a binary for devices that don't have a
|
| 487 |
+
// file system.
|
| 488 |
+
|
| 489 |
+
{include_line}
|
| 490 |
+
// We need to keep the data array aligned on some architectures.
|
| 491 |
+
#ifdef __has_attribute
|
| 492 |
+
#define HAVE_ATTRIBUTE(x) __has_attribute(x)
|
| 493 |
+
#else
|
| 494 |
+
#define HAVE_ATTRIBUTE(x) 0
|
| 495 |
+
#endif
|
| 496 |
+
#if HAVE_ATTRIBUTE(aligned) || (defined(__GNUC__) && !defined(__clang__))
|
| 497 |
+
#define DATA_ALIGN_ATTRIBUTE __attribute__((aligned(4)))
|
| 498 |
+
#else
|
| 499 |
+
#define DATA_ALIGN_ATTRIBUTE
|
| 500 |
+
#endif
|
| 501 |
+
|
| 502 |
+
const unsigned char {array_name}[] DATA_ALIGN_ATTRIBUTE = {{
|
| 503 |
+
{array_values}}};
|
| 504 |
+
const int {array_name}_len = {array_length};
|
| 505 |
+
"""
|
| 506 |
+
|
| 507 |
+
source_text = source_template.format(
|
| 508 |
+
array_name=array_name,
|
| 509 |
+
array_length=len(data),
|
| 510 |
+
array_values=array_values,
|
| 511 |
+
license_text=license_text,
|
| 512 |
+
include_line=include_line)
|
| 513 |
+
|
| 514 |
+
header_template = """
|
| 515 |
+
{license_text}
|
| 516 |
+
|
| 517 |
+
// This is a TensorFlow Lite model file that has been converted into a C data
|
| 518 |
+
// array using the tensorflow.lite.util.convert_bytes_to_c_source() function.
|
| 519 |
+
// This form is useful for compiling into a binary for devices that don't have a
|
| 520 |
+
// file system.
|
| 521 |
+
|
| 522 |
+
#ifndef {include_guard}
|
| 523 |
+
#define {include_guard}
|
| 524 |
+
|
| 525 |
+
extern const unsigned char {array_name}[];
|
| 526 |
+
extern const int {array_name}_len;
|
| 527 |
+
|
| 528 |
+
#endif // {include_guard}
|
| 529 |
+
"""
|
| 530 |
+
|
| 531 |
+
header_text = header_template.format(
|
| 532 |
+
array_name=array_name,
|
| 533 |
+
include_guard=include_guard,
|
| 534 |
+
license_text=license_text)
|
| 535 |
+
|
| 536 |
+
return source_text, header_text
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
def _convert_model_from_bytearray_to_object(model_bytearray):
|
| 540 |
+
"""Converts a tflite model from a bytearray into a parsable object."""
|
| 541 |
+
model_object = schema_fb.Model.GetRootAsModel(model_bytearray, 0)
|
| 542 |
+
model_object = schema_fb.ModelT.InitFromObj(model_object)
|
| 543 |
+
model_object = copy.deepcopy(model_object)
|
| 544 |
+
return model_object
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
def _convert_model_from_object_to_bytearray(model_object):
|
| 548 |
+
"""Converts a tflite model from a parsable object into a bytearray."""
|
| 549 |
+
# Initial size of the buffer, which will grow automatically if needed
|
| 550 |
+
builder = flatbuffers.Builder(1024)
|
| 551 |
+
model_offset = model_object.Pack(builder)
|
| 552 |
+
builder.Finish(model_offset, file_identifier=_TFLITE_FILE_IDENTIFIER)
|
| 553 |
+
return bytes(builder.Output())
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
def get_quantize_opcode_idx(model):
|
| 557 |
+
"""Returns the quantize op idx."""
|
| 558 |
+
quant_opcode_idxs = []
|
| 559 |
+
for idx, opcode in enumerate(model.operatorCodes):
|
| 560 |
+
builtin_code = schema_util.get_builtin_code_from_operator_code(opcode)
|
| 561 |
+
if builtin_code == schema_fb.BuiltinOperator.QUANTIZE:
|
| 562 |
+
quant_opcode_idxs.append(idx)
|
| 563 |
+
return quant_opcode_idxs
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
def get_dequantize_opcode_idx(model):
|
| 567 |
+
"""Returns the quantize op idx."""
|
| 568 |
+
quant_opcode_idxs = []
|
| 569 |
+
for idx, opcode in enumerate(model.operatorCodes):
|
| 570 |
+
builtin_code = schema_util.get_builtin_code_from_operator_code(opcode)
|
| 571 |
+
if builtin_code == schema_fb.BuiltinOperator.DEQUANTIZE:
|
| 572 |
+
quant_opcode_idxs.append(idx)
|
| 573 |
+
return quant_opcode_idxs
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
def _update_signature_def_tensors(tensor_maps, map_old_to_new_tensors):
|
| 577 |
+
"""Update the tensors in the SignatureDef's TensorMaps."""
|
| 578 |
+
for i in range(len(tensor_maps)):
|
| 579 |
+
if tensor_maps[i].tensorIndex in map_old_to_new_tensors:
|
| 580 |
+
tensor_maps[i].tensorIndex = (
|
| 581 |
+
map_old_to_new_tensors[tensor_maps[i].tensorIndex])
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
def _remove_tensors_from_model(model, remove_tensors_idxs):
|
| 585 |
+
"""Remove tensors from model."""
|
| 586 |
+
if not remove_tensors_idxs:
|
| 587 |
+
return
|
| 588 |
+
if len(model.subgraphs) > 1:
|
| 589 |
+
logging.info("Skipping the removal of dangled tensors since the model has "
|
| 590 |
+
"multiple subgraphs and tensors can be used in the different "
|
| 591 |
+
"subgraph(s)")
|
| 592 |
+
return
|
| 593 |
+
subgraph = model.subgraphs[0]
|
| 594 |
+
tensors = subgraph.tensors
|
| 595 |
+
operators = subgraph.operators
|
| 596 |
+
|
| 597 |
+
logging.debug("Removing tensors at indices : %s", remove_tensors_idxs)
|
| 598 |
+
# An optimized check to validate if "remove_tensors_idxs" (eg: [4,5,6]) is an
|
| 599 |
+
# exact subset, with ordering, of "tensors" indices (eg: [0,1,2,3,4,5,6]).
|
| 600 |
+
if min(remove_tensors_idxs) == len(tensors) - len(remove_tensors_idxs):
|
| 601 |
+
logging.debug("Removing tensors only at the end of the tensor list")
|
| 602 |
+
del tensors[min(remove_tensors_idxs):]
|
| 603 |
+
else:
|
| 604 |
+
logging.debug("Removing tensors requires updating the model")
|
| 605 |
+
# Map the old tensor indices to new tensor indices
|
| 606 |
+
d_old_to_new_tensors = {}
|
| 607 |
+
left_shift_by = 0
|
| 608 |
+
for idx in range(len(tensors)):
|
| 609 |
+
if idx in remove_tensors_idxs:
|
| 610 |
+
left_shift_by += 1
|
| 611 |
+
else:
|
| 612 |
+
d_old_to_new_tensors[idx] = idx - left_shift_by
|
| 613 |
+
logging.debug("Old to new tensors map: %s", d_old_to_new_tensors.__str__())
|
| 614 |
+
# Update tensor indices referenced throughout the model
|
| 615 |
+
def update_tensors(tensor_idxs):
|
| 616 |
+
for i, ti in enumerate(tensor_idxs):
|
| 617 |
+
tensor_idxs[i] = d_old_to_new_tensors.get(ti, -1)
|
| 618 |
+
update_tensors(subgraph.inputs)
|
| 619 |
+
update_tensors(subgraph.outputs)
|
| 620 |
+
for op in operators:
|
| 621 |
+
update_tensors(op.inputs)
|
| 622 |
+
update_tensors(op.outputs)
|
| 623 |
+
if model.signatureDefs:
|
| 624 |
+
signature_def = model.signatureDefs[0]
|
| 625 |
+
_update_signature_def_tensors(signature_def.inputs, d_old_to_new_tensors)
|
| 626 |
+
_update_signature_def_tensors(signature_def.outputs, d_old_to_new_tensors)
|
| 627 |
+
# Delete the tensors
|
| 628 |
+
for idx in sorted(remove_tensors_idxs, reverse=True):
|
| 629 |
+
tensors.pop(idx)
|
| 630 |
+
logging.debug("Removed tensors marked for deletion")
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
def _modify_model_input_type(model, inference_input_type=dtypes.float32):
|
| 634 |
+
"""Modify model input type."""
|
| 635 |
+
if inference_input_type == dtypes.float32:
|
| 636 |
+
return
|
| 637 |
+
|
| 638 |
+
if not model.signatureDefs:
|
| 639 |
+
_modify_model_input_type_per_subgraph(model, 0, -1, inference_input_type)
|
| 640 |
+
return
|
| 641 |
+
|
| 642 |
+
for signature_index, signature_def in enumerate(model.signatureDefs):
|
| 643 |
+
_modify_model_input_type_per_subgraph(model, signature_def.subgraphIndex,
|
| 644 |
+
signature_index, inference_input_type)
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
def _modify_model_input_type_per_subgraph(model, subgraph_index,
|
| 648 |
+
signature_index,
|
| 649 |
+
inference_input_type):
|
| 650 |
+
"""Modify model input type per subgraph."""
|
| 651 |
+
subgraph = model.subgraphs[subgraph_index]
|
| 652 |
+
tensors = subgraph.tensors
|
| 653 |
+
operators = subgraph.operators
|
| 654 |
+
|
| 655 |
+
# Find all quantize operators
|
| 656 |
+
quant_opcode_idxs = get_quantize_opcode_idx(model)
|
| 657 |
+
if operators and not quant_opcode_idxs:
|
| 658 |
+
for input_idx in subgraph.inputs:
|
| 659 |
+
input_type = _convert_tflite_enum_type_to_tf_type(tensors[input_idx].type)
|
| 660 |
+
if input_type == dtypes.float32:
|
| 661 |
+
raise ValueError("Model input is not dequantized.")
|
| 662 |
+
# None of the inputs have float32, then they must be int16, int8, or bool
|
| 663 |
+
return
|
| 664 |
+
|
| 665 |
+
# Validate that the model input is quantized
|
| 666 |
+
input_quant_ops = []
|
| 667 |
+
for op in operators:
|
| 668 |
+
# Find operators that quantize model input
|
| 669 |
+
if op.opcodeIndex in quant_opcode_idxs and op.inputs[0] in subgraph.inputs:
|
| 670 |
+
float_tensor, quant_tensor = tensors[op.inputs[0]], tensors[op.outputs[0]]
|
| 671 |
+
# If found, validate that the operator's input type is float
|
| 672 |
+
float_type = _convert_tflite_enum_type_to_tf_type(float_tensor.type)
|
| 673 |
+
if float_type != dtypes.float32:
|
| 674 |
+
if float_type == inference_input_type:
|
| 675 |
+
continue
|
| 676 |
+
else:
|
| 677 |
+
raise ValueError(
|
| 678 |
+
"Initial model input type must be tf.float32. Expected type for "
|
| 679 |
+
"tensor with name '{}' is tf.float32, instead type is {}".format(
|
| 680 |
+
float_tensor.name, get_tf_type_name(float_type)))
|
| 681 |
+
# If found, validate that the operator output is quantized and compatible
|
| 682 |
+
# with the final model input type
|
| 683 |
+
quant_type = _convert_tflite_enum_type_to_tf_type(quant_tensor.type)
|
| 684 |
+
if quant_type not in _MAP_QUANT_TO_IO_TYPES:
|
| 685 |
+
raise ValueError(
|
| 686 |
+
"Initial model input is not quantized. Expected type for "
|
| 687 |
+
"tensor with name '{}' should be in {}, instead type is {}".format(
|
| 688 |
+
quant_tensor.name,
|
| 689 |
+
tuple(get_tf_type_name(t) for t in
|
| 690 |
+
_MAP_QUANT_TO_IO_TYPES.keys()),
|
| 691 |
+
get_tf_type_name(quant_type)))
|
| 692 |
+
else:
|
| 693 |
+
inference_io_types = _MAP_QUANT_TO_IO_TYPES[quant_type]
|
| 694 |
+
if inference_input_type not in inference_io_types:
|
| 695 |
+
raise ValueError(
|
| 696 |
+
"Unsupported `inference_input_type` value. Expected to be in "
|
| 697 |
+
"{}, instead got {}.".format(
|
| 698 |
+
tuple(get_tf_type_name(t) for t in inference_io_types),
|
| 699 |
+
get_tf_type_name(inference_input_type)))
|
| 700 |
+
input_quant_ops.append(op)
|
| 701 |
+
|
| 702 |
+
if len(subgraph.inputs) != len(input_quant_ops):
|
| 703 |
+
logging.warning(
|
| 704 |
+
"For model inputs containing unsupported operations which cannot be "
|
| 705 |
+
"quantized, the `inference_input_type` attribute will default to the "
|
| 706 |
+
"original type."
|
| 707 |
+
)
|
| 708 |
+
|
| 709 |
+
# Modify model input type
|
| 710 |
+
if inference_input_type == dtypes.uint8:
|
| 711 |
+
# Change quant op (float to int8) to quant op (uint8 to int8)
|
| 712 |
+
for op in input_quant_ops:
|
| 713 |
+
int8_quantization = tensors[op.outputs[0]].quantization
|
| 714 |
+
uint8_quantization = schema_fb.QuantizationParametersT()
|
| 715 |
+
uint8_quantization.scale = [int8_quantization.scale[0]]
|
| 716 |
+
uint8_quantization.zeroPoint = [int8_quantization.zeroPoint[0] + 128]
|
| 717 |
+
tensors[op.inputs[0]].quantization = uint8_quantization
|
| 718 |
+
tensors[op.inputs[0]].type = schema_fb.TensorType.UINT8
|
| 719 |
+
elif inference_input_type in _MAP_QUANT_TO_IO_TYPES:
|
| 720 |
+
# Remove the inputs and the quant operator
|
| 721 |
+
remove_tensors_idxs = set()
|
| 722 |
+
for op in input_quant_ops:
|
| 723 |
+
subgraph.inputs[subgraph.inputs == op.inputs[0]] = op.outputs[0]
|
| 724 |
+
if signature_index >= 0:
|
| 725 |
+
signature_def = model.signatureDefs[signature_index]
|
| 726 |
+
for i in range(len(signature_def.inputs)):
|
| 727 |
+
if signature_def.inputs[i].tensorIndex == op.inputs[0]:
|
| 728 |
+
signature_def.inputs[i].tensorIndex = op.outputs[0]
|
| 729 |
+
remove_tensors_idxs.add(op.inputs[0])
|
| 730 |
+
operators.remove(op)
|
| 731 |
+
# Remove tensors marked for deletion.
|
| 732 |
+
_remove_tensors_from_model(model, remove_tensors_idxs)
|
| 733 |
+
else:
|
| 734 |
+
raise ValueError(
|
| 735 |
+
"Unsupported `inference_input_type` value {}.".format(
|
| 736 |
+
get_tf_type_name(inference_input_type)))
|
| 737 |
+
|
| 738 |
+
|
| 739 |
+
def _modify_model_output_type(model, inference_output_type=dtypes.float32):
|
| 740 |
+
"""Modify model output type."""
|
| 741 |
+
if inference_output_type == dtypes.float32:
|
| 742 |
+
return
|
| 743 |
+
|
| 744 |
+
if not model.signatureDefs:
|
| 745 |
+
_modify_model_output_type_per_subgraph(model, 0, -1, inference_output_type)
|
| 746 |
+
return
|
| 747 |
+
|
| 748 |
+
for signature_index, signature_def in enumerate(model.signatureDefs):
|
| 749 |
+
_modify_model_output_type_per_subgraph(model, signature_def.subgraphIndex,
|
| 750 |
+
signature_index,
|
| 751 |
+
inference_output_type)
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
def _modify_model_output_type_per_subgraph(model, subgraph_index,
|
| 755 |
+
signature_index,
|
| 756 |
+
inference_output_type):
|
| 757 |
+
"""Modify model output type per subgraph."""
|
| 758 |
+
subgraph = model.subgraphs[subgraph_index]
|
| 759 |
+
tensors = subgraph.tensors
|
| 760 |
+
operators = subgraph.operators
|
| 761 |
+
|
| 762 |
+
# Find all dequantize operators
|
| 763 |
+
dequant_opcode_idxs = get_dequantize_opcode_idx(model)
|
| 764 |
+
if operators and not dequant_opcode_idxs:
|
| 765 |
+
for output in subgraph.outputs:
|
| 766 |
+
output_type = _convert_tflite_enum_type_to_tf_type(tensors[output].type)
|
| 767 |
+
if output_type == dtypes.float32:
|
| 768 |
+
raise ValueError("Model output is not dequantized.")
|
| 769 |
+
# None of the outputs have float32, then they must be int16, int8, or bool
|
| 770 |
+
return
|
| 771 |
+
|
| 772 |
+
# Validate that the model output is dequantized
|
| 773 |
+
output_dequant_ops = []
|
| 774 |
+
for op in operators:
|
| 775 |
+
# Find operators that dequantize model output
|
| 776 |
+
if (op.opcodeIndex in dequant_opcode_idxs and
|
| 777 |
+
op.outputs[0] in subgraph.outputs):
|
| 778 |
+
# If found, validate that the operator's output type is float
|
| 779 |
+
quant_tensor, float_tensor = tensors[op.inputs[0]], tensors[op.outputs[0]]
|
| 780 |
+
float_type = _convert_tflite_enum_type_to_tf_type(float_tensor.type)
|
| 781 |
+
if float_type != dtypes.float32:
|
| 782 |
+
if float_type == inference_output_type:
|
| 783 |
+
continue
|
| 784 |
+
else:
|
| 785 |
+
raise ValueError(
|
| 786 |
+
"Initial model output type must be tf.float32. Expected type for "
|
| 787 |
+
"tensor with name '{}' is tf.float32, instead type is {}".format(
|
| 788 |
+
float_tensor.name, get_tf_type_name(float_type)))
|
| 789 |
+
# If found, validate that the operator input is quantized and compatible
|
| 790 |
+
# with the final model output type
|
| 791 |
+
quant_type = _convert_tflite_enum_type_to_tf_type(quant_tensor.type)
|
| 792 |
+
if quant_type not in _MAP_QUANT_TO_IO_TYPES:
|
| 793 |
+
raise ValueError(
|
| 794 |
+
"Initial model output is not dequantized. Expected type for "
|
| 795 |
+
"tensor with name '{}' should be in {}, instead type is {}".format(
|
| 796 |
+
quant_tensor.name,
|
| 797 |
+
tuple(get_tf_type_name(t) for t in
|
| 798 |
+
_MAP_QUANT_TO_IO_TYPES.keys()),
|
| 799 |
+
get_tf_type_name(quant_type)))
|
| 800 |
+
else:
|
| 801 |
+
inference_io_types = _MAP_QUANT_TO_IO_TYPES[quant_type]
|
| 802 |
+
if inference_output_type not in inference_io_types:
|
| 803 |
+
raise ValueError(
|
| 804 |
+
"Unsupported `inference_output_type` value. Expected to be in "
|
| 805 |
+
"{}, instead got {}.".format(
|
| 806 |
+
tuple(get_tf_type_name(t) for t in inference_io_types),
|
| 807 |
+
get_tf_type_name(inference_output_type)))
|
| 808 |
+
output_dequant_ops.append(op)
|
| 809 |
+
|
| 810 |
+
if len(subgraph.outputs) != len(output_dequant_ops):
|
| 811 |
+
logging.warning(
|
| 812 |
+
"For model outputs containing unsupported operations which cannot be "
|
| 813 |
+
"quantized, the `inference_output_type` attribute will default to the "
|
| 814 |
+
"original type."
|
| 815 |
+
)
|
| 816 |
+
|
| 817 |
+
# Modify model output type
|
| 818 |
+
if inference_output_type == dtypes.uint8:
|
| 819 |
+
# Find a quantize operator
|
| 820 |
+
quant_opcode_idx = -1
|
| 821 |
+
for idx, opcode in enumerate(model.operatorCodes):
|
| 822 |
+
builtin_code = schema_util.get_builtin_code_from_operator_code(opcode)
|
| 823 |
+
if builtin_code == schema_fb.BuiltinOperator.QUANTIZE:
|
| 824 |
+
quant_opcode_idx = idx
|
| 825 |
+
break
|
| 826 |
+
# Create a quantize operator, if none exist
|
| 827 |
+
if quant_opcode_idx == -1:
|
| 828 |
+
quant_op = schema_fb.OperatorCodeT()
|
| 829 |
+
quant_op.builtinCode = schema_fb.BuiltinOperator.QUANTIZE
|
| 830 |
+
quant_op.deprecatedBuiltinCode = schema_fb.BuiltinOperator.QUANTIZE
|
| 831 |
+
model.operatorCodes.append(quant_op)
|
| 832 |
+
quant_opcode_idx = len(model.operatorCodes) - 1
|
| 833 |
+
# Change dequant op (int8 to float) to quant op (int8 to uint8)
|
| 834 |
+
for op in output_dequant_ops:
|
| 835 |
+
op.opcodeIndex = quant_opcode_idx
|
| 836 |
+
int8_quantization = tensors[op.inputs[0]].quantization
|
| 837 |
+
uint8_quantization = schema_fb.QuantizationParametersT()
|
| 838 |
+
uint8_quantization.scale = [int8_quantization.scale[0]]
|
| 839 |
+
uint8_quantization.zeroPoint = [int8_quantization.zeroPoint[0] + 128]
|
| 840 |
+
tensors[op.outputs[0]].quantization = uint8_quantization
|
| 841 |
+
tensors[op.outputs[0]].type = schema_fb.TensorType.UINT8
|
| 842 |
+
elif inference_output_type in _MAP_QUANT_TO_IO_TYPES:
|
| 843 |
+
# Remove the outputs and the dequant operator
|
| 844 |
+
remove_tensors_idxs = set()
|
| 845 |
+
for op in output_dequant_ops:
|
| 846 |
+
subgraph.outputs[subgraph.outputs == op.outputs[0]] = op.inputs[0]
|
| 847 |
+
if signature_index >= 0:
|
| 848 |
+
signature_def = model.signatureDefs[signature_index]
|
| 849 |
+
for i in range(len(signature_def.outputs)):
|
| 850 |
+
if signature_def.outputs[i].tensorIndex == op.outputs[0]:
|
| 851 |
+
signature_def.outputs[i].tensorIndex = op.inputs[0]
|
| 852 |
+
remove_tensors_idxs.add(op.outputs[0])
|
| 853 |
+
operators.remove(op)
|
| 854 |
+
# Remove tensors marked for deletion.
|
| 855 |
+
_remove_tensors_from_model(model, remove_tensors_idxs)
|
| 856 |
+
else:
|
| 857 |
+
raise ValueError(
|
| 858 |
+
"Unsupported `inference_output_type` value {}.".format(
|
| 859 |
+
get_tf_type_name(inference_output_type)))
|
| 860 |
+
|
| 861 |
+
|
| 862 |
+
def _remove_redundant_quantize_ops(model):
|
| 863 |
+
"""Finds back to back quantize ops and remove the first quantize op."""
|
| 864 |
+
if not model.signatureDefs:
|
| 865 |
+
_remove_redundant_quantize_ops_per_subgraph(model, 0, -1)
|
| 866 |
+
return
|
| 867 |
+
|
| 868 |
+
for signature_index, signature_def in enumerate(model.signatureDefs):
|
| 869 |
+
_remove_redundant_quantize_ops_per_subgraph(model,
|
| 870 |
+
signature_def.subgraphIndex,
|
| 871 |
+
signature_index)
|
| 872 |
+
|
| 873 |
+
|
| 874 |
+
def _remove_redundant_quantize_ops_per_subgraph(model, subgraph_index,
|
| 875 |
+
signature_index):
|
| 876 |
+
"""Remove redundant quantize ops per subgraph."""
|
| 877 |
+
subgraph = model.subgraphs[subgraph_index]
|
| 878 |
+
tensors = subgraph.tensors
|
| 879 |
+
operators = subgraph.operators
|
| 880 |
+
|
| 881 |
+
# Find all quantize operators.
|
| 882 |
+
quant_opcode_idxs = get_quantize_opcode_idx(model)
|
| 883 |
+
dequant_opcode_idxs = get_dequantize_opcode_idx(model)
|
| 884 |
+
|
| 885 |
+
# Find all redundant quant tensors.
|
| 886 |
+
all_quant_ops = []
|
| 887 |
+
redundant_quant_tensors = {}
|
| 888 |
+
output_dequant_tensors = {}
|
| 889 |
+
for op in operators:
|
| 890 |
+
if op.opcodeIndex in quant_opcode_idxs:
|
| 891 |
+
all_quant_ops.append(op)
|
| 892 |
+
input_tensor = tensors[op.inputs[0]]
|
| 893 |
+
output_tensor = tensors[op.outputs[0]]
|
| 894 |
+
input_type = _convert_tflite_enum_type_to_tf_type(input_tensor.type)
|
| 895 |
+
output_type = _convert_tflite_enum_type_to_tf_type(output_tensor.type)
|
| 896 |
+
# This is a requantize op, so write down its input tensor index.
|
| 897 |
+
if input_type != dtypes.float32 and output_type != dtypes.float32:
|
| 898 |
+
redundant_quant_tensors[op.inputs[0]] = op
|
| 899 |
+
if (op.opcodeIndex in dequant_opcode_idxs and
|
| 900 |
+
op.outputs[0] in subgraph.outputs):
|
| 901 |
+
output_dequant_tensors[op.inputs[0]] = op
|
| 902 |
+
|
| 903 |
+
# Remove all the quant ops which produce the redundant quant tensors.
|
| 904 |
+
for op in all_quant_ops:
|
| 905 |
+
output_tensor_idx = op.outputs[0]
|
| 906 |
+
if output_tensor_idx in redundant_quant_tensors:
|
| 907 |
+
requantize_op = redundant_quant_tensors[output_tensor_idx]
|
| 908 |
+
if model.signatureDefs:
|
| 909 |
+
signature_def = model.signatureDefs[0]
|
| 910 |
+
for output in signature_def.outputs:
|
| 911 |
+
if output.tensorIndex == op.outputs[0]:
|
| 912 |
+
output.tensorIndex = op.inputs[0]
|
| 913 |
+
deleted_tensor = requantize_op.inputs[0]
|
| 914 |
+
# Reset the input of the requantize op to the float input
|
| 915 |
+
requantize_op.inputs[0] = op.inputs[0]
|
| 916 |
+
# Migrate other operator users to output tensor of requantize op
|
| 917 |
+
for op_user in operators:
|
| 918 |
+
if deleted_tensor in op_user.inputs and op_user != requantize_op:
|
| 919 |
+
for idx, input_tensor in enumerate(op_user.inputs):
|
| 920 |
+
if input_tensor == deleted_tensor:
|
| 921 |
+
op_user.inputs[idx] = requantize_op.outputs[0]
|
| 922 |
+
operators.remove(op)
|
| 923 |
+
|
| 924 |
+
# Remove all the quant ops which connect to the output dequant op.
|
| 925 |
+
for op in all_quant_ops:
|
| 926 |
+
output_tensor_idx = op.outputs[0]
|
| 927 |
+
if output_tensor_idx in output_dequant_tensors:
|
| 928 |
+
dequant_op = output_dequant_tensors[output_tensor_idx]
|
| 929 |
+
subgraph.outputs[subgraph.outputs == dequant_op.outputs[0]] = op.inputs[0]
|
| 930 |
+
if signature_index >= 0:
|
| 931 |
+
signature_def = model.signatureDefs[signature_index]
|
| 932 |
+
for output in signature_def.outputs:
|
| 933 |
+
if output.tensorIndex == dequant_op.outputs[0]:
|
| 934 |
+
output.tensorIndex = op.inputs[0]
|
| 935 |
+
operators.remove(op)
|
| 936 |
+
operators.remove(dequant_op)
|
| 937 |
+
|
| 938 |
+
|
| 939 |
+
def modify_model_io_type(
|
| 940 |
+
model, inference_input_type=dtypes.float32,
|
| 941 |
+
inference_output_type=dtypes.float32):
|
| 942 |
+
"""Modify the input/output type of a tflite model.
|
| 943 |
+
|
| 944 |
+
Args:
|
| 945 |
+
model: A tflite model.
|
| 946 |
+
inference_input_type: tf.DType representing modified input type.
|
| 947 |
+
(default tf.float32. If model input is int8 quantized, it must be in
|
| 948 |
+
{tf.float32, tf.int8,tf.uint8}, else if model input is int16 quantized,
|
| 949 |
+
it must be in {tf.float32, tf.int16}, else it must be tf.float32)
|
| 950 |
+
inference_output_type: tf.DType representing modified output type.
|
| 951 |
+
(default tf.float32. If model output is int8 dequantized, it must be in
|
| 952 |
+
{tf.float32, tf.int8,tf.uint8}, else if model output is int16 dequantized,
|
| 953 |
+
it must be in {tf.float32, tf.int16}, else it must be tf.float32)
|
| 954 |
+
Returns:
|
| 955 |
+
A tflite model with modified input/output type.
|
| 956 |
+
|
| 957 |
+
Raises:
|
| 958 |
+
ValueError: If `inference_input_type`/`inference_output_type` is unsupported
|
| 959 |
+
or a supported integer type is specified for a model whose input/output is
|
| 960 |
+
not quantized/dequantized.
|
| 961 |
+
RuntimeError: If the modification was unsuccessful.
|
| 962 |
+
|
| 963 |
+
"""
|
| 964 |
+
if (inference_input_type == dtypes.float32 and
|
| 965 |
+
inference_output_type == dtypes.float32):
|
| 966 |
+
return model
|
| 967 |
+
|
| 968 |
+
model_object = _convert_model_from_bytearray_to_object(model)
|
| 969 |
+
|
| 970 |
+
_modify_model_input_type(model_object, inference_input_type)
|
| 971 |
+
|
| 972 |
+
_modify_model_output_type(model_object, inference_output_type)
|
| 973 |
+
|
| 974 |
+
_remove_redundant_quantize_ops(model_object)
|
| 975 |
+
|
| 976 |
+
return _convert_model_from_object_to_bytearray(model_object)
|
| 977 |
+
|
| 978 |
+
|
| 979 |
+
def get_sparsity_modes(model_object):
|
| 980 |
+
"""Get sparsity modes used in a tflite model.
|
| 981 |
+
|
| 982 |
+
The sparsity modes are listed in conversion_metadata.fbs file.
|
| 983 |
+
|
| 984 |
+
Args:
|
| 985 |
+
model_object: A tflite model in object form.
|
| 986 |
+
|
| 987 |
+
Returns:
|
| 988 |
+
The list of sparsity modes used in the model.
|
| 989 |
+
"""
|
| 990 |
+
if not model_object or not model_object.metadata:
|
| 991 |
+
return []
|
| 992 |
+
|
| 993 |
+
result = set()
|
| 994 |
+
for subgraph in model_object.subgraphs:
|
| 995 |
+
for tensor in subgraph.tensors:
|
| 996 |
+
if not tensor.sparsity:
|
| 997 |
+
continue
|
| 998 |
+
|
| 999 |
+
# Block map is the list if indexes where the block size is larger than 1.
|
| 1000 |
+
# So empty block map means it is random sparsity.
|
| 1001 |
+
if not tensor.sparsity.blockMap:
|
| 1002 |
+
result.add(
|
| 1003 |
+
conversion_metadata_fb.ModelOptimizationMode.RANDOM_SPARSITY)
|
| 1004 |
+
else:
|
| 1005 |
+
result.add(
|
| 1006 |
+
conversion_metadata_fb.ModelOptimizationMode.BLOCK_SPARSITY)
|
| 1007 |
+
|
| 1008 |
+
return list(result)
|
| 1009 |
+
|
| 1010 |
+
|
| 1011 |
+
def populate_conversion_metadata(model_object, metadata):
|
| 1012 |
+
"""Add or update conversion metadata to a tflite model.
|
| 1013 |
+
|
| 1014 |
+
Args:
|
| 1015 |
+
model_object: A tflite model in object form.
|
| 1016 |
+
metadata: The conversion metadata.
|
| 1017 |
+
|
| 1018 |
+
Returns:
|
| 1019 |
+
A tflite model object with embedded conversion metadata.
|
| 1020 |
+
"""
|
| 1021 |
+
try:
|
| 1022 |
+
metadata_builder = flatbuffers.Builder(0)
|
| 1023 |
+
metadata_builder.Finish(metadata.Pack(metadata_builder))
|
| 1024 |
+
buffer_field = schema_fb.BufferT()
|
| 1025 |
+
buffer_field.data = metadata_builder.Output()
|
| 1026 |
+
|
| 1027 |
+
if not model_object.metadata:
|
| 1028 |
+
model_object.metadata = []
|
| 1029 |
+
else:
|
| 1030 |
+
# Check if metadata has already been populated.
|
| 1031 |
+
for meta in model_object.metadata:
|
| 1032 |
+
if meta.name.decode("utf-8") == CONVERSION_METADATA_FIELD_NAME:
|
| 1033 |
+
model_object.buffers[meta.buffer] = buffer_field
|
| 1034 |
+
return model_object
|
| 1035 |
+
|
| 1036 |
+
if not model_object.buffers:
|
| 1037 |
+
model_object.buffers = []
|
| 1038 |
+
model_object.buffers.append(buffer_field)
|
| 1039 |
+
# Creates a new metadata field.
|
| 1040 |
+
metadata_field = schema_fb.MetadataT()
|
| 1041 |
+
metadata_field.name = CONVERSION_METADATA_FIELD_NAME
|
| 1042 |
+
metadata_field.buffer = len(model_object.buffers) - 1
|
| 1043 |
+
model_object.metadata.append(metadata_field)
|
| 1044 |
+
|
| 1045 |
+
return model_object
|
| 1046 |
+
except Exception: # pylint: disable=broad-except
|
| 1047 |
+
return model_object
|
| 1048 |
+
|
| 1049 |
+
|
| 1050 |
+
def get_conversion_metadata(model_buffer):
|
| 1051 |
+
"""Read conversion metadata from a tflite model.
|
| 1052 |
+
|
| 1053 |
+
Args:
|
| 1054 |
+
model_buffer: A tflite model.
|
| 1055 |
+
|
| 1056 |
+
Returns:
|
| 1057 |
+
The conversion metadata or None if it is not populated.
|
| 1058 |
+
"""
|
| 1059 |
+
model_object = flatbuffer_utils.convert_bytearray_to_object(model_buffer)
|
| 1060 |
+
if not model_object or not model_object.metadata:
|
| 1061 |
+
return None
|
| 1062 |
+
|
| 1063 |
+
for meta in model_object.metadata:
|
| 1064 |
+
if meta.name.decode("utf-8") == CONVERSION_METADATA_FIELD_NAME:
|
| 1065 |
+
metadata_buf = model_object.buffers[meta.buffer].data.tobytes()
|
| 1066 |
+
return conversion_metadata_fb.ConversionMetadataT.InitFromObj(
|
| 1067 |
+
conversion_metadata_fb.ConversionMetadata.GetRootAsConversionMetadata(
|
| 1068 |
+
metadata_buf, 0))
|
| 1069 |
+
|
| 1070 |
+
return None
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/wrap_toco.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Wraps toco interface with python lazy loader."""
|
| 16 |
+
# We need to import pywrap_tensorflow prior to the toco wrapper.
|
| 17 |
+
# pylint: disable=invalid-import-order,g-bad-import-order
|
| 18 |
+
from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import
|
| 19 |
+
from tensorflow.python import _pywrap_toco_api
|
| 20 |
+
|
| 21 |
+
# TODO(b/137402359): Remove lazy loading wrapper
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def wrapped_toco_convert(model_flags_str, toco_flags_str, input_data_str,
|
| 25 |
+
debug_info_str, enable_mlir_converter):
|
| 26 |
+
"""Wraps TocoConvert with lazy loader."""
|
| 27 |
+
return _pywrap_toco_api.TocoConvert(
|
| 28 |
+
model_flags_str,
|
| 29 |
+
toco_flags_str,
|
| 30 |
+
input_data_str,
|
| 31 |
+
False, # extended_return
|
| 32 |
+
debug_info_str,
|
| 33 |
+
enable_mlir_converter)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def wrapped_experimental_mlir_quantize(
|
| 37 |
+
input_data_str, disable_per_channel, fully_quantize, inference_type,
|
| 38 |
+
input_data_type, output_data_type, enable_numeric_verify,
|
| 39 |
+
enable_whole_model_verify, denylisted_ops, denylisted_nodes,
|
| 40 |
+
enable_variable_quantization):
|
| 41 |
+
"""Wraps experimental mlir quantize model."""
|
| 42 |
+
return _pywrap_toco_api.ExperimentalMlirQuantizeModel(
|
| 43 |
+
input_data_str, disable_per_channel, fully_quantize, inference_type,
|
| 44 |
+
input_data_type, output_data_type, enable_numeric_verify,
|
| 45 |
+
enable_whole_model_verify, denylisted_ops, denylisted_nodes,
|
| 46 |
+
enable_variable_quantization)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def wrapped_experimental_mlir_sparsify(input_data_str):
|
| 50 |
+
"""Wraps experimental mlir sparsify model."""
|
| 51 |
+
return _pywrap_toco_api.ExperimentalMlirSparsifyModel(input_data_str)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def wrapped_register_custom_opdefs(custom_opdefs_list):
|
| 55 |
+
"""Wraps RegisterCustomOpdefs with lazy loader."""
|
| 56 |
+
return _pywrap_toco_api.RegisterCustomOpdefs(custom_opdefs_list)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def wrapped_retrieve_collected_errors():
|
| 60 |
+
"""Wraps RetrieveCollectedErrors with lazy loader."""
|
| 61 |
+
return _pywrap_toco_api.RetrieveCollectedErrors()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def wrapped_flat_buffer_file_to_mlir(model, input_is_filepath):
|
| 65 |
+
"""Wraps FlatBufferFileToMlir with lazy loader."""
|
| 66 |
+
return _pywrap_toco_api.FlatBufferToMlir(model, input_is_filepath)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/logging/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/logging/gen_html.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""A utility class to generate the report HTML based on a common template."""
|
| 16 |
+
|
| 17 |
+
import io
|
| 18 |
+
import os
|
| 19 |
+
|
| 20 |
+
from tensorflow.lite.toco.logging import toco_conversion_log_pb2 as _toco_conversion_log_pb2
|
| 21 |
+
from tensorflow.python.lib.io import file_io as _file_io
|
| 22 |
+
from tensorflow.python.platform import resource_loader as _resource_loader
|
| 23 |
+
|
| 24 |
+
html_escape_table = {
|
| 25 |
+
"&": "&",
|
| 26 |
+
'"': """,
|
| 27 |
+
"'": "'",
|
| 28 |
+
">": ">",
|
| 29 |
+
"<": "<",
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def html_escape(text):
|
| 34 |
+
return "".join(html_escape_table.get(c, c) for c in text)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def get_input_type_from_signature(op_signature):
|
| 38 |
+
"""Parses op_signature and returns a string denoting the input tensor type.
|
| 39 |
+
|
| 40 |
+
Args:
|
| 41 |
+
op_signature: a string specifying the signature of a particular operator.
|
| 42 |
+
The signature of an operator contains the input tensor's shape and type,
|
| 43 |
+
output tensor's shape and type, operator's name and its version. It has
|
| 44 |
+
the following schema:
|
| 45 |
+
INPUT:input_1_shape::input_1_type::input_2_shape::input_2_type::..
|
| 46 |
+
::OUTPUT:output_1_shape::output_1_type::output_2_shape::output_2_type::
|
| 47 |
+
..::NAME:operator_name ::VERSION:operator_version
|
| 48 |
+
An example of an operator signature is:
|
| 49 |
+
INPUT:[1,73,73,160]::float::[64,1,1,160]::float::[64]::float::
|
| 50 |
+
OUTPUT:[1,73,73,64]::float::NAME:Conv::VERSION:1
|
| 51 |
+
|
| 52 |
+
Returns:
|
| 53 |
+
A string denoting the input tensors' type. In the form of shape/type
|
| 54 |
+
separated
|
| 55 |
+
by comma. For example:
|
| 56 |
+
shape:[1,73,73,160],type:float,shape:[64,1,1,160],type:float,shape:[64],
|
| 57 |
+
type:float
|
| 58 |
+
"""
|
| 59 |
+
start = op_signature.find(":")
|
| 60 |
+
end = op_signature.find("::OUTPUT")
|
| 61 |
+
inputs = op_signature[start + 1:end]
|
| 62 |
+
lst = inputs.split("::")
|
| 63 |
+
out_str = ""
|
| 64 |
+
for i in range(len(lst)):
|
| 65 |
+
if i % 2 == 0:
|
| 66 |
+
out_str += "shape:"
|
| 67 |
+
else:
|
| 68 |
+
out_str += "type:"
|
| 69 |
+
out_str += lst[i]
|
| 70 |
+
out_str += ","
|
| 71 |
+
return out_str[:-1]
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def get_operator_type(op_name, conversion_log):
|
| 75 |
+
if op_name in conversion_log.built_in_ops:
|
| 76 |
+
return "BUILT-IN"
|
| 77 |
+
elif op_name in conversion_log.custom_ops:
|
| 78 |
+
return "CUSTOM OP"
|
| 79 |
+
else:
|
| 80 |
+
return "SELECT OP"
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class HTMLGenerator:
|
| 84 |
+
"""Utility class to generate an HTML report."""
|
| 85 |
+
|
| 86 |
+
def __init__(self, html_template_path, export_report_path):
|
| 87 |
+
"""Reads the HTML template content.
|
| 88 |
+
|
| 89 |
+
Args:
|
| 90 |
+
html_template_path: A string, path to the template HTML file.
|
| 91 |
+
export_report_path: A string, path to the generated HTML report. This path
|
| 92 |
+
should point to a '.html' file with date and time in its name.
|
| 93 |
+
e.g. 2019-01-01-10:05.toco_report.html.
|
| 94 |
+
|
| 95 |
+
Raises:
|
| 96 |
+
IOError: File doesn't exist.
|
| 97 |
+
"""
|
| 98 |
+
# Load the template HTML.
|
| 99 |
+
if not _file_io.file_exists(html_template_path):
|
| 100 |
+
raise IOError("File '{0}' does not exist.".format(html_template_path))
|
| 101 |
+
with _file_io.FileIO(html_template_path, "r") as f:
|
| 102 |
+
self.html_template = f.read()
|
| 103 |
+
|
| 104 |
+
_file_io.recursive_create_dir(os.path.dirname(export_report_path))
|
| 105 |
+
self.export_report_path = export_report_path
|
| 106 |
+
|
| 107 |
+
def generate(self,
|
| 108 |
+
toco_conversion_log_before,
|
| 109 |
+
toco_conversion_log_after,
|
| 110 |
+
post_training_quant_enabled,
|
| 111 |
+
dot_before,
|
| 112 |
+
dot_after,
|
| 113 |
+
toco_err_log="",
|
| 114 |
+
tflite_graph_path=""):
|
| 115 |
+
"""Generates the HTML report and writes it to local directory.
|
| 116 |
+
|
| 117 |
+
This function uses the fields in `toco_conversion_log_before` and
|
| 118 |
+
`toco_conversion_log_after` to populate the HTML content. Certain markers
|
| 119 |
+
(placeholders) in the HTML template are then substituted with the fields
|
| 120 |
+
from the protos. Once finished it will write the HTML file to the specified
|
| 121 |
+
local file path.
|
| 122 |
+
|
| 123 |
+
Args:
|
| 124 |
+
toco_conversion_log_before: A `TocoConversionLog` protobuf generated
|
| 125 |
+
before the model is converted by TOCO.
|
| 126 |
+
toco_conversion_log_after: A `TocoConversionLog` protobuf generated after
|
| 127 |
+
the model is converted by TOCO.
|
| 128 |
+
post_training_quant_enabled: A boolean, whether post-training quantization
|
| 129 |
+
is enabled.
|
| 130 |
+
dot_before: A string, the dot representation of the model
|
| 131 |
+
before the conversion.
|
| 132 |
+
dot_after: A string, the dot representation of the model after
|
| 133 |
+
the conversion.
|
| 134 |
+
toco_err_log: A string, the logs emitted by TOCO during conversion. Caller
|
| 135 |
+
need to ensure that this string is properly anonymized (any kind of
|
| 136 |
+
user data should be eliminated).
|
| 137 |
+
tflite_graph_path: A string, the filepath to the converted TFLite model.
|
| 138 |
+
|
| 139 |
+
Raises:
|
| 140 |
+
RuntimeError: When error occurs while generating the template.
|
| 141 |
+
"""
|
| 142 |
+
html_dict = {}
|
| 143 |
+
html_dict["<!--CONVERSION_STATUS-->"] = (
|
| 144 |
+
r'<span class="label label-danger">Fail</span>'
|
| 145 |
+
) if toco_err_log else r'<span class="label label-success">Success</span>'
|
| 146 |
+
html_dict["<!--TOTAL_OPS_BEFORE_CONVERT-->"] = str(
|
| 147 |
+
toco_conversion_log_before.model_size)
|
| 148 |
+
html_dict["<!--TOTAL_OPS_AFTER_CONVERT-->"] = str(
|
| 149 |
+
toco_conversion_log_after.model_size)
|
| 150 |
+
html_dict["<!--BUILT_IN_OPS_COUNT-->"] = str(
|
| 151 |
+
sum(toco_conversion_log_after.built_in_ops.values()))
|
| 152 |
+
html_dict["<!--SELECT_OPS_COUNT-->"] = str(
|
| 153 |
+
sum(toco_conversion_log_after.select_ops.values()))
|
| 154 |
+
html_dict["<!--CUSTOM_OPS_COUNT-->"] = str(
|
| 155 |
+
sum(toco_conversion_log_after.custom_ops.values()))
|
| 156 |
+
html_dict["<!--POST_TRAINING_QUANT_ENABLED-->"] = (
|
| 157 |
+
"is" if post_training_quant_enabled else "isn't")
|
| 158 |
+
|
| 159 |
+
pre_op_profile = ""
|
| 160 |
+
post_op_profile = ""
|
| 161 |
+
|
| 162 |
+
# Generate pre-conversion op profiles as a list of HTML table rows.
|
| 163 |
+
for i in range(len(toco_conversion_log_before.op_list)):
|
| 164 |
+
# Append operator name column.
|
| 165 |
+
pre_op_profile += "<tr><td>" + toco_conversion_log_before.op_list[
|
| 166 |
+
i] + "</td>"
|
| 167 |
+
# Append input type column.
|
| 168 |
+
if i < len(toco_conversion_log_before.op_signatures):
|
| 169 |
+
pre_op_profile += "<td>" + get_input_type_from_signature(
|
| 170 |
+
toco_conversion_log_before.op_signatures[i]) + "</td></tr>"
|
| 171 |
+
else:
|
| 172 |
+
pre_op_profile += "<td></td></tr>"
|
| 173 |
+
|
| 174 |
+
# Generate post-conversion op profiles as a list of HTML table rows.
|
| 175 |
+
for op in toco_conversion_log_after.op_list:
|
| 176 |
+
supported_type = get_operator_type(op, toco_conversion_log_after)
|
| 177 |
+
post_op_profile += ("<tr><td>" + op + "</td><td>" + supported_type +
|
| 178 |
+
"</td></tr>")
|
| 179 |
+
|
| 180 |
+
html_dict["<!--REPEAT_TABLE1_ROWS-->"] = pre_op_profile
|
| 181 |
+
html_dict["<!--REPEAT_TABLE2_ROWS-->"] = post_op_profile
|
| 182 |
+
html_dict["<!--DOT_BEFORE_CONVERT-->"] = dot_before
|
| 183 |
+
html_dict["<!--DOT_AFTER_CONVERT-->"] = dot_after
|
| 184 |
+
if toco_err_log:
|
| 185 |
+
html_dict["<!--TOCO_INFO_LOG-->"] = html_escape(toco_err_log)
|
| 186 |
+
else:
|
| 187 |
+
success_info = ("TFLite graph conversion successful. You can preview the "
|
| 188 |
+
"converted model at: ") + tflite_graph_path
|
| 189 |
+
html_dict["<!--TOCO_INFO_LOG-->"] = html_escape(success_info)
|
| 190 |
+
|
| 191 |
+
# Replace each marker (as keys of html_dict) with the actual text (as values
|
| 192 |
+
# of html_dict) in the HTML template string.
|
| 193 |
+
template = self.html_template
|
| 194 |
+
for marker in html_dict:
|
| 195 |
+
template = template.replace(marker, html_dict[marker], 1)
|
| 196 |
+
# Check that the marker text is replaced.
|
| 197 |
+
if template.find(marker) != -1:
|
| 198 |
+
raise RuntimeError("Could not populate marker text %r" % marker)
|
| 199 |
+
|
| 200 |
+
with _file_io.FileIO(self.export_report_path, "w") as f:
|
| 201 |
+
f.write(template)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def gen_conversion_log_html(conversion_log_dir, quantization_enabled,
|
| 205 |
+
tflite_graph_path):
|
| 206 |
+
"""Generates an HTML report about the conversion process.
|
| 207 |
+
|
| 208 |
+
Args:
|
| 209 |
+
conversion_log_dir: A string specifying the file directory of the conversion
|
| 210 |
+
logs. It's required that before calling this function, the
|
| 211 |
+
`conversion_log_dir`
|
| 212 |
+
already contains the following files: `toco_log_before.pb`,
|
| 213 |
+
`toco_log_after.pb`, `toco_tf_graph.dot`,
|
| 214 |
+
`toco_tflite_graph.dot`.
|
| 215 |
+
quantization_enabled: A boolean, passed from the tflite converter to
|
| 216 |
+
indicate whether post-training quantization is enabled during conversion.
|
| 217 |
+
tflite_graph_path: A string, the filepath to the converted TFLite model.
|
| 218 |
+
|
| 219 |
+
Raises:
|
| 220 |
+
IOError: When any of the required files doesn't exist.
|
| 221 |
+
"""
|
| 222 |
+
template_filename = _resource_loader.get_path_to_datafile("template.html")
|
| 223 |
+
if not os.path.exists(template_filename):
|
| 224 |
+
raise IOError("Failed to generate HTML: file '{0}' doesn't exist.".format(
|
| 225 |
+
template_filename))
|
| 226 |
+
|
| 227 |
+
toco_log_before_path = os.path.join(conversion_log_dir, "toco_log_before.pb")
|
| 228 |
+
toco_log_after_path = os.path.join(conversion_log_dir, "toco_log_after.pb")
|
| 229 |
+
dot_before_path = os.path.join(conversion_log_dir, "toco_tf_graph.dot")
|
| 230 |
+
dot_after_path = os.path.join(conversion_log_dir, "toco_tflite_graph.dot")
|
| 231 |
+
if not os.path.exists(toco_log_before_path):
|
| 232 |
+
raise IOError("Failed to generate HTML: file '{0}' doesn't exist.".format(
|
| 233 |
+
toco_log_before_path))
|
| 234 |
+
if not os.path.exists(toco_log_after_path):
|
| 235 |
+
raise IOError("Failed to generate HTML: file '{0}' doesn't exist.".format(
|
| 236 |
+
toco_log_after_path))
|
| 237 |
+
if not os.path.exists(dot_before_path):
|
| 238 |
+
raise IOError("Failed to generate HTML: file '{0}' doesn't exist.".format(
|
| 239 |
+
dot_before_path))
|
| 240 |
+
if not os.path.exists(dot_after_path):
|
| 241 |
+
raise IOError("Failed to generate HTML: file '{0}' doesn't exist.".format(
|
| 242 |
+
dot_after_path))
|
| 243 |
+
|
| 244 |
+
html_generator = HTMLGenerator(
|
| 245 |
+
template_filename,
|
| 246 |
+
os.path.join(conversion_log_dir, "toco_conversion_summary.html"))
|
| 247 |
+
|
| 248 |
+
# Parse the generated `TocoConversionLog`.
|
| 249 |
+
toco_conversion_log_before = _toco_conversion_log_pb2.TocoConversionLog()
|
| 250 |
+
toco_conversion_log_after = _toco_conversion_log_pb2.TocoConversionLog()
|
| 251 |
+
with open(toco_log_before_path, "rb") as f:
|
| 252 |
+
toco_conversion_log_before.ParseFromString(f.read())
|
| 253 |
+
with open(toco_log_after_path, "rb") as f:
|
| 254 |
+
toco_conversion_log_after.ParseFromString(f.read())
|
| 255 |
+
|
| 256 |
+
# Read the dot file before/after the conversion.
|
| 257 |
+
with io.open(dot_before_path, "r", encoding="utf-8") as f:
|
| 258 |
+
dot_before = f.read().rstrip()
|
| 259 |
+
with io.open(dot_after_path, "r", encoding="utf-8") as f:
|
| 260 |
+
dot_after = f.read().rstrip()
|
| 261 |
+
|
| 262 |
+
html_generator.generate(toco_conversion_log_before, toco_conversion_log_after,
|
| 263 |
+
quantization_enabled, dot_before, dot_after,
|
| 264 |
+
toco_conversion_log_after.toco_err_logs,
|
| 265 |
+
tflite_graph_path)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/logging/toco_conversion_log_pb2.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Generated by the protocol buffer compiler. DO NOT EDIT!
|
| 3 |
+
# source: tensorflow/lite/toco/logging/toco_conversion_log.proto
|
| 4 |
+
"""Generated protocol buffer code."""
|
| 5 |
+
from google.protobuf.internal import builder as _builder
|
| 6 |
+
from google.protobuf import descriptor as _descriptor
|
| 7 |
+
from google.protobuf import descriptor_pool as _descriptor_pool
|
| 8 |
+
from google.protobuf import symbol_database as _symbol_database
|
| 9 |
+
# @@protoc_insertion_point(imports)
|
| 10 |
+
|
| 11 |
+
_sym_db = _symbol_database.Default()
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n6tensorflow/lite/toco/logging/toco_conversion_log.proto\x12\x04toco\"\xc9\x04\n\x11TocoConversionLog\x12\x0f\n\x07op_list\x18\x01 \x03(\t\x12=\n\x0c\x62uilt_in_ops\x18\x02 \x03(\x0b\x32\'.toco.TocoConversionLog.BuiltInOpsEntry\x12:\n\ncustom_ops\x18\x03 \x03(\x0b\x32&.toco.TocoConversionLog.CustomOpsEntry\x12:\n\nselect_ops\x18\x04 \x03(\x0b\x32&.toco.TocoConversionLog.SelectOpsEntry\x12\x15\n\rop_signatures\x18\x05 \x03(\t\x12\x1a\n\x12input_tensor_types\x18\x06 \x03(\t\x12\x1b\n\x13output_tensor_types\x18\x07 \x03(\t\x12\x19\n\x11log_generation_ts\x18\x08 \x01(\x03\x12\x12\n\nmodel_size\x18\t \x01(\x05\x12\x17\n\x0ftf_lite_version\x18\n \x01(\t\x12\x12\n\nos_version\x18\x0b \x01(\t\x12\x12\n\nmodel_hash\x18\x0c \x01(\t\x12\x15\n\rtoco_err_logs\x18\r \x01(\t\x1a\x31\n\x0f\x42uiltInOpsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a\x30\n\x0e\x43ustomOpsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a\x30\n\x0eSelectOpsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01')
|
| 17 |
+
|
| 18 |
+
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
|
| 19 |
+
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tensorflow.lite.toco.logging.toco_conversion_log_pb2', globals())
|
| 20 |
+
if _descriptor._USE_C_DESCRIPTORS == False:
|
| 21 |
+
|
| 22 |
+
DESCRIPTOR._options = None
|
| 23 |
+
_TOCOCONVERSIONLOG_BUILTINOPSENTRY._options = None
|
| 24 |
+
_TOCOCONVERSIONLOG_BUILTINOPSENTRY._serialized_options = b'8\001'
|
| 25 |
+
_TOCOCONVERSIONLOG_CUSTOMOPSENTRY._options = None
|
| 26 |
+
_TOCOCONVERSIONLOG_CUSTOMOPSENTRY._serialized_options = b'8\001'
|
| 27 |
+
_TOCOCONVERSIONLOG_SELECTOPSENTRY._options = None
|
| 28 |
+
_TOCOCONVERSIONLOG_SELECTOPSENTRY._serialized_options = b'8\001'
|
| 29 |
+
_TOCOCONVERSIONLOG._serialized_start=65
|
| 30 |
+
_TOCOCONVERSIONLOG._serialized_end=650
|
| 31 |
+
_TOCOCONVERSIONLOG_BUILTINOPSENTRY._serialized_start=501
|
| 32 |
+
_TOCOCONVERSIONLOG_BUILTINOPSENTRY._serialized_end=550
|
| 33 |
+
_TOCOCONVERSIONLOG_CUSTOMOPSENTRY._serialized_start=552
|
| 34 |
+
_TOCOCONVERSIONLOG_CUSTOMOPSENTRY._serialized_end=600
|
| 35 |
+
_TOCOCONVERSIONLOG_SELECTOPSENTRY._serialized_start=602
|
| 36 |
+
_TOCOCONVERSIONLOG_SELECTOPSENTRY._serialized_end=650
|
| 37 |
+
# @@protoc_insertion_point(module_scope)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/model_flags_pb2.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Generated by the protocol buffer compiler. DO NOT EDIT!
|
| 3 |
+
# source: tensorflow/lite/toco/model_flags.proto
|
| 4 |
+
"""Generated protocol buffer code."""
|
| 5 |
+
from google.protobuf.internal import builder as _builder
|
| 6 |
+
from google.protobuf import descriptor as _descriptor
|
| 7 |
+
from google.protobuf import descriptor_pool as _descriptor_pool
|
| 8 |
+
from google.protobuf import symbol_database as _symbol_database
|
| 9 |
+
# @@protoc_insertion_point(imports)
|
| 10 |
+
|
| 11 |
+
_sym_db = _symbol_database.Default()
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
from tensorflow.lite.toco import types_pb2 as tensorflow_dot_lite_dot_toco_dot_types__pb2
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n&tensorflow/lite/toco/model_flags.proto\x12\x04toco\x1a tensorflow/lite/toco/types.proto\"5\n\x0fInputArrayShape\x12\x0c\n\x04\x64ims\x18\x02 \x03(\x05\x12\x14\n\x0cunknown_rank\x18\x03 \x01(\x08\"\x8f\x01\n\nInputArray\x12\x0c\n\x04name\x18\x01 \x01(\t\x12$\n\x05shape\x18\x06 \x01(\x0b\x32\x15.toco.InputArrayShape\x12\x12\n\nmean_value\x18\x03 \x01(\x02\x12\x14\n\tstd_value\x18\x04 \x01(\x02:\x01\x31\x12#\n\tdata_type\x18\x05 \x01(\x0e\x32\x10.toco.IODataType\"t\n\x08RnnState\x12\x13\n\x0bstate_array\x18\x01 \x01(\t\x12\x1e\n\x16\x62\x61\x63k_edge_source_array\x18\x02 \x01(\t\x12\x13\n\x0b\x64iscardable\x18\x05 \x01(\x08\x12\x0c\n\x04size\x18\x03 \x01(\x05\x12\x10\n\x08num_dims\x18\x04 \x01(\x05\"\xef\x01\n\x0f\x41rraysExtraInfo\x12,\n\x07\x65ntries\x18\x01 \x03(\x0b\x32\x1b.toco.ArraysExtraInfo.Entry\x1a\xad\x01\n\x05\x45ntry\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x13\n\x0bname_regexp\x18\x07 \x01(\t\x12\x0b\n\x03min\x18\x02 \x01(\x01\x12\x0b\n\x03max\x18\x03 \x01(\x01\x12#\n\tdata_type\x18\x04 \x01(\x0e\x32\x10.toco.IODataType\x12$\n\x05shape\x18\x05 \x01(\x0b\x32\x15.toco.InputArrayShape\x12\x1c\n\x14\x63onstant_float_value\x18\x06 \x01(\x02\"\xc6\x05\n\nModelFlags\x12&\n\x0cinput_arrays\x18\x01 \x03(\x0b\x32\x10.toco.InputArray\x12\x15\n\routput_arrays\x18\x02 \x03(\t\x12\x1d\n\x15\x63ontrol_output_arrays\x18\x18 \x03(\t\x12\x16\n\x0evariable_batch\x18\n \x01(\x08\x12\"\n\nrnn_states\x18\x0c \x03(\x0b\x32\x0e.toco.RnnState\x12\x31\n\x0cmodel_checks\x18\x0e \x03(\x0b\x32\x1b.toco.ModelFlags.ModelCheck\x12 \n\x18\x61llow_nonexistent_arrays\x18\x10 \x01(\x08\x12\x1d\n\x15\x61llow_nonascii_arrays\x18\x11 \x01(\x08\x12\x30\n\x11\x61rrays_extra_info\x18\x12 \x01(\x0b\x32\x15.toco.ArraysExtraInfo\x12(\n\x1a\x63hange_concat_input_ranges\x18\x13 \x01(\x08:\x04true\x12\x17\n\x0fsaved_model_dir\x18\x14 \x01(\t\x12\x1b\n\x13saved_model_version\x18\x15 \x01(\x05\x12\x18\n\x10saved_model_tags\x18\x16 \x03(\t\x12\"\n\x1asaved_model_exported_names\x18\x17 \x03(\t\x12\x16\n\x0euse_hlo_import\x18\x19 \x01(\x08\x12\x33\n\rhlo_file_type\x18\x1a \x01(\x0e\x32\x1c.toco.ModelFlags.HloFileType\x1aT\n\nModelCheck\x12\x18\n\ncount_type\x18\x01 \x01(\t:\x04None\x12\x15\n\tcount_min\x18\x02 \x01(\x05:\x02-1\x12\x15\n\tcount_max\x18\x03 \x01(\x05:\x02-1\"7\n\x0bHloFileType\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x0c\n\x08HLO_TEXT\x10\x01\x12\r\n\tHLO_PROTO\x10\x02')
|
| 18 |
+
|
| 19 |
+
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
|
| 20 |
+
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tensorflow.lite.toco.model_flags_pb2', globals())
|
| 21 |
+
if _descriptor._USE_C_DESCRIPTORS == False:
|
| 22 |
+
|
| 23 |
+
DESCRIPTOR._options = None
|
| 24 |
+
_INPUTARRAYSHAPE._serialized_start=82
|
| 25 |
+
_INPUTARRAYSHAPE._serialized_end=135
|
| 26 |
+
_INPUTARRAY._serialized_start=138
|
| 27 |
+
_INPUTARRAY._serialized_end=281
|
| 28 |
+
_RNNSTATE._serialized_start=283
|
| 29 |
+
_RNNSTATE._serialized_end=399
|
| 30 |
+
_ARRAYSEXTRAINFO._serialized_start=402
|
| 31 |
+
_ARRAYSEXTRAINFO._serialized_end=641
|
| 32 |
+
_ARRAYSEXTRAINFO_ENTRY._serialized_start=468
|
| 33 |
+
_ARRAYSEXTRAINFO_ENTRY._serialized_end=641
|
| 34 |
+
_MODELFLAGS._serialized_start=644
|
| 35 |
+
_MODELFLAGS._serialized_end=1354
|
| 36 |
+
_MODELFLAGS_MODELCHECK._serialized_start=1213
|
| 37 |
+
_MODELFLAGS_MODELCHECK._serialized_end=1297
|
| 38 |
+
_MODELFLAGS_HLOFILETYPE._serialized_start=1299
|
| 39 |
+
_MODELFLAGS_HLOFILETYPE._serialized_end=1354
|
| 40 |
+
# @@protoc_insertion_point(module_scope)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/python/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/python/toco_from_protos.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2017 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 |
+
"""Python console command to invoke TOCO from serialized protos."""
|
| 16 |
+
import argparse
|
| 17 |
+
import sys
|
| 18 |
+
|
| 19 |
+
# We need to import pywrap_tensorflow prior to the toco wrapper.
|
| 20 |
+
# pylint: disable=invalid-import-order,g-bad-import-order
|
| 21 |
+
from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import
|
| 22 |
+
from tensorflow.python import _pywrap_toco_api
|
| 23 |
+
from absl import app
|
| 24 |
+
|
| 25 |
+
FLAGS = None
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def execute(unused_args):
|
| 29 |
+
"""Runs the converter."""
|
| 30 |
+
with open(FLAGS.model_proto_file, "rb") as model_file:
|
| 31 |
+
model_str = model_file.read()
|
| 32 |
+
|
| 33 |
+
with open(FLAGS.toco_proto_file, "rb") as toco_file:
|
| 34 |
+
toco_str = toco_file.read()
|
| 35 |
+
|
| 36 |
+
with open(FLAGS.model_input_file, "rb") as input_file:
|
| 37 |
+
input_str = input_file.read()
|
| 38 |
+
|
| 39 |
+
debug_info_str = None
|
| 40 |
+
if FLAGS.debug_proto_file:
|
| 41 |
+
with open(FLAGS.debug_proto_file, "rb") as debug_info_file:
|
| 42 |
+
debug_info_str = debug_info_file.read()
|
| 43 |
+
|
| 44 |
+
enable_mlir_converter = FLAGS.enable_mlir_converter
|
| 45 |
+
|
| 46 |
+
output_str = _pywrap_toco_api.TocoConvert(
|
| 47 |
+
model_str,
|
| 48 |
+
toco_str,
|
| 49 |
+
input_str,
|
| 50 |
+
False, # extended_return
|
| 51 |
+
debug_info_str,
|
| 52 |
+
enable_mlir_converter)
|
| 53 |
+
open(FLAGS.model_output_file, "wb").write(output_str)
|
| 54 |
+
sys.exit(0)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def main():
|
| 58 |
+
global FLAGS
|
| 59 |
+
parser = argparse.ArgumentParser(
|
| 60 |
+
description="Invoke toco using protos as input.")
|
| 61 |
+
parser.add_argument(
|
| 62 |
+
"model_proto_file",
|
| 63 |
+
type=str,
|
| 64 |
+
help="File containing serialized proto that describes the model.")
|
| 65 |
+
parser.add_argument(
|
| 66 |
+
"toco_proto_file",
|
| 67 |
+
type=str,
|
| 68 |
+
help="File containing serialized proto describing how TOCO should run.")
|
| 69 |
+
parser.add_argument(
|
| 70 |
+
"model_input_file", type=str, help="Input model is read from this file.")
|
| 71 |
+
parser.add_argument(
|
| 72 |
+
"model_output_file",
|
| 73 |
+
type=str,
|
| 74 |
+
help="Result of applying TOCO conversion is written here.")
|
| 75 |
+
parser.add_argument(
|
| 76 |
+
"--debug_proto_file",
|
| 77 |
+
type=str,
|
| 78 |
+
default="",
|
| 79 |
+
help=("File containing serialized `GraphDebugInfo` proto that describes "
|
| 80 |
+
"logging information."))
|
| 81 |
+
parser.add_argument(
|
| 82 |
+
"--enable_mlir_converter",
|
| 83 |
+
action="store_true",
|
| 84 |
+
help=("Boolean indicating whether to enable MLIR-based conversion "
|
| 85 |
+
"instead of TOCO conversion. (default False)"))
|
| 86 |
+
|
| 87 |
+
FLAGS, unparsed = parser.parse_known_args()
|
| 88 |
+
|
| 89 |
+
app.run(main=execute, argv=[sys.argv[0]] + unparsed)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
if __name__ == "__main__":
|
| 93 |
+
main()
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/toco_flags_pb2.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Generated by the protocol buffer compiler. DO NOT EDIT!
|
| 3 |
+
# source: tensorflow/lite/toco/toco_flags.proto
|
| 4 |
+
"""Generated protocol buffer code."""
|
| 5 |
+
from google.protobuf.internal import builder as _builder
|
| 6 |
+
from google.protobuf import descriptor as _descriptor
|
| 7 |
+
from google.protobuf import descriptor_pool as _descriptor_pool
|
| 8 |
+
from google.protobuf import symbol_database as _symbol_database
|
| 9 |
+
# @@protoc_insertion_point(imports)
|
| 10 |
+
|
| 11 |
+
_sym_db = _symbol_database.Default()
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
from tensorflow.compiler.mlir.lite.debug import debug_options_pb2 as tensorflow_dot_compiler_dot_mlir_dot_lite_dot_debug_dot_debug__options__pb2
|
| 15 |
+
from tensorflow.compiler.mlir.quantization.stablehlo import quantization_options_pb2 as tensorflow_dot_compiler_dot_mlir_dot_quantization_dot_stablehlo_dot_quantization__options__pb2
|
| 16 |
+
from tensorflow.lite.toco import types_pb2 as tensorflow_dot_lite_dot_toco_dot_types__pb2
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n%tensorflow/lite/toco/toco_flags.proto\x12\x04toco\x1a\x37tensorflow/compiler/mlir/lite/debug/debug_options.proto\x1aJtensorflow/compiler/mlir/quantization/stablehlo/quantization_options.proto\x1a tensorflow/lite/toco/types.proto\"\xdc\x10\n\tTocoFlags\x12&\n\x0cinput_format\x18\x01 \x01(\x0e\x32\x10.toco.FileFormat\x12\'\n\routput_format\x18\x02 \x01(\x0e\x32\x10.toco.FileFormat\x12.\n\x14inference_input_type\x18\x0b \x01(\x0e\x32\x10.toco.IODataType\x12(\n\x0einference_type\x18\x04 \x01(\x0e\x32\x10.toco.IODataType\x12\x1a\n\x12\x64\x65\x66\x61ult_ranges_min\x18\x05 \x01(\x02\x12\x1a\n\x12\x64\x65\x66\x61ult_ranges_max\x18\x06 \x01(\x02\x12 \n\x18\x64\x65\x66\x61ult_int16_ranges_min\x18\x0f \x01(\x02\x12 \n\x18\x64\x65\x66\x61ult_int16_ranges_max\x18\x10 \x01(\x02\x12\x17\n\x0f\x64rop_fake_quant\x18\x07 \x01(\x08\x12!\n\x19reorder_across_fake_quant\x18\x08 \x01(\x08\x12\x18\n\x10\x61llow_custom_ops\x18\n \x01(\x08\x12\x1f\n\x17\x64rop_control_dependency\x18\x0c \x01(\x08\x12+\n#debug_disable_recurrent_cell_fusion\x18\r \x01(\x08\x12%\n\x1dpropagate_fake_quant_num_bits\x18\x0e \x01(\x08\x12\x35\n-allow_nudging_weights_to_use_fast_gemm_kernel\x18\x11 \x01(\x08\x12\'\n\x1b\x64\x65\x64upe_array_min_size_bytes\x18\x12 \x01(\x03:\x02\x36\x34\x12&\n\x18split_tflite_lstm_inputs\x18\x13 \x01(\x08:\x04true\x12\x1f\n\x10quantize_weights\x18\x14 \x01(\x08:\x05\x66\x61lse\x12\x19\n\x11\x64ump_graphviz_dir\x18\x18 \x01(\t\x12#\n\x1b\x64ump_graphviz_include_video\x18\x19 \x01(\x08\x12%\n\x16post_training_quantize\x18\x1a \x01(\x08:\x05\x66\x61lse\x12#\n\x14\x65nable_select_tf_ops\x18\x1b \x01(\x08:\x05\x66\x61lse\x12\"\n\x13\x66orce_select_tf_ops\x18\x1c \x01(\x08:\x05\x66\x61lse\x12\"\n\x13quantize_to_float16\x18\x1d \x01(\x08:\x05\x66\x61lse\x12#\n\x15\x61llow_dynamic_tensors\x18\x1e \x01(\x08:\x04true\x12\x1e\n\x16\x63onversion_summary_dir\x18\x1f \x01(\t\x12\x19\n\rcustom_opdefs\x18 \x03(\tB\x02\x18\x01\x12\x1a\n\x12select_user_tf_ops\x18! \x03(\t\x12.\n enable_tflite_resource_variables\x18\" \x01(\x08:\x04true\x12!\n\x12unfold_batchmatmul\x18# \x01(\x08:\x05\x66\x61lse\x12#\n\x15lower_tensor_list_ops\x18$ \x01(\x08:\x04true\x12+\n\x11\x61\x63\x63umulation_type\x18% \x01(\x0e\x32\x10.toco.IODataType\x12\x1d\n\x0e\x61llow_bfloat16\x18& \x01(\x08:\x05\x66\x61lse\x12\x1f\n\x17\x61llow_all_select_tf_ops\x18\' \x01(\x08\x12*\n\x1bunfold_large_splat_constant\x18( \x01(\x08:\x05\x66\x61lse\x12\x1a\n\x12supported_backends\x18) \x03(\t\x12\x39\n*default_to_single_batch_in_tensor_list_ops\x18* \x01(\x08:\x05\x66\x61lse\x12/\n disable_per_channel_quantization\x18+ \x01(\x08:\x05\x66\x61lse\x12\x32\n#enable_mlir_dynamic_range_quantizer\x18, \x01(\x08:\x05\x66\x61lse\x12\x1c\n\x14tf_quantization_mode\x18- \x01(\t\x12)\n\x1a\x64isable_infer_tensor_range\x18. \x01(\x08:\x05\x66\x61lse\x12&\n\x17use_fake_quant_num_bits\x18/ \x01(\x08:\x05\x66\x61lse\x12*\n\x1b\x65nable_dynamic_update_slice\x18\x30 \x01(\x08:\x05\x66\x61lse\x12!\n\x12preserve_assert_op\x18\x31 \x01(\x08:\x05\x66\x61lse\x12*\n\x1bguarantee_all_funcs_one_use\x18\x32 \x01(\x08:\x05\x66\x61lse\x12#\n\x14\x63onvert_to_stablehlo\x18\x33 \x01(\x08:\x05\x66\x61lse\x12\x30\n!enable_mlir_variable_quantization\x18\x34 \x01(\x08:\x05\x66\x61lse\x12&\n\x17\x64isable_fuse_mul_and_fc\x18\x35 \x01(\x08:\x05\x66\x61lse\x12I\n\x14quantization_options\x18\x36 \x01(\x0b\x32+.stablehlo.quantization.QuantizationOptions\x12.\n\x1b\x65nable_hlo_to_tf_conversion\x18\x37 \x01(\x08:\x05\x66\x61lseB\x02\x18\x01\x12\x39\n\rdebug_options\x18\x38 \x01(\x0b\x32\".tensorflow.converter.DebugOptions\x12 \n\x11use_buffer_offset\x18\x39 \x01(\x08:\x05\x66\x61lse\x12.\n\x1flegalize_custom_tensor_list_ops\x18: \x01(\x08:\x05\x66\x61lse\x12$\n\x15reduce_type_precision\x18; \x01(\x08:\x05\x66\x61lse*\\\n\nFileFormat\x12\x17\n\x13\x46ILE_FORMAT_UNKNOWN\x10\x00\x12\x17\n\x13TENSORFLOW_GRAPHDEF\x10\x01\x12\n\n\x06TFLITE\x10\x02\x12\x10\n\x0cGRAPHVIZ_DOT\x10\x03')
|
| 20 |
+
|
| 21 |
+
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
|
| 22 |
+
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tensorflow.lite.toco.toco_flags_pb2', globals())
|
| 23 |
+
if _descriptor._USE_C_DESCRIPTORS == False:
|
| 24 |
+
|
| 25 |
+
DESCRIPTOR._options = None
|
| 26 |
+
_TOCOFLAGS.fields_by_name['custom_opdefs']._options = None
|
| 27 |
+
_TOCOFLAGS.fields_by_name['custom_opdefs']._serialized_options = b'\030\001'
|
| 28 |
+
_TOCOFLAGS.fields_by_name['enable_hlo_to_tf_conversion']._options = None
|
| 29 |
+
_TOCOFLAGS.fields_by_name['enable_hlo_to_tf_conversion']._serialized_options = b'\030\001'
|
| 30 |
+
_FILEFORMAT._serialized_start=2357
|
| 31 |
+
_FILEFORMAT._serialized_end=2449
|
| 32 |
+
_TOCOFLAGS._serialized_start=215
|
| 33 |
+
_TOCOFLAGS._serialized_end=2355
|
| 34 |
+
# @@protoc_insertion_point(module_scope)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/types_pb2.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Generated by the protocol buffer compiler. DO NOT EDIT!
|
| 3 |
+
# source: tensorflow/lite/toco/types.proto
|
| 4 |
+
"""Generated protocol buffer code."""
|
| 5 |
+
from google.protobuf.internal import builder as _builder
|
| 6 |
+
from google.protobuf import descriptor as _descriptor
|
| 7 |
+
from google.protobuf import descriptor_pool as _descriptor_pool
|
| 8 |
+
from google.protobuf import symbol_database as _symbol_database
|
| 9 |
+
# @@protoc_insertion_point(imports)
|
| 10 |
+
|
| 11 |
+
_sym_db = _symbol_database.Default()
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n tensorflow/lite/toco/types.proto\x12\x04toco*\xb3\x02\n\nIODataType\x12\x18\n\x14IO_DATA_TYPE_UNKNOWN\x10\x00\x12\t\n\x05\x46LOAT\x10\x01\x12\x13\n\x0fQUANTIZED_UINT8\x10\x02\x12\t\n\x05INT32\x10\x03\x12\t\n\x05INT64\x10\x04\x12\n\n\x06STRING\x10\x05\x12\x13\n\x0fQUANTIZED_INT16\x10\x06\x12\x08\n\x04\x42OOL\x10\x07\x12\r\n\tCOMPLEX64\x10\x08\x12\x12\n\x0eQUANTIZED_INT8\x10\t\x12\x0b\n\x07\x46LOAT16\x10\n\x12\x0b\n\x07\x46LOAT64\x10\x0b\x12\x0e\n\nCOMPLEX128\x10\x0c\x12\n\n\x06UINT64\x10\r\x12\x0c\n\x08RESOURCE\x10\x0e\x12\x0b\n\x07VARIANT\x10\x0f\x12\n\n\x06UINT32\x10\x10\x12\t\n\x05UINT8\x10\x11\x12\x08\n\x04INT8\x10\x12\x12\t\n\x05INT16\x10\x13\x12\n\n\x06UINT16\x10\x14')
|
| 17 |
+
|
| 18 |
+
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
|
| 19 |
+
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tensorflow.lite.toco.types_pb2', globals())
|
| 20 |
+
if _descriptor._USE_C_DESCRIPTORS == False:
|
| 21 |
+
|
| 22 |
+
DESCRIPTOR._options = None
|
| 23 |
+
_IODATATYPE._serialized_start=43
|
| 24 |
+
_IODATATYPE._serialized_end=350
|
| 25 |
+
# @@protoc_insertion_point(module_scope)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/flatbuffer_utils.py
ADDED
|
@@ -0,0 +1,432 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Utility functions for FlatBuffers.
|
| 16 |
+
|
| 17 |
+
All functions that are commonly used to work with FlatBuffers.
|
| 18 |
+
|
| 19 |
+
Refer to the tensorflow lite flatbuffer schema here:
|
| 20 |
+
tensorflow/lite/schema/schema.fbs
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
import copy
|
| 24 |
+
import random
|
| 25 |
+
import re
|
| 26 |
+
import struct
|
| 27 |
+
import sys
|
| 28 |
+
|
| 29 |
+
import flatbuffers
|
| 30 |
+
|
| 31 |
+
from tensorflow.lite.python import schema_py_generated as schema_fb
|
| 32 |
+
from tensorflow.lite.python import schema_util
|
| 33 |
+
from tensorflow.python.platform import gfile
|
| 34 |
+
|
| 35 |
+
_TFLITE_FILE_IDENTIFIER = b'TFL3'
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def convert_bytearray_to_object(model_bytearray):
|
| 39 |
+
"""Converts a tflite model from a bytearray to an object for parsing."""
|
| 40 |
+
model_object = schema_fb.Model.GetRootAsModel(model_bytearray, 0)
|
| 41 |
+
return schema_fb.ModelT.InitFromObj(model_object)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def read_model(input_tflite_file):
|
| 45 |
+
"""Reads a tflite model as a python object.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
input_tflite_file: Full path name to the input tflite file
|
| 49 |
+
|
| 50 |
+
Raises:
|
| 51 |
+
RuntimeError: If input_tflite_file path is invalid.
|
| 52 |
+
IOError: If input_tflite_file cannot be opened.
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
A python object corresponding to the input tflite file.
|
| 56 |
+
"""
|
| 57 |
+
if not gfile.Exists(input_tflite_file):
|
| 58 |
+
raise RuntimeError('Input file not found at %r\n' % input_tflite_file)
|
| 59 |
+
with gfile.GFile(input_tflite_file, 'rb') as input_file_handle:
|
| 60 |
+
model_bytearray = bytearray(input_file_handle.read())
|
| 61 |
+
model = convert_bytearray_to_object(model_bytearray)
|
| 62 |
+
if sys.byteorder == 'big':
|
| 63 |
+
byte_swap_tflite_model_obj(model, 'little', 'big')
|
| 64 |
+
return model
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def read_model_with_mutable_tensors(input_tflite_file):
|
| 68 |
+
"""Reads a tflite model as a python object with mutable tensors.
|
| 69 |
+
|
| 70 |
+
Similar to read_model() with the addition that the returned object has
|
| 71 |
+
mutable tensors (read_model() returns an object with immutable tensors).
|
| 72 |
+
|
| 73 |
+
NOTE: This API only works for TFLite generated with
|
| 74 |
+
_experimental_use_buffer_offset=false
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
input_tflite_file: Full path name to the input tflite file
|
| 78 |
+
|
| 79 |
+
Raises:
|
| 80 |
+
RuntimeError: If input_tflite_file path is invalid.
|
| 81 |
+
IOError: If input_tflite_file cannot be opened.
|
| 82 |
+
|
| 83 |
+
Returns:
|
| 84 |
+
A mutable python object corresponding to the input tflite file.
|
| 85 |
+
"""
|
| 86 |
+
return copy.deepcopy(read_model(input_tflite_file))
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def convert_object_to_bytearray(model_object, extra_buffer=b''):
|
| 90 |
+
"""Converts a tflite model from an object to a immutable bytearray."""
|
| 91 |
+
# Initial size of the buffer, which will grow automatically if needed
|
| 92 |
+
builder = flatbuffers.Builder(1024)
|
| 93 |
+
model_offset = model_object.Pack(builder)
|
| 94 |
+
builder.Finish(model_offset, file_identifier=_TFLITE_FILE_IDENTIFIER)
|
| 95 |
+
model_bytearray = bytes(builder.Output())
|
| 96 |
+
model_bytearray = model_bytearray + extra_buffer
|
| 97 |
+
return model_bytearray
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def write_model(model_object, output_tflite_file):
|
| 101 |
+
"""Writes the tflite model, a python object, into the output file.
|
| 102 |
+
|
| 103 |
+
NOTE: This API only works for TFLite generated with
|
| 104 |
+
_experimental_use_buffer_offset=false
|
| 105 |
+
|
| 106 |
+
Args:
|
| 107 |
+
model_object: A tflite model as a python object
|
| 108 |
+
output_tflite_file: Full path name to the output tflite file.
|
| 109 |
+
|
| 110 |
+
Raises:
|
| 111 |
+
IOError: If output_tflite_file path is invalid or cannot be opened.
|
| 112 |
+
"""
|
| 113 |
+
if sys.byteorder == 'big':
|
| 114 |
+
model_object = copy.deepcopy(model_object)
|
| 115 |
+
byte_swap_tflite_model_obj(model_object, 'big', 'little')
|
| 116 |
+
model_bytearray = convert_object_to_bytearray(model_object)
|
| 117 |
+
with gfile.GFile(output_tflite_file, 'wb') as output_file_handle:
|
| 118 |
+
output_file_handle.write(model_bytearray)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def strip_strings(model):
|
| 122 |
+
"""Strips all nonessential strings from the model to reduce model size.
|
| 123 |
+
|
| 124 |
+
We remove the following strings:
|
| 125 |
+
(find strings by searching ":string" in the tensorflow lite flatbuffer schema)
|
| 126 |
+
1. Model description
|
| 127 |
+
2. SubGraph name
|
| 128 |
+
3. Tensor names
|
| 129 |
+
We retain OperatorCode custom_code and Metadata name.
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
model: The model from which to remove nonessential strings.
|
| 133 |
+
"""
|
| 134 |
+
|
| 135 |
+
model.description = None
|
| 136 |
+
for subgraph in model.subgraphs:
|
| 137 |
+
subgraph.name = None
|
| 138 |
+
for tensor in subgraph.tensors:
|
| 139 |
+
tensor.name = None
|
| 140 |
+
# We clear all signature_def structure, since without names it is useless.
|
| 141 |
+
model.signatureDefs = None
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def type_to_name(tensor_type):
|
| 145 |
+
"""Converts a numerical enum to a readable tensor type."""
|
| 146 |
+
for name, value in schema_fb.TensorType.__dict__.items():
|
| 147 |
+
if value == tensor_type:
|
| 148 |
+
return name
|
| 149 |
+
return None
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def randomize_weights(model, random_seed=0, buffers_to_skip=None):
|
| 153 |
+
"""Randomize weights in a model.
|
| 154 |
+
|
| 155 |
+
Args:
|
| 156 |
+
model: The model in which to randomize weights.
|
| 157 |
+
random_seed: The input to the random number generator (default value is 0).
|
| 158 |
+
buffers_to_skip: The list of buffer indices to skip. The weights in these
|
| 159 |
+
buffers are left unmodified.
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
# The input to the random seed generator. The default value is 0.
|
| 163 |
+
random.seed(random_seed)
|
| 164 |
+
|
| 165 |
+
# Parse model buffers which store the model weights
|
| 166 |
+
buffers = model.buffers
|
| 167 |
+
buffer_ids = range(1, len(buffers)) # ignore index 0 as it's always None
|
| 168 |
+
if buffers_to_skip is not None:
|
| 169 |
+
buffer_ids = [idx for idx in buffer_ids if idx not in buffers_to_skip]
|
| 170 |
+
|
| 171 |
+
buffer_types = {}
|
| 172 |
+
for graph in model.subgraphs:
|
| 173 |
+
for op in graph.operators:
|
| 174 |
+
if op.inputs is None:
|
| 175 |
+
break
|
| 176 |
+
for input_idx in op.inputs:
|
| 177 |
+
tensor = graph.tensors[input_idx]
|
| 178 |
+
buffer_types[tensor.buffer] = type_to_name(tensor.type)
|
| 179 |
+
|
| 180 |
+
for i in buffer_ids:
|
| 181 |
+
buffer_i_data = buffers[i].data
|
| 182 |
+
buffer_i_size = 0 if buffer_i_data is None else buffer_i_data.size
|
| 183 |
+
if buffer_i_size == 0:
|
| 184 |
+
continue
|
| 185 |
+
|
| 186 |
+
# Raw data buffers are of type ubyte (or uint8) whose values lie in the
|
| 187 |
+
# range [0, 255]. Those ubytes (or unint8s) are the underlying
|
| 188 |
+
# representation of each datatype. For example, a bias tensor of type
|
| 189 |
+
# int32 appears as a buffer 4 times it's length of type ubyte (or uint8).
|
| 190 |
+
# For floats, we need to generate a valid float and then pack it into
|
| 191 |
+
# the raw bytes in place.
|
| 192 |
+
buffer_type = buffer_types.get(i, 'INT8')
|
| 193 |
+
if buffer_type.startswith('FLOAT'):
|
| 194 |
+
format_code = 'e' if buffer_type == 'FLOAT16' else 'f'
|
| 195 |
+
for offset in range(0, buffer_i_size, struct.calcsize(format_code)):
|
| 196 |
+
value = random.uniform(-0.5, 0.5) # See http://b/152324470#comment2
|
| 197 |
+
struct.pack_into(format_code, buffer_i_data, offset, value)
|
| 198 |
+
else:
|
| 199 |
+
for j in range(buffer_i_size):
|
| 200 |
+
buffer_i_data[j] = random.randint(0, 255)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def rename_custom_ops(model, map_custom_op_renames):
|
| 204 |
+
"""Rename custom ops so they use the same naming style as builtin ops.
|
| 205 |
+
|
| 206 |
+
Args:
|
| 207 |
+
model: The input tflite model.
|
| 208 |
+
map_custom_op_renames: A mapping from old to new custom op names.
|
| 209 |
+
"""
|
| 210 |
+
for op_code in model.operatorCodes:
|
| 211 |
+
if op_code.customCode:
|
| 212 |
+
op_code_str = op_code.customCode.decode('ascii')
|
| 213 |
+
if op_code_str in map_custom_op_renames:
|
| 214 |
+
op_code.customCode = map_custom_op_renames[op_code_str].encode('ascii')
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def opcode_to_name(model, op_code):
|
| 218 |
+
"""Converts a TFLite op_code to the human readable name.
|
| 219 |
+
|
| 220 |
+
Args:
|
| 221 |
+
model: The input tflite model.
|
| 222 |
+
op_code: The op_code to resolve to a readable name.
|
| 223 |
+
|
| 224 |
+
Returns:
|
| 225 |
+
A string containing the human readable op name, or None if not resolvable.
|
| 226 |
+
"""
|
| 227 |
+
op = model.operatorCodes[op_code]
|
| 228 |
+
code = max(op.builtinCode, op.deprecatedBuiltinCode)
|
| 229 |
+
for name, value in vars(schema_fb.BuiltinOperator).items():
|
| 230 |
+
if value == code:
|
| 231 |
+
return name
|
| 232 |
+
return None
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def xxd_output_to_bytes(input_cc_file):
|
| 236 |
+
"""Converts xxd output C++ source file to bytes (immutable).
|
| 237 |
+
|
| 238 |
+
Args:
|
| 239 |
+
input_cc_file: Full path name to th C++ source file dumped by xxd
|
| 240 |
+
|
| 241 |
+
Raises:
|
| 242 |
+
RuntimeError: If input_cc_file path is invalid.
|
| 243 |
+
IOError: If input_cc_file cannot be opened.
|
| 244 |
+
|
| 245 |
+
Returns:
|
| 246 |
+
A bytearray corresponding to the input cc file array.
|
| 247 |
+
"""
|
| 248 |
+
# Match hex values in the string with comma as separator
|
| 249 |
+
pattern = re.compile(r'\W*(0x[0-9a-fA-F,x ]+).*')
|
| 250 |
+
|
| 251 |
+
model_bytearray = bytearray()
|
| 252 |
+
|
| 253 |
+
with open(input_cc_file) as file_handle:
|
| 254 |
+
for line in file_handle:
|
| 255 |
+
values_match = pattern.match(line)
|
| 256 |
+
|
| 257 |
+
if values_match is None:
|
| 258 |
+
continue
|
| 259 |
+
|
| 260 |
+
# Match in the parentheses (hex array only)
|
| 261 |
+
list_text = values_match.group(1)
|
| 262 |
+
|
| 263 |
+
# Extract hex values (text) from the line
|
| 264 |
+
# e.g. 0x1c, 0x00, 0x00, 0x00, 0x54, 0x46, 0x4c,
|
| 265 |
+
values_text = filter(None, list_text.split(','))
|
| 266 |
+
|
| 267 |
+
# Convert to hex
|
| 268 |
+
values = [int(x, base=16) for x in values_text]
|
| 269 |
+
model_bytearray.extend(values)
|
| 270 |
+
|
| 271 |
+
return bytes(model_bytearray)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def xxd_output_to_object(input_cc_file):
|
| 275 |
+
"""Converts xxd output C++ source file to object.
|
| 276 |
+
|
| 277 |
+
Args:
|
| 278 |
+
input_cc_file: Full path name to th C++ source file dumped by xxd
|
| 279 |
+
|
| 280 |
+
Raises:
|
| 281 |
+
RuntimeError: If input_cc_file path is invalid.
|
| 282 |
+
IOError: If input_cc_file cannot be opened.
|
| 283 |
+
|
| 284 |
+
Returns:
|
| 285 |
+
A python object corresponding to the input tflite file.
|
| 286 |
+
"""
|
| 287 |
+
model_bytes = xxd_output_to_bytes(input_cc_file)
|
| 288 |
+
return convert_bytearray_to_object(model_bytes)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def byte_swap_buffer_content(buffer, chunksize, from_endiness, to_endiness):
|
| 292 |
+
"""Helper function for byte-swapping the buffers field."""
|
| 293 |
+
to_swap = [
|
| 294 |
+
buffer.data[i : i + chunksize]
|
| 295 |
+
for i in range(0, len(buffer.data), chunksize)
|
| 296 |
+
]
|
| 297 |
+
buffer.data = b''.join(
|
| 298 |
+
[
|
| 299 |
+
int.from_bytes(byteswap, from_endiness).to_bytes(
|
| 300 |
+
chunksize, to_endiness
|
| 301 |
+
)
|
| 302 |
+
for byteswap in to_swap
|
| 303 |
+
]
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def byte_swap_string_content(buffer, from_endiness, to_endiness):
|
| 308 |
+
"""Helper function for byte-swapping the string buffer.
|
| 309 |
+
|
| 310 |
+
Args:
|
| 311 |
+
buffer: TFLite string buffer of from_endiness format.
|
| 312 |
+
from_endiness: The original endianness format of the string buffer.
|
| 313 |
+
to_endiness: The destined endianness format of the string buffer.
|
| 314 |
+
"""
|
| 315 |
+
num_of_strings = int.from_bytes(buffer.data[0:4], from_endiness)
|
| 316 |
+
string_content = bytearray(buffer.data[4 * (num_of_strings + 2) :])
|
| 317 |
+
prefix_data = b''.join(
|
| 318 |
+
[
|
| 319 |
+
int.from_bytes(buffer.data[i : i + 4], from_endiness).to_bytes(
|
| 320 |
+
4, to_endiness
|
| 321 |
+
)
|
| 322 |
+
for i in range(0, (num_of_strings + 1) * 4 + 1, 4)
|
| 323 |
+
]
|
| 324 |
+
)
|
| 325 |
+
buffer.data = prefix_data + string_content
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def byte_swap_tflite_model_obj(model, from_endiness, to_endiness):
|
| 329 |
+
"""Byte swaps the buffers field in a TFLite model.
|
| 330 |
+
|
| 331 |
+
Args:
|
| 332 |
+
model: TFLite model object of from_endiness format.
|
| 333 |
+
from_endiness: The original endianness format of the buffers in model.
|
| 334 |
+
to_endiness: The destined endianness format of the buffers in model.
|
| 335 |
+
"""
|
| 336 |
+
if model is None:
|
| 337 |
+
return
|
| 338 |
+
# Get all the constant buffers, byte swapping them as per their data types
|
| 339 |
+
buffer_swapped = []
|
| 340 |
+
types_of_16_bits = [
|
| 341 |
+
schema_fb.TensorType.FLOAT16,
|
| 342 |
+
schema_fb.TensorType.INT16,
|
| 343 |
+
schema_fb.TensorType.UINT16,
|
| 344 |
+
]
|
| 345 |
+
types_of_32_bits = [
|
| 346 |
+
schema_fb.TensorType.FLOAT32,
|
| 347 |
+
schema_fb.TensorType.INT32,
|
| 348 |
+
schema_fb.TensorType.COMPLEX64,
|
| 349 |
+
schema_fb.TensorType.UINT32,
|
| 350 |
+
]
|
| 351 |
+
types_of_64_bits = [
|
| 352 |
+
schema_fb.TensorType.INT64,
|
| 353 |
+
schema_fb.TensorType.FLOAT64,
|
| 354 |
+
schema_fb.TensorType.COMPLEX128,
|
| 355 |
+
schema_fb.TensorType.UINT64,
|
| 356 |
+
]
|
| 357 |
+
for subgraph in model.subgraphs:
|
| 358 |
+
for tensor in subgraph.tensors:
|
| 359 |
+
if (
|
| 360 |
+
tensor.buffer > 0
|
| 361 |
+
and tensor.buffer < len(model.buffers)
|
| 362 |
+
and tensor.buffer not in buffer_swapped
|
| 363 |
+
and model.buffers[tensor.buffer].data is not None
|
| 364 |
+
):
|
| 365 |
+
if tensor.type == schema_fb.TensorType.STRING:
|
| 366 |
+
byte_swap_string_content(
|
| 367 |
+
model.buffers[tensor.buffer], from_endiness, to_endiness
|
| 368 |
+
)
|
| 369 |
+
elif tensor.type in types_of_16_bits:
|
| 370 |
+
byte_swap_buffer_content(
|
| 371 |
+
model.buffers[tensor.buffer], 2, from_endiness, to_endiness
|
| 372 |
+
)
|
| 373 |
+
elif tensor.type in types_of_32_bits:
|
| 374 |
+
byte_swap_buffer_content(
|
| 375 |
+
model.buffers[tensor.buffer], 4, from_endiness, to_endiness
|
| 376 |
+
)
|
| 377 |
+
elif tensor.type in types_of_64_bits:
|
| 378 |
+
byte_swap_buffer_content(
|
| 379 |
+
model.buffers[tensor.buffer], 8, from_endiness, to_endiness
|
| 380 |
+
)
|
| 381 |
+
else:
|
| 382 |
+
continue
|
| 383 |
+
buffer_swapped.append(tensor.buffer)
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def byte_swap_tflite_buffer(tflite_model, from_endiness, to_endiness):
|
| 387 |
+
"""Generates a new model byte array after byte swapping its buffers field.
|
| 388 |
+
|
| 389 |
+
Args:
|
| 390 |
+
tflite_model: TFLite flatbuffer in a byte array.
|
| 391 |
+
from_endiness: The original endianness format of the buffers in
|
| 392 |
+
tflite_model.
|
| 393 |
+
to_endiness: The destined endianness format of the buffers in tflite_model.
|
| 394 |
+
|
| 395 |
+
Returns:
|
| 396 |
+
TFLite flatbuffer in a byte array, after being byte swapped to to_endiness
|
| 397 |
+
format.
|
| 398 |
+
"""
|
| 399 |
+
if tflite_model is None:
|
| 400 |
+
return None
|
| 401 |
+
# Load TFLite Flatbuffer byte array into an object.
|
| 402 |
+
model = convert_bytearray_to_object(tflite_model)
|
| 403 |
+
|
| 404 |
+
# Byte swapping the constant buffers as per their data types
|
| 405 |
+
byte_swap_tflite_model_obj(model, from_endiness, to_endiness)
|
| 406 |
+
|
| 407 |
+
# Return a TFLite flatbuffer as a byte array.
|
| 408 |
+
return convert_object_to_bytearray(model)
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def count_resource_variables(model):
|
| 412 |
+
"""Calculates the number of unique resource variables in a model.
|
| 413 |
+
|
| 414 |
+
Args:
|
| 415 |
+
model: the input tflite model, either as bytearray or object.
|
| 416 |
+
|
| 417 |
+
Returns:
|
| 418 |
+
An integer number representing the number of unique resource variables.
|
| 419 |
+
"""
|
| 420 |
+
if not isinstance(model, schema_fb.ModelT):
|
| 421 |
+
model = convert_bytearray_to_object(model)
|
| 422 |
+
unique_shared_names = set()
|
| 423 |
+
for subgraph in model.subgraphs:
|
| 424 |
+
if subgraph.operators is None:
|
| 425 |
+
continue
|
| 426 |
+
for op in subgraph.operators:
|
| 427 |
+
builtin_code = schema_util.get_builtin_code_from_operator_code(
|
| 428 |
+
model.operatorCodes[op.opcodeIndex]
|
| 429 |
+
)
|
| 430 |
+
if builtin_code == schema_fb.BuiltinOperator.VAR_HANDLE:
|
| 431 |
+
unique_shared_names.add(op.builtinOptions.sharedName)
|
| 432 |
+
return len(unique_shared_names)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/optimize/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/optimize/debugging/__init__.py
ADDED
|
File without changes
|