def test_debugger_creation_counter_increase_multiple_same_topic_success(self): try: stub = metrics.TFLiteMetrics() stub.increase_counter_debugger_creation() self.assertEqual(metrics._counter_debugger_creation.get_cell().value(), 1) stub2 = metrics.TFLiteMetrics() stub2.increase_counter_debugger_creation() self.assertEqual(metrics._counter_debugger_creation.get_cell().value(), 2) del stub gc.collect() stub2.increase_counter_debugger_creation() self.assertEqual(metrics._counter_debugger_creation.get_cell().value(), 3) except: raise Exception('No exception should be raised.')
def test_converter_params_multiple_set_success(self): stub = metrics.TFLiteMetrics() stub.set_converter_param('name', 'value') stub.set_converter_param('name', 'value1') self.assertEqual( metrics._gauge_conversion_params.get_cell('name').value(), 'value1')
def _initialize_stats(self): """Helper function initializes stats.""" # TODO(b/177749613) : Fix the dependency on tf.lite._get_ops_details() # Following code is needed to get op's name from the output tensor index, # since NumericVerify op only provides its quantized input tensor index. self._defining_op = dict() for op_info in self._quant_interpreter._get_ops_details(): # pylint: disable=protected-access self._defining_op.update({ tensor_idx: op_info['index'] for tensor_idx in op_info['outputs'] }) self._numeric_verify_tensor_details = None self._numeric_verify_op_details = None if not self._get_numeric_verify_tensor_details(): raise ValueError( 'Please check if the quantized model is in debug mode') self._layer_debug_metrics = _DEFAULT_LAYER_DEBUG_METRICS.copy() if self._debug_options.layer_debug_metrics: self._layer_debug_metrics.update( self._debug_options.layer_debug_metrics) self.layer_statistics = None self.model_statistics = None self._metrics = metrics_stub.TFLiteMetrics() self._metrics.increase_counter_debugger_creation()
def __init__(self, model_path=None, model_content=None, experimental_delegates=None, num_threads=None, experimental_op_resolver_type=OpResolverType.AUTO, experimental_preserve_all_tensors=False): """Constructor. Args: model_path: Path to TF-Lite Flatbuffer file. model_content: Content of model. experimental_delegates: Experimental. Subject to change. List of [TfLiteDelegate](https://www.tensorflow.org/lite/performance/delegates) objects returned by lite.load_delegate(). num_threads: Sets the number of threads used by the interpreter and available to CPU kernels. If not set, the interpreter will use an implementation-dependent default number of threads. Currently, only a subset of kernels, such as conv, support multi-threading. num_threads should be >= -1. Setting num_threads to 0 has the effect to disable multithreading, which is equivalent to setting num_threads to 1. If set to the value -1, the number of threads used will be implementation-defined and platform-dependent. experimental_op_resolver_type: The op resolver used by the interpreter. It must be 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 resolver type is AUTO or BUILTIN, the type will be changed to BUILTIN_WITHOUT_DEFAULT_DELEGATES so that no Tensorflow Lite default delegates are applied. If false, getting intermediate tensors could result in undefined values or None, especially when the graph is successfully modified by the Tensorflow Lite default delegate. Raises: ValueError: If the interpreter was unable to create. """ if not hasattr(self, '_custom_op_registerers'): self._custom_op_registerers = [] 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): actual_resolver_type = OpResolverType.BUILTIN_WITHOUT_DEFAULT_DELEGATES op_resolver_id = _get_op_resolver_id(actual_resolver_type) if op_resolver_id is None: raise ValueError('Unrecognized passed in op resolver type: {}'.format( experimental_op_resolver_type)) if model_path and not model_content: custom_op_registerers_by_name = [ x for x in self._custom_op_registerers if isinstance(x, str) ] custom_op_registerers_by_func = [ x for x in self._custom_op_registerers if not isinstance(x, str) ] self._interpreter = ( _interpreter_wrapper.CreateWrapperFromFile( model_path, op_resolver_id, custom_op_registerers_by_name, custom_op_registerers_by_func, experimental_preserve_all_tensors)) if not self._interpreter: raise ValueError('Failed to open {}'.format(model_path)) elif model_content and not model_path: custom_op_registerers_by_name = [ x for x in self._custom_op_registerers if isinstance(x, str) ] custom_op_registerers_by_func = [ x for x in self._custom_op_registerers if not isinstance(x, str) ] # Take a reference, so the pointer remains valid. # Since python strings are immutable then PyString_XX functions # will always return the same pointer. self._model_content = model_content self._interpreter = ( _interpreter_wrapper.CreateWrapperFromBuffer( model_content, op_resolver_id, custom_op_registerers_by_name, custom_op_registerers_by_func, experimental_preserve_all_tensors)) elif not model_content and not model_path: raise ValueError('`model_path` or `model_content` must be specified.') else: raise ValueError('Can\'t both provide `model_path` and `model_content`') if num_threads is not None: if not isinstance(num_threads, int): raise ValueError('type of num_threads should be int') if num_threads < 1: raise ValueError('num_threads should >= 1') self._interpreter.SetNumThreads(num_threads) # Each delegate is a wrapper that owns the delegates that have been loaded # as plugins. The interpreter wrapper will be using them, but we need to # hold them in a list so that the lifetime is preserved at least as long as # the interpreter wrapper. self._delegates = [] if experimental_delegates: self._delegates = experimental_delegates for delegate in self._delegates: self._interpreter.ModifyGraphWithDelegate( delegate._get_native_delegate_pointer()) # pylint: disable=protected-access self._signature_defs = self.get_signature_list() self._metrics = metrics.TFLiteMetrics() self._metrics.increase_counter_interpreter_creation()
def test_converter_success_counter_increase_success(self): stub = metrics.TFLiteMetrics() stub.increase_counter_converter_success() self.assertEqual( metrics._counter_conversion_success.get_cell().value(), 1)
def test_interpreter_creation_counter_increase_success(self): stub = metrics.TFLiteMetrics() stub.increase_counter_interpreter_creation() self.assertEqual( metrics._counter_interpreter_creation.get_cell('python').value(), 1)
def test_TFLiteMetrics_creation_fail2_with_only_model_path(self): with self.assertRaises(ValueError): metrics.TFLiteMetrics(model_path='/path/to/model')
def test_TFLiteMetrics_creation_fails_with_only_hash(self): with self.assertRaises(ValueError): metrics.TFLiteMetrics(model_hash='hash')
def test_TFLiteMetrics_creation_arg_success(self): metrics.TFLiteMetrics('hash', '/path/to/model')
def test_TFLiteMetrics_creation_no_arg_success(self): metrics.TFLiteMetrics()
def test_converter_params_set_latency(self): stub = metrics.TFLiteMetrics() stub.set_converter_latency(34566) self.assertEqual(metrics._gauge_conversion_latency.get_cell().value(), 34566)
def test_converter_params_set_success(self): stub = metrics.TFLiteMetrics() stub.set_converter_param('name', 'value')
def test_converter_success_counter_increase_success(self): stub = metrics.TFLiteMetrics() stub.increase_counter_converter_success()
def test_interpreter_creation_counter_increase_success(self): stub = metrics.TFLiteMetrics() stub.increase_counter_interpreter_creation()