id
stringlengths
15
25
source
stringclasses
1 value
chunk_index
int64
0
393k
token_count
int32
449
512
text
stringlengths
203
7.95k
combine_chunk_392400
combine.txt
392,400
512
.experimental.convert_op_hints_to_stubs"]) @_deprecation.deprecated( None, "Please follow instructions under " "https://www.tensorflow.org/lite/convert/operation_fusion for operation" "fusion in tflite." ) def convert_op_hints_to_stubs(session=None, graph_def=None, ...
combine_chunk_392401
combine.txt
392,401
512
implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for lite.py functionality related to TensorFlow 2.0.""" import os from absl.testing import parameterized import num...
combine_chunk_392402
combine.txt
392,402
512
. Key is the output name in the SignatureDef 'signature_key' Value is the output value """ interpreter = Interpreter(model_content=tflite_model) signature_runner = interpreter.get_signature_runner(signature_key) return signature_runner(**inputs) def _getSimpleVariableModel(self): root...
combine_chunk_392403
combine.txt
392,403
512
@def_function.function def mul(self, x): return x * self.weight return BasicModelWithSharedWeight() def _getMatMulModelWithSmallWeights(self): class MatMulModelWithSmallWeights(autotrackable.AutoTrackable): """MatMul model with small weights and relatively large biases.""" ...
combine_chunk_392404
combine.txt
392,404
512
.layer.kernel def call(self, inputs): self.layer.kernel = ( tf.quantization.fake_quant_with_min_max_vars_per_channel( self.quantized_weights, min=[bit_min], max=[bit_max], num_bits=num_bits, narrow_range=True)) if not weight_only: quant_inputs...
combine_chunk_392405
combine.txt
392,405
512
range(5): yield [np.random.uniform(-1, 1, size=(1, 2, 3)).astype(np.float32)] inputs = tf.keras.layers.Input(shape=(2, 3), batch_size=1, dtype=dtype) outputs = ReadAssign(number_of_states)(inputs) model = tf.keras.Model(inputs, outputs) return model, calibration_gen def _getInfFloatModel(se...
combine_chunk_392406
combine.txt
392,406
512
import export_meta_graph as _export_meta_graph # The field name of conversion metadata in the flatbuffer file. CONVERSION_METADATA_FIELD_NAME = "CONVERSION_METADATA" # Keras functions used by TFLite model_input_signature = _tflite_keras_util.model_input_signature trace_model_call = _tflite_keras_util.trace_model_cal...
combine_chunk_392407
combine.txt
392,407
512
: {}" .format(tflite_enum_type, _MAP_TFLITE_ENUM_TO_TF_TYPES)) return tf_type def get_tf_type_name(tf_type): """Converts tf.dtype (eg: tf.float32) to str (eg: "tf.float32").""" return "tf." + tf_type.name if tf_type else None def get_tensor_name(tensor): """Returns name of the input tensor. Args...
combine_chunk_392408
combine.txt
392,408
512
"""Sets Tensor shape for each tensor if the shape is defined. Args: tensors: TensorFlow tensor.Tensor. shapes: Dict of strings representing input tensor names to list of integers representing input shapes (e.g., {"foo": : [1, 16, 16, 3]}). Raises: ValueError: `shapes` contains an invalid ...
combine_chunk_392409
combine.txt
392,409
512
[array.name].tensor_shape.CopyFrom(array.shape.as_proto()) for array in output_arrays: signature.outputs[array.name].name = array.name signature.outputs[array.name].dtype = array.dtype.as_datatype_enum signature.outputs[array.name].tensor_shape.CopyFrom(array.shape.as_proto()) meta_graph.signature_def...
combine_chunk_392410
combine.txt
392,410
512
graph_def, input_tensors, output_tensors, config, graph=sess.graph) # If ophints are present, just convert them. hinted_outputs_nodes = find_all_hinted_output_nodes(sess) if hinted_outputs_nodes: return _convert_op_hints_if_present(sess, graph_def, output_tensors, hin...
combine_chunk_392411
combine.txt
392,411
512
Convert all the op definitions to stack traces in terms of GraphDebugInfo. return _error_interpolation.create_graph_debug_info_def(useful_ops) return f def convert_debug_info_func(saved_debug_info): """Returns a method to retrieve the `GraphDebugInfo` from the original graph. Args: saved_debug_info: ...
combine_chunk_392412
combine.txt
392,412
512
definition. include_path: Optional path to include in the source file. use_tensorflow_license: Whether to include the standard TensorFlow Apache2 license in the generated files. Returns: Text that can be compiled as a C source file to link in the data as a literal array of values. Text tha...
combine_chunk_392413
combine.txt
392,413
512
(x) 0 #endif #if HAVE_ATTRIBUTE(aligned) || (defined(__GNUC__) && !defined(__clang__)) #define DATA_ALIGN_ATTRIBUTE __attribute__((aligned(4))) #else #define DATA_ALIGN_ATTRIBUTE #endif const unsigned char {array_name}[] DATA_ALIGN_ATTRIBUTE = {{ {array_values}}}; const int {array_name}_len = {array_length}; """ so...
combine_chunk_392414
combine.txt
392,414
512
_opcode_idxs = [] for idx, opcode in enumerate(model.operatorCodes): builtin_code = schema_util.get_builtin_code_from_operator_code(opcode) if builtin_code == schema_fb.BuiltinOperator.DEQUANTIZE: quant_opcode_idxs.append(idx) return quant_opcode_idxs def _update_signature_def_tensors(tensor_maps, m...
combine_chunk_392415
combine.txt
392,415
512
update_tensors(subgraph.outputs) for op in operators: update_tensors(op.inputs) update_tensors(op.outputs) if model.signatureDefs: signature_def = model.signatureDefs[0] _update_signature_def_tensors(signature_def.inputs, d_old_to_new_tensors) _update_signature_def_tensors(signatu...
combine_chunk_392416
combine.txt
392,416
512
raise ValueError( "Initial model input type must be tf.float32. Expected type for " "tensor with name '{}' is tf.float32, instead type is {}".format( float_tensor.name, get_tf_type_name(float_type))) # If found, validate that the operator output is quantized and comp...
combine_chunk_392417
combine.txt
392,417
512
.inputs == op.inputs[0]] = op.outputs[0] if signature_index >= 0: signature_def = model.signatureDefs[signature_index] for i in range(len(signature_def.inputs)): if signature_def.inputs[i].tensorIndex == op.inputs[0]: signature_def.inputs[i].tensorIndex = op.outputs[0] ...
combine_chunk_392418
combine.txt
392,418
512
float_type = _convert_tflite_enum_type_to_tf_type(float_tensor.type) if float_type != dtypes.float32: if float_type == inference_output_type: continue else: raise ValueError( "Initial model output type must be tf.float32. Expected type for " "tensor...
combine_chunk_392419
combine.txt
392,419
512
Operator.QUANTIZE model.operatorCodes.append(quant_op) quant_opcode_idx = len(model.operatorCodes) - 1 # Change dequant op (int8 to float) to quant op (int8 to uint8) for op in output_dequant_ops: op.opcodeIndex = quant_opcode_idx int8_quantization = tensors[op.inputs[0]].quantization ...
combine_chunk_392420
combine.txt
392,420
512
operators # Find all quantize operators. quant_opcode_idxs = get_quantize_opcode_idx(model) dequant_opcode_idxs = get_dequantize_opcode_idx(model) # Find all redundant quant tensors. all_quant_ops = [] redundant_quant_tensors = {} output_dequant_tensors = {} for op in operators: if op.opcodeIndex ...
combine_chunk_392421
combine.txt
392,421
512
subgraph.outputs[subgraph.outputs == dequant_op.outputs[0]] = op.inputs[0] if signature_index >= 0: signature_def = model.signatureDefs[signature_index] for output in signature_def.outputs: if output.tensorIndex == dequant_op.outputs[0]: output.tensorIndex = op.inputs[0...
combine_chunk_392422
combine.txt
392,422
512
ite model in object form. Returns: The list of sparsity modes used in the model. """ if not model_object or not model_object.metadata: return [] result = set() for subgraph in model_object.subgraphs: for tensor in subgraph.tensors: if not tensor.sparsity: continue # Block ma...
combine_chunk_392423
combine.txt
392,423
512
_hash_with_primitive_value( hash_value, len(subgraph.outputs) ) return hash_value def update_hash_with_primitive_value(hash_value, value): """Update the hash value using a primitive value. Args: hash_value (uint64): The current hash value. value: The primitive value to incorporate ...
combine_chunk_392424
combine.txt
392,424
512
model_object.buffers.append(buffer_field) # Creates a new metadata field. metadata_field = schema_fb.MetadataT() metadata_field.name = CONVERSION_METADATA_FIELD_NAME metadata_field.buffer = len(model_object.buffers) - 1 model_object.metadata.append(metadata_field) return model_object except ...
combine_chunk_392425
combine.txt
392,425
512
VERT_TF_TO_TFLITE_MODEL" # RUN quantization and sparsification. OPTIMIZE_TFLITE_MODEL = "OPTIMIZE_TFLITE_MODEL" SubComponentItem = collections.namedtuple("SubComponentItem", ["name", "component"]) class SubComponent(SubComponentItem, enum.Enum): """Enum class definin...
combine_chunk_392426
combine.txt
392,426
512
Component.CONVERT_TF_TO_TFLITE_MODEL) # Convert a GraphDef to TFLite model. CONVERT_GRAPHDEF = SubComponentItem("CONVERT_GRAPHDEF", Component.CONVERT_TF_TO_TFLITE_MODEL) # Convert a SavedModel to TFLite model. CONVERT_SAVED_MODEL = SubComponentItem("CONVERT_SAVED_MO...
combine_chunk_392427
combine.txt
392,427
512
Data .ERROR_UNSUPPORTED_CONTROL_FLOW_V1, } for pattern, error_code in error_code_mapping.items(): if pattern in message: error_data = converter_error_data_pb2.ConverterErrorData() error_data.error_message = message error_data.error_code = error_code self.append_...
combine_chunk_392428
combine.txt
392,428
512
Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distrib...
combine_chunk_392429
combine.txt
392,429
512
decorated function. - _obj_func : for class object, we need to use this object to provide `self` instance as 1 first argument. - _verified : whether the compatibility is checked or not. Args: target: decorated function. converter_target_spec : target_spec of TFLite converter ...
combine_chunk_392430
combine.txt
392,430
512
of the decorated function.""" return self._get_func().get_concrete_function(*args, **kwargs) def _get_location_string(self, location): """Dump location of ConveterError.errors.location.""" callstack = [] for single_call in reversed(location.call): if (location.type == converter_error...
combine_chunk_392431
combine.txt
392,431
512
.ERROR_NEEDS_CUSTOM_OPS: custom_ops.append(err.operator.name) custom_ops_location.append(err.location) # Check TensorFlow op usage error. elif err.error_code == converter_error_data_pb2.ConverterErrorData.ERROR_NEEDS_FLEX_OPS: tf_ops.append(err.operator.name) tf_ops_location....
combine_chunk_392432
combine.txt
392,432
512
, "errors"): self._decode_converter_error(err) else: self._decode_error_legacy(err) if self._raise_exception and self._log_messages: raise CompatibilityError(f"CompatibilityException at {repr(self._func)}") def _log(self, message): """Log and print authoring warning / error message."""...
combine_chunk_392433
combine.txt
392,433
512
.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, ...
combine_chunk_392434
combine.txt
392,434
512
from tensorflow.lite.python.convert import mlir_quantize as _mlir_quantize from tensorflow.lite.python.convert import mlir_sparsify as _mlir_sparsify from tensorflow.lite.python.convert import mlir_to_flatbuffer as _mlir_to_flatbuffer from tensorflow.lite.python.convert import OpsSet from tensorflow.lite.python.conver...
combine_chunk_392435
combine.txt
392,435
512
from tensorflow.lite.python.util import model_input_signature as _model_input_signature from tensorflow.lite.python.util import modify_model_io_type as _modify_model_io_type from tensorflow.lite.python.util import populate_conversion_metadata as _populate_conversion_metadata from tensorflow.lite.python.util import run...
combine_chunk_392436
combine.txt
392,436
512
Refer to the [documentation](https://ai.google.dev/edge/litert/models/post_training_quantization) for further information on the types available and how to use them. OPTIMIZE_FOR_SIZE Deprecated. Does the same as DEFAULT. OPTIMIZE_FOR_LATENCY Deprecated. Does the same as DEFAULT. EXPER...
combine_chunk_392437
combine.txt
392,437
512
. Usually, this is a small subset of a few hundred samples randomly chosen, in no particular order, from the training or evaluation dataset. """ def __init__(self, input_gen): """Creates a representative dataset. Args: input_gen: A generator function that generates input samples for the model ...
combine_chunk_392438
combine.txt
392,438
512
if experimental_select_user_tf_ops is None: experimental_select_user_tf_ops = set() self.experimental_select_user_tf_ops = experimental_select_user_tf_ops self.experimental_supported_backends = experimental_supported_backends self._experimental_custom_op_registerers = [] # Hint for the support...
combine_chunk_392439
combine.txt
392,439
512
and self._representative_dataset is not None and not self._is_int16x8_target_required() and not self.is_allow_float() and self._is_int8_target_required() ) def is_post_training_int8_quantization_with_float_fallback(self): return ( self.is_any_optimization_enabled() an...
combine_chunk_392440
combine.txt
392,440
512
_training() ) def is_post_training_dynamic_range_quantization(self): # Post-training dynamic range quantization is only enabled if post-training # int8 quantization and training time quantization was not done. return ( self.is_any_optimization_enabled() and self._representative_datase...
combine_chunk_392441
combine.txt
392,441
512
ir_variable_quantization ), } elif self.is_post_training_dynamic_range_quantization(): return { "inference_type": _dtypes.float32, "inference_input_type": _dtypes.float32, "post_training_quantize": True, # enable dynamic range quantization "quantize_to_...
combine_chunk_392442
combine.txt
392,442
512
( set(self._target_spec.supported_types) == set() or set(self._target_spec.supported_types) == {_dtypes.int8} ): raise ValueError( "As full integer quantization has been enabled by setting " "`target_spec.supported_ops`={tf.lite.OpsSet.TFLITE_BUILTINS_INT8}, " "t...
combine_chunk_392443
combine.txt
392,443
512
"Expected bias type to be `dtypes.int32` or `dtypes.int64` for " f"Int16Quant. Current setting bias type: {bias_type}" ) def _is_int8_target_required(self): return ( OpsSet.TFLITE_BUILTINS_INT8 in set(self._target_spec.supported_ops) ) or (set(self._target_spec.supported_types) == se...
combine_chunk_392444
combine.txt
392,444
512
model type temporarily to transmit the information # from the factory class methods to TFLiteConverterBase init function. _original_model_type = conversion_metadata_fb.ModelType.NONE def __init__(self): self.optimizations = set() self.representative_dataset = None self.target_spec = TargetSpec() ...
combine_chunk_392445
combine.txt
392,445
512
() self._metadata.environment = conversion_metadata_fb.EnvironmentT() self._metadata.options = conversion_metadata_fb.ConversionOptionsT() self._metadata.environment.tensorflowVersion = versions.__version__ self._metadata.environment.modelType = self._get_original_model_type() self._experimental_ena...
combine_chunk_392446
combine.txt
392,446
512
optimizers: optimizers = [] # MLIR converter will take care of constant folding instead of grappler. if not self.experimental_new_converter: optimizers.append("constfold") is_only_flex_enabled = set([OpsSet.SELECT_TF_OPS]) == set( self.target_spec.supported_ops ) if is_only_fle...
combine_chunk_392447
combine.txt
392,447
512
_dense, debug_options_str=debug_options.SerializeToString(), ) else: disable_dense = ( self._experimental_disable_per_channel_quantization_for_dense_layers ) return calibrate_quantize.calibrate_and_quantize( self.representative_dataset.input_gen, input...
combine_chunk_392448
combine.txt
392,448
512
quantization_options": self._experimental_quantization_options, "ir_dump_dir": self.ir_dump_dir, "ir_dump_pass_regex": self.ir_dump_pass_regex, "ir_dump_func_regex": self.ir_dump_func_regex, "enable_timing": self.enable_timing, "print_ir_before": self.print_ir_before, "pr...
combine_chunk_392449
combine.txt
392,449
512
.experimental_use_stablehlo_quantizer: self._assign_stablehlo_quantization_config_or_populate_default(args) elif self.experimental_stablehlo_quantizer_config is not None: raise ValueError( "QuantizationConfig should be provided only when" " experimental_use_stablehlo_quantizer is set...
combine_chunk_392450
combine.txt
392,450
512
LO quantizer only supports static-range and weight-only PTQ." ) def _contains_function_with_implements_attr(self, saved_model_proto): meta_graph = saved_model_proto.meta_graphs[0] for function in meta_graph.graph_def.library.function: if function.attr.get("_implements", None) or function.attr.get...
combine_chunk_392451
combine.txt
392,451
512
: raise ValueError("The original model type should be specified.") cls._original_model_type = model_type def _get_original_model_type(self): """One-time getter to return original model type and set it to NONE.""" model_type = TFLiteConverterBase._original_model_type TFLiteConverterBase._origina...
combine_chunk_392452
combine.txt
392,452
512
if isinstance(elem, enum.Enum): return str(elem.value) return pprint.pformat(elem) def format_param(param): if isinstance(param, (list, tuple, set)): if not param: return "None" # Return None if empty. string_list = [format_element(x) for x in param] ret...
combine_chunk_392453
combine.txt
392,453
512
` is set to `True`. StableHLO # Quantizer performs quantization during the conversion step, which happens # before `_optimize_tflite_model`. if ( quant_mode.is_integer_quantization() and not self.experimental_use_stablehlo_quantizer ): in_type, out_type = self.inference_input_type,...
combine_chunk_392454
combine.txt
392,454
512
) return model def _convert_and_export_metrics(self, convert_func, *args, **kwargs): """Wraps around convert function to export metrics. Args: convert_func: The convert function to wrap. *args: Positional arguments of the convert function. **kwargs: The keyword arguments of th...
combine_chunk_392455
combine.txt
392,455
512
, *args, **kwargs): # pylint: disable=protected-access return self._convert_and_export_metrics(convert_func, *args, **kwargs) # pylint: enable=protected-access return wrapper class TFLiteConverterBaseV2(TFLiteConverterBase): """Converter subclass to share functionality between V2 converters.""" de...
combine_chunk_392456
combine.txt
392,456
512
_impl.SavedModelLoader(saved_model_dir) saved_model.load_graph(graph, tags=saved_model_tags) meta_graph = saved_model.get_meta_graph_def_from_tags(saved_model_tags) graph_def = meta_graph.graph_def signature_def = meta_graph.signature_def[ _signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY ...
combine_chunk_392457
combine.txt
392,457
512
" ): self._debug_info = _get_debug_info( _build_debug_info_func(self._funcs[0].graph), graph_def ) else: self._debug_info = _get_debug_info( _convert_debug_info_func(self._trackable_obj.graph_debug_info), graph_def, ) @convert_phase(Component.PREPARE_TF_M...
combine_chunk_392458
combine.txt
392,458
512
(quant_mode.converter_flags()) result = _convert_saved_model(**converter_kwargs) return self._optimize_tflite_model( result, quant_mode, _build_conversion_flags(**converter_kwargs).debug_options, quant_io=self.experimental_new_quantizer, ) def convert(self, graph_def, inp...
combine_chunk_392459
combine.txt
392,459
512
_names: Names to be exported when the saved model import path is on. trackable_obj: tf.AutoTrackable object associated with `funcs`. A reference to this object needs to be maintained so that Variables do not get garbage collected since functions have a weak reference to Variables. ...
combine_chunk_392460
combine.txt
392,460
512
_model.pb and can be read cheaply. # # Note on adjust_debug_info_func_names: _convert_debug_info_func() (in # util.py) ignores its original_nodes argument entirely and returns the # saved_debug_info proto unchanged, so the function-name adjustment that # _load() applies via adjust_debug_info_func_na...
combine_chunk_392461
combine.txt
392,461
512
if _keras_model is a Keras 3+ model.""" try: import keras # pylint: disable=g-import-not-at-top return keras.__version__.startswith("3") and isinstance( self._keras_model, keras.layers.Layer ) except ImportError: return False if _is_keras_3...
combine_chunk_392462
combine.txt
392,462
512
] self._parse_saved_model_args( always_enable_saved_model_import=self.experimental_lower_to_saved_model ) if self.saved_model_dir: graph_def, input_tensors, output_tensors = self._load_saved_model( self.saved_model_dir, self._saved_model_tags ) self._trackable_obj = _loa...
combine_chunk_392463
combine.txt
392,463
512
_saved_model(self): """Converts a Keras model as a saved model. Returns: The converted data in serialized format. """ temp_dir = tempfile.mkdtemp() try: graph_def, input_tensors, output_tensors = ( self._convert_keras_to_saved_model(temp_dir) ) if self.saved_model_...
combine_chunk_392464
combine.txt
392,464
512
funcs, trackable_obj=None): """Constructor for TFLiteConverter. Args: funcs: List of TensorFlow ConcreteFunctions. The list should not contain duplicate elements. trackable_obj: tf.AutoTrackable object associated with `funcs`. A reference to this object needs to be maintained so th...
combine_chunk_392465
combine.txt
392,465
512
input tensors. output_tensors: List of output tensors. """ if len(self._funcs) == 0: # pylint: disable=g-explicit-length-test raise ValueError("No ConcreteFunction is specified.") if not self.experimental_lower_to_saved_model: return None, None, None # Without the provided trackabl...
combine_chunk_392466
combine.txt
392,466
512
, _ = ( self._convert_concrete_functions_to_saved_model(temp_dir) ) if self.saved_model_dir: self._validate_inputs(graph_def, input_tensors) return self._convert_from_saved_model(graph_def) finally: shutil.rmtree(temp_dir, True) return None @_export_metrics def c...
combine_chunk_392467
combine.txt
392,467
512
to pass in the desired `input placeholders` with the correct input shape/type. In the converted tflite model, the function name will be default to "main", the output names will be the traced outputs. The output ordering shall match the serving function. """ # fmt: skip super(TFLiteJaxConvert...
combine_chunk_392468
combine.txt
392,468
512
.compiler_ir("hlo") .as_serialized_hlo_module_proto() ) except Exception: # pylint: disable=broad-except raise ValueError("Failed to convert the given Jax function to hlo.") # We need to set the hlo proto, and here we use serialized proto format # since it's more compact. conver...
combine_chunk_392469
combine.txt
392,469
512
: Experimental flag, subject to change. Set of optimizations to apply. e.g {tf.lite.Optimize.DEFAULT}. (default None, must be None or a set of values of type `tf.lite.Optimize`) representative_dataset: A generator function used for integer quantization where each generated sample has the same orde...
combine_chunk_392470
combine.txt
392,470
512
_variables: Experimental flag, subject to change. Enables [resource variables](https://tensorflow.org/guide/migrate/tf1_vs_tf2#resourcevariables_instead_of_referencevariables) to be converted by this converter. This is only allowed if the from_saved_model interface is used. (default True) se...
combine_chunk_392471
combine.txt
392,471
512
under development. trackable_obj: An `AutoTrackable` object (typically `tf.module`) associated with `funcs`. A reference to this object needs to be maintained so that Variables do not get garbage collected since functions have a weak reference to Variables. Returns: TFLiteCon...
combine_chunk_392472
combine.txt
392,472
512
if signature_keys: if len(signature_keys) != 1: raise ValueError("Only support a single signature key.") else: signature_key = signature_keys[0] logging.warning( "Invoking the TF1 implementation of TFLiteConverter " "because eager is disabled. Consider enab...
combine_chunk_392473
combine.txt
392,473
512
_metadata_fb.ModelType.KERAS_MODEL ) # pylint: enable=protected-access return TFLiteKerasModelConverterV2(model) @classmethod @_deprecation.deprecated( None, "Use `jax2tf.convert` and (`lite.TFLiteConverter.from_saved_model`" " or `lite.TFLiteConverter.from_concrete_functions`) instea...
combine_chunk_392474
combine.txt
392,474
512
""" super(TFLiteConverterBaseV1, self).__init__() self.inference_type = _dtypes.float32 self.inference_input_type = None self.inference_output_type = None self.output_format = constants.TFLITE self.quantized_input_stats = {} self.default_ranges_stats = None self.drop_control_dependency ...
combine_chunk_392475
combine.txt
392,475
512
( requires_quantized_input_stats and not converter_kwargs["quantized_input_stats"] ): raise ValueError( "The `quantized_input_stats` flag must be defined when either " "`inference_type` flag or `inference_input_type` flag is set to " "tf.int8 or tf.uint8. Current...
combine_chunk_392476
combine.txt
392,476
512
"tensors '{0}'.".format(",".join(invalid_stats)) ) else: self._quantized_stats = None @convert_phase(Component.PREPARE_TF_MODEL, SubComponent.OPTIMIZE_TF_MODEL) def _optimize_tf_model( self, graph_def, input_tensors, output_tensors, quant_mode ): """Run a Grappler pass to ...
combine_chunk_392477
combine.txt
392,477
512
_quantization, self._experimental_strict_qdq, ) optimized_graph = self._optimize_tf_model( self._graph_def, self._input_tensors, self._output_tensors, quant_mode ) self._debug_info = _get_debug_info(self._debug_info_func, optimized_graph) converter_kwargs = self._get_base_converte...
combine_chunk_392478
combine.txt
392,478
512
(tensor) for tensor in self._input_tensors] else: return [name for name, _ in self._input_arrays_with_shape] def _has_valid_tensors(self): """Checks if the input and output tensors have been initialized. Returns: Bool. """ return self._input_tensors is not None and self._output_tenso...
combine_chunk_392479
combine.txt
392,479
512
self.inference_type, self.inference_input_type ) class TFLiteSavedModelConverter(TFLiteConverterBaseV1): """Converts the given SavedModel into TensorFlow Lite model. Attributes: saved_model_dir: Directory of the SavedModel. """ def __init__( self, saved_model_dir, saved_model_ta...
combine_chunk_392480
combine.txt
392,480
512
specified. None value for dimension in input_tensor. """ return super(TFLiteSavedModelConverter, self).convert() class TFLiteKerasModelConverter(TFLiteConverterBaseV1): """Converts the given SavedModel into TensorFlow Lite model.""" def __init__( self, model_file, input_arrays=...
combine_chunk_392481
combine.txt
392,481
512
build_debug_info_func(frozen_func.graph) return # Handles Keras when Eager mode is disabled. keras_deps.get_clear_session_function()() keras_model = keras_deps.get_load_model_function()( model_file, custom_objects ) sess = keras_deps.get_get_session_function()() # Get input and o...
combine_chunk_392482
combine.txt
392,482
512
a saved model. Returns: The converted data in serialized format. """ temp_dir = tempfile.mkdtemp() try: self._freeze_keras_model(temp_dir) if self.saved_model_dir: return super(TFLiteKerasModelConverter, self).convert() finally: shutil.rmtree(temp_dir, True) @_ex...
combine_chunk_392483
combine.txt
392,483
512
self._input_tensors = input_tensors self._output_tensors = output_tensors self._control_output_arrays = None # Attributes are used by models that cannot be loaded into TensorFlow. if not self._has_valid_tensors(): self._input_arrays_with_shape = input_arrays_with_shape self._output_arr...
combine_chunk_392484
combine.txt
392,484
512
in no particular order, from the training or evaluation dataset. This is an optional attribute, but required for full integer quantization, i.e, if `tf.int8` is the only supported type in `target_spec.supported_types`. Refer to `tf.lite.RepresentativeDataset`. (default None) target_spec: Ex...
combine_chunk_392485
combine.txt
392,485
512
Quant nodes in unexpected locations. Used when the location of the FakeQuant nodes is preventing graph transformations necessary to convert the graph. Results in a graph that differs from the quantized training graph, potentially causing differing arithmetic behavior. (default False) change_...
combine_chunk_392486
combine.txt
392,486
512
_graph( graph_def_file, input_arrays, output_arrays) tflite_model = converter.convert() open("converted_model.tflite", "wb").write(tflite_model) # Converting a SavedModel. converter = tf.compat.v1.lite.TFLiteConverter.from_saved_model( saved_model_dir) tflite_model = converter.convert() o...
combine_chunk_392487
combine.txt
392,487
512
Session. input_tensors: List of input tensors. Type and shape are computed using `foo.shape` and `foo.dtype`. output_tensors: List of output tensors (only .name is used from this). Returns: TFLiteConverter class. """ # pylint: disable=protected-access TFLiteConverterBase._set...
combine_chunk_392488
combine.txt
392,488
512
Error): try: print("Ignore 'tcmalloc: large alloc' warnings.") if not isinstance(file_content, str): file_content = file_content.decode("utf-8") graph_def = _graph_pb2.GraphDef() _text_format.Merge(file_content, graph_def) except (_text_...
combine_chunk_392489
combine.txt
392,489
512
tensor names to list of integers representing input shapes (e.g., {"foo" : [1, 16, 16, 3]}). Automatically determined when input shapes is None (e.g., {"foo" : None}). (default None) output_arrays: List of output tensors to freeze graph with. Uses output arrays from SignatureDef w...
combine_chunk_392490
combine.txt
392,490
512
, 3]}). Automatically determined when input shapes is None (e.g., {"foo" : None}). (default None) output_arrays: List of output tensors to freeze graph with. Uses output arrays from SignatureDef when none are provided. (default None) custom_objects: Dict mapping names (strings) to cu...
combine_chunk_392491
combine.txt
392,491
512
.from_saved_model` instead." ) def from_saved_model( cls, saved_model_dir, input_arrays=None, input_shapes=None, output_arrays=None, tag_set=None, signature_key=None, ): """Creates a TocoConverter class from a SavedModel.""" return TFLiteConverter.from_saved_model...
combine_chunk_392492
combine.txt
392,492
512
() try: while True: yield sess.run(input_data) except tf.errors.OutOfRangeError: pass def run_eval(interpreter, input_image): """Performs evaluation for input image over specified model. Args: interpreter: TFLite interpreter initialized with model to execute. input_image: ...
combine_chunk_392493
combine.txt
392,493
512
official/r1/mnist/dataset.py """ import gzip import os import shutil import tempfile import urllib import numpy as np import tensorflow as tf def read32(bytestream): """Read 4 bytes from bytestream as an unsigned 32-bit integer.""" dt = np.dtype(np.uint32).newbyteorder('>') return np.frombuffer(bytestream.rea...
combine_chunk_392494
combine.txt
392,494
512
shutil.copyfileobj(f_in, f_out) os.remove(zipped_filepath) return filepath def dataset(directory, images_file, labels_file): """Download and parse MNIST dataset.""" images_file = download(directory, images_file) labels_file = download(directory, labels_file) check_image_file_header(images_file) ch...
combine_chunk_392495
combine.txt
392,495
512
r"""Generate python docs for tf.lite. # How to run ``` python build_docs.py --output_dir=/path/to/output ``` """ import pathlib from absl import app from absl import flags import tensorflow as tf from tensorflow_docs.api_generator import generate_lib flags.DEFINE_string('output_dir', '/tmp/lite_api/', ...
combine_chunk_392496
combine.txt
392,496
512
"Use this branch as the root version and don't " 'create in version directory') _SITE_PATH = flags.DEFINE_string('site_path', 'lite/api_docs/java', 'Path prefix in the _toc.yaml') flags.DEFINE_string('code_url_prefix', None...
combine_chunk_392497
combine.txt
392,497
512
..., with root.""" nested = path.parts[0] / path if (root_path := root / path).exists(): return root_path elif (root_nested_path := root / nested).exists(): return root_nested_path raise ValueError(f'Could not find {path} or {nested}') def exists_maybe_nested(paths: Iterable[pathlib.Path], ...
combine_chunk_392498
combine.txt
392,498
512
v in EXTERNAL_APIS.items()}) if __name__ == '__main__': app.run(main) <|file|>tensorflow/tensorflow/lite/schema/upgrade_schema.py # ============================================================================== # Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Ve...
combine_chunk_392499
combine.txt
392,499
512
upgrade strategy to go from version to version. Usage: converter = Converter() converter.Convert("a.tflite", "a.json") converter.Convert("b.json", "b.tflite") """ def __init__(self): # TODO(aselle): make this work in the open source version with better # path. paths_to_try = [ "...