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_392300
combine.txt
392,300
512
"); # 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, # WITHOUT WARRAN...
combine_chunk_392301
combine.txt
392,301
512
/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, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations...
combine_chunk_392302
combine.txt
392,302
512
.TensorSpec( shape=shape, dtype=model.input_dtype, name=key ) return specs elif isinstance(input_shape, list): specs = [] for shape in input_shape: shape = (None,) + shape[1:] specs.append(tensor_spec.TensorSpec(shape=shape, dtype=model.input_dtype)) return specs def mode...
combine_chunk_392303
combine.txt
392,303
512
(model): raise ValueError( 'Model {} cannot be saved because the input shapes have not been ' 'set. Usually, input shapes are automatically determined from calling' ' `.fit()` or `.predict()`. To manually set the shapes, call ' '`model.build(input_shape)`.'.format(model)) def _create_pseudo_...
combine_chunk_392304
combine.txt
392,304
512
model. """ if input_signature is None: if isinstance(model.call, def_function.Function): input_signature = model.call.input_signature if input_signature is None: input_signature = model_input_signature(model) if input_signature is None: raise_model_input_error(model) @def_function.functi...
combine_chunk_392305
combine.txt
392,305
512
.lite.python.optimize." "_pywrap_tensorflow_lite_calibration_wrapper" ), ) def add_intermediate_tensors(model_content): """Adds intermediate tensors to fused op if needed.""" return _calibration_wrapper.AddIntermediateTensors(model_content) class Calibrator: """Calibrates a floating point model an...
combine_chunk_392306
combine.txt
392,306
512
dictionary with input " "names and values in the second argument in the " "tuple" ) # Convert signature based inputs to the tensor index based data. if self._interpreter is None: self._interpreter = Interpreter(model_content=self._model_content) s...
combine_chunk_392307
combine.txt
392,307
512
shapes of the calibrator are resized with the calibration data if `resize_input` is set. Returns: A quantized model. Args: dataset_gen: A generator that generates calibration samples. input_type: A tf.dtype representing the desired real-value input type. output_type: A tf.dtype re...
combine_chunk_392308
combine.txt
392,308
512
an integer-only backend. If False, an error will be thrown if an operation cannot be quantized, otherwise the model will fallback to float ops. op_output_name: A string, only this op will be quantized. resize_input: A boolean. True if the shape of the sample data is different from t...
combine_chunk_392309
combine.txt
392,309
512
def Prepare(self, arg0: object) -> object: ... @overload def Prepare(self, arg0: str) -> object: ... @overload def Prepare(self) -> object: ... @overload def QuantizeModel(self, arg0: int, arg1: int, arg2: bool, arg3: int, arg4: int, arg5: bool, arg6: bool) -> object: ... @overload d...
combine_chunk_392310
combine.txt
392,310
512
from tensorflow.python.util import deprecation from tensorflow.python.util.tf_export import tf_export as _tf_export def _is_quantized_input_stats_required( conversion_flags: _conversion_flags_pb2.ConverterFlags, ) -> bool: """Checks if the `quantized_input_stats` flag is required for conversion. Args: co...
combine_chunk_392311
combine.txt
392,311
512
} tflite_type = mapping.get(tf_type) if tflite_type is None: raise ValueError( "Unsupported TensorFlow type `{0}` provided for the {1}".format( tf_type, usage ) ) return tflite_type # Only a few restricted tensor types are allowed for explicitly setting # inference/input/out...
combine_chunk_392312
combine.txt
392,312
512
TFLITE_BUILTINS_INT8 = "TFLITE_BUILTINS_INT8" # Convert model using only TensorFlow Lite operations with quantized int8 # weights, int16 activations and int64 bias. # Specifying this will throw an error for operations that do not yet have # quantized implementations. # This quantization mode may be used in ...
combine_chunk_392313
combine.txt
392,313
512
wrap_converter.wrapped_flat_buffer_file_to_mlir( model_content, input_is_filepath=input_is_filepath, bytecode=bytecode, cl_options=cl_options, ) @convert_phase(Component.OPTIMIZE_TFLITE_MODEL, SubComponent.UNSPECIFIED) def mlir_to_flatbuffer( mlir_content, input_is_filepath=False, ...
combine_chunk_392314
combine.txt
392,314
512
-channel or per-tensor quantization fully_quantize: Bool indicating whether to fully quantize the model. Besides model body, the input/output will be quantized as well. inference_type: Data type for the activations. The default value is int8. input_data_type: Data type for the inputs. The defaul...
combine_chunk_392315
combine.txt
392,315
512
_data_str` to encode sparse tensor with proper format. Args: input_data_str: Input data in serialized form (e.g. a TFLITE model). Returns: Sparsified model in serialized form (e.g. a TFLITE model). """ return wrap_converter.wrapped_experimental_mlir_sparsify(input_data_str) def register_custom_opdef...
combine_chunk_392316
combine.txt
392,316
512
properly # inlined. if ( error_data.error_code == converter_error_data_pb2.ConverterErrorData.ERROR_STATEFUL_PARTITIONED_CALL_IN_FINAL_IR and not conversion_flags.guarantee_all_funcs_one_use ): conversion_flags.guarantee_all_funcs_one_use = True return co...
combine_chunk_392317
combine.txt
392,317
512
the SavedModel import path will be used. saved_model_tags: Set of string saved model tags, formatted in the comma-separated value. This value will be set only when the SavedModel import path will be used. saved_model_exported_names: Names to be exported (default: export all) when the sa...
combine_chunk_392318
combine.txt
392,318
512
=False, ir_dump_dir=None, ir_dump_pass_regex=None, ir_dump_func_regex=None, enable_timing=None, print_ir_before=None, print_ir_after=None, print_ir_module_scope=None, elide_elementsattrs_if_larger=None, use_buffer_offset=False, reduce_type_precision=False, qdq_conversion_mode...
combine_chunk_392319
combine.txt
392,319
512
differs from the quantized training graph, potentially causing differing arithmetic behavior. (default False) allow_custom_ops: Boolean indicating whether to allow custom operations. When false any unknown operation is an error. When true, custom ops are created for any op that is unknown. The de...
combine_chunk_392320
combine.txt
392,320
512
when the tensor list ops has the unspecified batch size. accumulation_type: Data type of the accumulators in quantized inference. Typically used for float16 quantization and is either fp16 or fp32. allow_bfloat16: Whether the converted model supports reduced precision inference with the bfloat16 ty...
combine_chunk_392321
combine.txt
392,321
512
izing weights. ir_dump_dir: A string specifying the target directory to output MLIR dumps produced during conversion. If populated, enables MLIR dumps. ir_dump_pass_regex: A string containing a regular expression for filtering the pass names to be dumped. Effective only if `ir_dump_dir` is populated...
combine_chunk_392322
combine.txt
392,322
512
+Inf/-Inf to MIN/MAX float value and output of converter only contains finite values. serialize_debug_metadata: When set to true, serialize debug metadata in the flatbuffer. unsafe_fuse_dynamic_shaped_broadcast: When set to true, allows fusion of dynamic shaped broadcast ops. It helps fusing ...
combine_chunk_392323
combine.txt
392,323
512
target_ops: conversion_flags.convert_to_stablehlo = True if OpsSet.EXPERIMENTAL_STABLEHLO_OPS in target_ops and len(target_ops) > 1: raise ValueError( "StableHLO Ops set can not be specified with other Ops set together" ) if conversion_summary_dir: conversion_flags.conversion_summ...
combine_chunk_392324
combine.txt
392,324
512
ir_variable_quantization = ( enable_mlir_variable_quantization ) conversion_flags.disable_fuse_mul_and_fc = disable_fuse_mul_and_fc # Transfer debug options. Check for existence before populating in order to # leverage defaults specified in proto definition. # TODO: b/319329480 - Match the debug_option...
combine_chunk_392325
combine.txt
392,325
512
_metadata conversion_flags.unsafe_fuse_dynamic_shaped_broadcast = ( unsafe_fuse_dynamic_shaped_broadcast ) conversion_flags.unsafe_single_batch_rank_reduction = ( unsafe_single_batch_rank_reduction ) return conversion_flags @convert_phase( Component.CONVERT_TF_TO_TFLITE_MODEL, SubComponent....
combine_chunk_392326
combine.txt
392,326
512
` flag must be defined when either " "`inference_type` flag or `inference_input_type` flag is set to " "tf.int8 or tf.uint8." ) input_array.name = name input_array.shape.dims.extend(list(map(int, shape))) if output_arrays: for name in output_arrays: model_flags.outpu...
combine_chunk_392327
combine.txt
392,327
512
if quantized_input_stats: input_array.mean_value, input_array.std_value = quantized_input_stats[ idx ] else: # We should ideally raise an error here, but we don't as it would break # several models/projects that depend on this workflow. warnings.warn( ...
combine_chunk_392328
combine.txt
392,328
512
.HLO_TEXT # Build input names. for input_name in input_names: input_array = model_flags.input_arrays.add() input_array.name = input_name conversion_flags = build_conversion_flags(**kwargs) data = convert( model_flags, conversion_flags, input_data_str=input_content, debug_info_s...
combine_chunk_392329
combine.txt
392,329
512
graphs: # To get all the read-only buffers: # (1) Get all read-only input tensors. # (2) Discard intermediate or output tensors. # (3) Discard the subgraph's input/output tensors. # (4) Gather the buffers of the read-only input tensors. # (1) Get read-only input tensors. read_only_input_ten...
combine_chunk_392330
combine.txt
392,330
512
FLite model.""" def __init__(self, idx, size, hash_value): self.idx = idx self.size = size self.hash_value = hash_value read_only_buffers = list( map( lambda index: BufferIndex( # pylint: disable=g-long-lambda index, model.buffers[index].data.size, ...
combine_chunk_392331
combine.txt
392,331
512
# Return a TFLite flatbuffer as a byte array. return flatbuffer_utils.convert_object_to_bytearray(model) <|file|>tensorflow/tensorflow/lite/python/metrics/_pywrap_tensorflow_lite_metrics_wrapper.pyi # Copyright 2023 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (th...
combine_chunk_392332
combine.txt
392,332
512
TFLite metrics helper.""" def __init__(self, model_hash: Optional[Text] = None, model_path: Optional[Text] = None) -> None: pass def increase_counter_debugger_creation(self): pass def increase_counter_interpreter_creation(self): pass def increase_counter_converter_a...
combine_chunk_392333
combine.txt
392,333
512
ite/python/metrics/metrics_nonportable.py # Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the 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/...
combine_chunk_392334
combine.txt
392,334
512
latency in ms.') class TFLiteMetrics(metrics_interface.TFLiteMetricsInterface): """TFLite metrics helper for prod (borg) environment. Attributes: model_hash: A string containing the hash of the model binary. model_path: A string containing the path of the model for debugging purposes. """ def...
combine_chunk_392335
combine.txt
392,335
512
: self.export_metrics() def set_export_required(self): self._exported = False def export_metrics(self): self._metrics_exporter.ExportMetrics() self._exported = True <|file|>tensorflow/tensorflow/lite/python/metrics/metrics_interface.py # Copyright 2021 The TensorFlow Authors. All Rights Reserve...
combine_chunk_392336
combine.txt
392,336
512
# limitations under the License. # ============================================================================== """Python TF-Lite interpreter.""" import ctypes import enum import os import platform import sys import warnings import numpy as np # pylint: disable=g-import-not-at-top if not os.path.splitext(__file__)...
combine_chunk_392337
combine.txt
392,337
512
need for __del__ ordering needs of CPython # by using explicit closes(). See implementation of Interpreter __del__. if platform.python_implementation() != 'CPython': raise RuntimeError('Delegates are currently only supported into CPython' 'due to missing immediate reference count...
combine_chunk_392338
combine.txt
392,338
512
because it needs to be freed. Returns: TfLiteDelegate * """ return self._delegate_ptr @_tf_export('lite.experimental.load_delegate') def load_delegate(library, options=None): """Returns loaded Delegate object. Example usage: ``` import tensorflow as tf try: delegate = tf.lite.expe...
combine_chunk_392339
combine.txt
392,339
512
if not interpreter: raise ValueError('None interpreter provided.') if not signature_key: raise ValueError('None signature_key provided.') self._interpreter = interpreter self._interpreter_wrapper = interpreter._interpreter self._signature_key = signature_key signature_defs = interpre...
combine_chunk_392340
combine.txt
392,340
512
where each item is a dictionary with details about an input tensor. Each dictionary contains the following fields that describe the tensor: + `name`: The tensor name. + `index`: The tensor index in the interpreter. + `shape`: The shape of the tensor. + `shape_signature`: Same as `s...
combine_chunk_392341
combine.txt
392,341
512
BUILTIN`: Indicates the op resolver for built-in ops with optimized kernel implementation. * `BUILTIN_REF`: Indicates the op resolver for built-in ops with reference kernel implementation. It's generally used for testing and debugging. * `BUILTIN_WITHOUT_DEFAULT_DELEGATES`: Indicates the op resolver for ...
combine_chunk_392342
combine.txt
392,342
512
tf.keras.layers.Dense(units=1, input_shape=[1]) ... ]) >>> model.compile(optimizer='sgd', loss='mean_squared_error') >>> model.fit(x, y, epochs=1) >>> converter = tf.lite.TFLiteConverter.from_keras_model(model) >>> tflite_model = converter.convert() `tflite_model` can be saved to a file ...
combine_chunk_392343
combine.txt
392,343
512
an instance of OpResolverType. By default, we use the built-in op resolver which corresponds to tflite::ops::builtin::BuiltinOpResolver in C++. experimental_preserve_all_tensors: If true, then intermediate tensors used during computation are preserved for inspection, and if the passed op ...
combine_chunk_392344
combine.txt
392,344
512
( experimental_compress_quantization_zero_points ) actual_resolver_type = experimental_op_resolver_type if experimental_preserve_all_tensors and ( experimental_op_resolver_type == OpResolverType.AUTO or experimental_op_resolver_type == OpResolverType.BUILTIN): warnings.warn( ...
combine_chunk_392345
combine.txt
392,345
512
self._interpreter = _interpreter_wrapper.CreateWrapperFromBuffer( model_content, op_resolver_id, custom_op_registerers_by_name, custom_op_registerers_by_func, experimental_preserve_all_tensors, experimental_disable_delegate_clustering, int(num_...
combine_chunk_392346
combine.txt
392,346
512
2 (1 in self and 1 in temporary of sys.getrefcount). return sys.getrefcount(self._interpreter) == 2 def _ensure_safe(self): """Makes sure no numpy arrays pointing to internal buffers are active. This should be called from any function that will call a function on _interpreter that may reallocate me...
combine_chunk_392347
combine.txt
392,347
512
'quantization_parameters'. This field only works for per-tensor quantization, whereas 'quantization_parameters' work in all cases. 'quantization_parameters': The parameters used to quantize the tensor: 'scales': List of scales (one if per-tensor quantization) 'zero_p...
combine_chunk_392348
combine.txt
392,348
512
Subgraphs() def get_tensor_details(self, subgraph_index=0): """Gets tensor details for every tensor with valid tensor details from a subgraph. Tensors where required information about the tensor is not found are not added to the list. This includes temporary tensors without a name. Args: subg...
combine_chunk_392349
combine.txt
392,349
512
zero_points. + `sparsity_parameters`: A dictionary of parameters used to encode a sparse tensor. This is empty if the tensor is dense. """ return [ self._get_tensor_details(i, subgraph_index=0) for i in self._interpreter.InputIndices() ] def set_tensor(self, tensor_index, va...
combine_chunk_392350
combine.txt
392,350
512
item is a dictionary with details about an output tensor. The dictionary contains the same fields as described for `get_input_details()`. """ return [ self._get_tensor_details(i, subgraph_index=0) for i in self._interpreter.OutputIndices() ] def get_signature_list(self): ...
combine_chunk_392351
combine.txt
392,351
512
], dtype=float32) # } ``` None can be passed for signature_key if the model has a single Signature only. All names used are these specific SignatureDef names. Args: signature_key: Signature key for the SignatureDef, it can be None if and only if the model has a single Signature...
combine_chunk_392352
combine.txt
392,352
512
_details()[0]["index"]) output = interpreter.tensor(interpreter.get_output_details()[0]["index"]) for i in range(10): input().fill(3.) interpreter.invoke() print("inference %s" % output()) ``` Notice how this function avoids making a numpy array directly. This is because it is imp...
combine_chunk_392353
combine.txt
392,353
512
function. Consider how that may work in a custom pybind wrapper: m.def("SomeNewFeature", ([](py::object handle) { auto* interpreter = reinterpret_cast<tflite::Interpreter*>(handle.cast<intptr_t>()); ... })) and corresponding Python call: SomeNewFeature(interpreter....
combine_chunk_392354
combine.txt
392,354
512
disable=g-import-not-at-top if not os.path.splitext(__file__)[0].endswith( os.path.join("tflite_runtime", "analyzer")): # This file is part of tensorflow package. from tensorflow.compiler.mlir.lite.python import wrap_converter from tensorflow.lite.python.analyzer_wrapper import _pywrap_analyzer_wrapper as _a...
combine_chunk_392355
combine.txt
392,355
512
model structure. This tool provides a way to understand users' TFLite flatbuffer model by dumping internal graph structure. It also provides additional features like checking GPU delegate compatibility. WARNING: Experimental interface, subject to change. The output format is not guarante...
combine_chunk_392356
combine.txt
392,356
512
distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Converts a TFLite model ...
combine_chunk_392357
combine.txt
392,357
512
"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, # WITHO...
combine_chunk_392358
combine.txt
392,358
512
, nargs=None, **kwargs): if nargs != "?": # This should never happen. This class is only used once below with # nargs="?". raise ValueError( "This parser only supports nargs='?' (0 or 1 additional arguments)") super(_ParseBooleanFlag, self).__init__( option_strings, dest, nar...
combine_chunk_392359
combine.txt
392,359
512
_model_signature_key elif flags.keras_model_file: converter_fn = lite.TFLiteConverter.from_keras_model_file converter_kwargs["model_file"] = flags.keras_model_file else: raise ValueError("--graph_def_file, --saved_model_dir, or " "--keras_model_file must be specified.") return co...
combine_chunk_392360
combine.txt
392,360
512
(list(zip(input_arrays, quant_stats))) if (flags.default_ranges_min is not None) and (flags.default_ranges_max is not None): converter.default_ranges_stats = (flags.default_ranges_min, flags.default_ranges_max) if flags.drop...
combine_chunk_392361
combine.txt
392,361
512
_summary_dir converter.experimental_new_converter = flags.experimental_new_converter if flags.experimental_new_quantizer is not None: converter.experimental_new_quantizer = flags.experimental_new_quantizer # Convert model. output_data = converter.convert() with gfile.GFile(flags.output_file, "wb") as f...
combine_chunk_392362
combine.txt
392,362
512
"--std_value", "--std_dev_values") output += _get_message_unparsed(flag, "--batch_size", "--input_shapes") output += _get_message_unparsed(flag, "--dump_graphviz", "--dump_graphviz_dir") if output: raise ValueError(output) # Check that flags are valid. i...
combine_chunk_392363
combine.txt
392,363
512
") def _get_tf1_flags(parser): """Returns ArgumentParser for tflite_convert for TensorFlow 1.X. Args: parser: ArgumentParser """ # Input file flags. input_file_group = parser.add_mutually_exclusive_group(required=True) input_file_group.add_argument( "--graph_def_file", type=str, hel...
combine_chunk_392364
combine.txt
392,364
512
ization flags. parser.add_argument( "--std_dev_values", type=str, help=("Standard deviation of training data for each input tensor, " "comma-separated floats. Used for quantized input tensors. " "(default None)")) parser.add_argument( "--mean_values", type=str, ...
combine_chunk_392365
combine.txt
392,365
512
" "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)")) # Usage for this flag is --change_concat_input...
combine_chunk_392366
combine.txt
392,366
512
.dot files. Preferred over --output_format=" "GRAPHVIZ_DOT in order to keep the requirements of the output " "file.")) parser.add_argument( "--dump_graphviz_video", action="store_true", help=("Boolean indicating whether to dump the graph after every graph " "tran...
combine_chunk_392367
combine.txt
392,367
512
output file.", required=True) if use_v2_converter: _get_tf2_flags(parser) else: _get_tf1_flags(parser) parser.add_argument( "--experimental_new_converter", action=_ParseBooleanFlag, nargs="?", default=True, help=("Experimental flag, subject to change. Enables MLIR-ba...
combine_chunk_392368
combine.txt
392,368
512
" the new converter via --experimental_new_converter. ") def main(): app.run(main=run_main, argv=sys.argv[:1]) if __name__ == "__main__": main() <|file|>tensorflow/tensorflow/lite/python/lite_constants.py # Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Vers...
combine_chunk_392369
combine.txt
392,369
512
converter_flags_pb2.ConverterFlags.PYTORCH ) _tf_export(v1=["lite.constants.FLOAT"]).export_constant(__name__, "FLOAT") _tf_export(v1=["lite.constants.FLOAT16"]).export_constant(__name__, "FLOAT16") _tf_export(v1=["lite.constants.INT32"]).export_constant(__name__, "INT32") _tf_export(v1=["lite.constants.INT64"]).expor...
combine_chunk_392370
combine.txt
392,370
512
ager import def_function def tflite_convert(fn, input_templates): """Converts the provided fn to tf.lite model. Args: fn: A callable that expects a list of inputs like input_templates that returns a tensor or structure of tensors. input_templates: A list of Tensors, ndarrays or TensorSpecs describi...
combine_chunk_392371
combine.txt
392,371
512
# distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ========================================================================...
combine_chunk_392372
combine.txt
392,372
512
_info): return [tensor_info[key].name for key in tensor_info] inputs = gather_names(inputs_tensor_info) outputs = gather_names(outputs_tensor_info) return inputs, outputs def _get_tensors(graph, signature_def_tensor_names=None, user_tensor_names=None): """Gets the tensors associated with...
combine_chunk_392373
combine.txt
392,373
512
. tag_set: Set of tags identifying the MetaGraphDef within the SavedModel to analyze. All tags in the tag set must be present. signature_key: Key identifying SignatureDef containing inputs and outputs. Returns: frozen_graph_def: Frozen GraphDef. in_tensors: List of input tensors for the graph. ...
combine_chunk_392374
combine.txt
392,374
512
express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== class InterpreterWrapper: def __init__(self, *args, **kwargs) -> None: ... def AllocateTensors(self, subgr...
combine_chunk_392375
combine.txt
392,375
512
-> object: ... def CreateWrapperFromBuffer(*args, **kwargs): ... def CreateWrapperFromFile(*args, **kwargs): ... <|file|>tensorflow/tensorflow/lite/python/test_util.py # Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use t...
combine_chunk_392376
combine.txt
392,376
512
<|file|>tensorflow/tensorflow/lite/python/schema_util.py # Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the 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.apa...
combine_chunk_392377
combine.txt
392,377
512
def ModelAnalyzer(arg0: str, arg1: bool, arg2: bool) -> str: ... <|file|>tensorflow/tensorflow/lite/python/op_hint.py # Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # Yo...
combine_chunk_392378
combine.txt
392,378
512
use cool_activation above you essentially get: a_input = tf.identity() result = tf.multiply(tf.sigmoid(a_input), a_input) output = tf.identity() a_input, output are identities that have parameters representing what argument they are, what the name of the function they should turn into in tf lite as well as a guid th...
combine_chunk_392379
combine.txt
392,379
512
an alternative implementation can be substituted later. Essentially, any "input" into this pseudo op is fed into an identity, and attributes are added to that input before being used by the constituent ops that make up the pseudo op. A similar process is done to any output that is to be exported from the cu...
combine_chunk_392380
combine.txt
392,380
512
this is for high level Ophint only. # This basically contains three kinds of mapping: # 1) How parental ophinted inputs map to the first child ophinted inputs; # 2) How internal children nodes are connected; # 3) How parental ophinted outputs map to the last child ophinted outputs. CHILDREN_INPUTS_MAPP...
combine_chunk_392381
combine.txt
392,381
512
be 0 for both # and the sort index will be 0 for the first added and 1 for the second. self._function_name = function_name self._unique_function_id = unique_function_id self._next_global_index = 0 # The absolute global index self._used_global_indices = set() self._tag_to_global_ind...
combine_chunk_392382
combine.txt
392,382
512
final stub be as stub_func(inputs[arg1, arg0], outputs=[]) rather than the default call order based ordering. Returns: A tensor representing the wrapped argument. Raises: ValueError: When indices are not consistent. """ # Find the appropriate index if tag is N...
combine_chunk_392383
combine.txt
392,383
512
.as_bytes(_json.dumps( self._children_inputs_mappings)))) if sort_index is not None: identity_op.op._set_attr( OpHint.FUNCTION_SORT_INDEX_ATTR, _attr_value_pb2.AttrValue(i=sort_index)) if aggregate is not None: identity_op.op._set_attr( ...
combine_chunk_392384
combine.txt
392,384
512
children_inputs_mappings: the Children ophint inputs/outputs mapping. """ assert isinstance(children_inputs_mappings, dict) assert "parent_first_child_input" in children_inputs_mappings assert "parent_last_child_output" in children_inputs_mappings assert "internal_children_input_output" in children...
combine_chunk_392385
combine.txt
392,385
512
*args: The output tensor. **kwargs: "name" label "tag" a tag to group multiple arguments that will be aggregated. I.e. a string like 'cool_input'. Basically multiple inputs can be added to the same hint for parallel operations that will eventually be combined. An exa...
combine_chunk_392386
combine.txt
392,386
512
information about the hint identity operators. They are also responsible for knowing how to serialize to output graphdefs. Typically this will be implemented by holding one or more identity nodes that were previously discovered as hints. """ def aggregate_and_return_name_for_input(self, out_graphdef): ...
combine_chunk_392387
combine.txt
392,387
512
should all be tracked as related arguments. """ def __init__(self, aggregation): _LiteOperand.__init__(self) self.aggregation = aggregation self.names = {} self.nodes = {} self.flattened = None def add(self, sort, node): self.names[sort] = _tensor_name_base(node.name) self.nodes[s...
combine_chunk_392388
combine.txt
392,388
512
== 1 and self.aggregation != OpHint.AGGREGATE_STACK: return _tensor_name_base(flattened[0].name) else: new_node = _node_def_pb2.NodeDef() new_node.op = "Pack" new_node.name = "OpHintStack-%s" % flattened[0].name new_node.attr["N"].i = len(flattened) new_node.attr["T"].type = fla...
combine_chunk_392389
combine.txt
392,389
512
_index)) out_graphdef.node.extend([stack_node]) for idx, discrete in enumerate(flattened): output_node = _copy.deepcopy(discrete) del output_node.input[:] output_node.input.append(_tensorflow_output_name(stack_node.name, idx)) out_graphdef.node.extend([output_node]) r...
combine_chunk_392390
combine.txt
392,390
512
format_args(self.inputs) outputs_str = "\tOutputs\n" + format_args(self.outputs) return ( "tflite function %s call %s level %d " "\n\tinputs:\n\t\t%s\n\toutputs:\n\t\t%s" % (self.function_name, self.uuid, self.level, inputs_str, outputs_str)) def _find_all_hints_in_nodes(nodes): ""...
combine_chunk_392391
combine.txt
392,391
512
in attr: put_operand(call_def.inputs, attr[OpHint.FUNCTION_INPUT_INDEX_ATTR].i, sort, node, aggregation) if OpHint.FUNCTION_OUTPUT_INDEX_ATTR in attr: put_operand(call_def.outputs, attr[OpHint.FUNCTION_OUTPUT_INDEX_ATTR].i, sort, node, aggregation) # Remember at...
combine_chunk_392392
combine.txt
392,392
512
: call: Parent OpHint that contains children ophints. graph_def: Original graph def. Returns: Ordered children hints inside the parent ophint; new graph def that contains nodes inside function defs (if applicable); nodes inside function defs. """ name_to_input_name, _, _ = _extract_graph_summary(...
combine_chunk_392393
combine.txt
392,393
512
full_tensor_name.startswith("^"): return full_tensor_name[1:] return full_tensor_name.split(":")[0] def _tensorflow_output_name(tensor_name, output_index): return tensor_name if output_index == 0 else "%s:%d" % (tensor_name, output_index) def _check...
combine_chunk_392394
combine.txt
392,394
512
= call.flattened_inputs_and_outputs() reachable_by_input = _bfs_for_reachable_nodes(input_names, name_to_input_name) reachable_by_output = _bfs_for_reachable_nodes(output_names, name_to_input_name) output_nodes_set = set(output_names) nodes_after_fuse = [] no...
combine_chunk_392395
combine.txt
392,395
512
Value(type=_dtypes.float32.as_datatype_enum)) optional_input_node.attr["value"].CopyFrom( _attr_value_pb2.AttrValue( tensor=_tensor_util.make_tensor_proto([-1], _dtypes.float32, [1]))) out.node.extend([optional_input_node]) max_index = max(sorted_input_indices) + 1 for cur_index in range(max_in...
combine_chunk_392396
combine.txt
392,396
512
omething) where changed_something is true if anything was done. """ name_to_input_name, name_to_node, name_to_seq_num = _extract_graph_summary( in_graph_def) del name_to_seq_num do_generic_pack_unpack = True out = _graph_pb2.GraphDef() out.library.CopyFrom(in_graph_def.library) out.versions.Co...
combine_chunk_392397
combine.txt
392,397
512
= False # Proceed with the substitution if the stack/unstack pair was created # through hints, or that it was not, but nobody is consuming things # between the stack and unstack. if is_hint_created_stack or no_external_dependency: end = unpack_nodes.pop() end_input = name_to_nod...
combine_chunk_392398
combine.txt
392,398
512
del graph_def # prevent using graph_def again (common source of error) for i in range(len(hints_q) - 1, -1, -1): level, hint_uuid = hints_q[i] if level >= 2: children_hints, curr_graph_def, function_def_nodes = _find_children_hints( hints[hint_uuid], curr_graph_def) # pylint: disable=...
combine_chunk_392399
combine.txt
392,399
512
_def = _convert_single_op_hint_to_stub(hints[hint_uuid], curr_graph_def) write_callback(curr_graph_def, "initial") # The stubbing process can create stacks/unstacks in the case of LSTMs # remove them. curr_graph_def = _remove_redundant_stack_unstack(cur...