• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Lint as: python2, python3
2# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#     http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15# ==============================================================================
16"""Python TF-Lite interpreter."""
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import print_function
20
21import ctypes
22import platform
23import sys
24
25import numpy as np
26
27# pylint: disable=g-import-not-at-top
28if not __file__.endswith('tflite_runtime/interpreter.py'):
29  # This file is part of tensorflow package.
30  from tensorflow.python.util.lazy_loader import LazyLoader
31  from tensorflow.python.util.tf_export import tf_export as _tf_export
32
33  # Lazy load since some of the performance benchmark skylark rules
34  # break dependencies. Must use double quotes to match code internal rewrite
35  # rule.
36  # pylint: disable=g-inconsistent-quotes
37  _interpreter_wrapper = LazyLoader(
38      "_interpreter_wrapper", globals(),
39      "tensorflow.lite.python.interpreter_wrapper."
40      "tensorflow_wrap_interpreter_wrapper")
41  # pylint: enable=g-inconsistent-quotes
42
43  del LazyLoader
44else:
45  # This file is part of tflite_runtime package.
46  from tflite_runtime import interpreter_wrapper as _interpreter_wrapper
47
48  def _tf_export(*x, **kwargs):
49    del x, kwargs
50    return lambda x: x
51
52
53class Delegate(object):
54  """Python wrapper class to manage TfLiteDelegate objects.
55
56  The shared library is expected to have two functions:
57    TfLiteDelegate* tflite_plugin_create_delegate(
58        char**, char**, size_t, void (*report_error)(const char *))
59    void tflite_plugin_destroy_delegate(TfLiteDelegate*)
60
61  The first one creates a delegate object. It may return NULL to indicate an
62  error (with a suitable error message reported by calling report_error()).
63  The second one destroys delegate object and must be called for every
64  created delegate object. Passing NULL as argument value is allowed, i.e.
65
66    tflite_plugin_destroy_delegate(tflite_plugin_create_delegate(...))
67
68  always works.
69  """
70
71  def __init__(self, library, options=None):
72    """Loads delegate from the shared library.
73
74    Args:
75      library: Shared library name.
76      options: Dictionary of options that are required to load the delegate. All
77        keys and values in the dictionary should be serializable. Consult the
78        documentation of the specific delegate for required and legal options.
79        (default None)
80    Raises:
81      RuntimeError: This is raised if the Python implementation is not CPython.
82    """
83
84    # TODO(b/136468453): Remove need for __del__ ordering needs of CPython
85    # by using explicit closes(). See implementation of Interpreter __del__.
86    if platform.python_implementation() != 'CPython':
87      raise RuntimeError('Delegates are currently only supported into CPython'
88                         'due to missing immediate reference counting.')
89
90    self._library = ctypes.pydll.LoadLibrary(library)
91    self._library.tflite_plugin_create_delegate.argtypes = [
92        ctypes.POINTER(ctypes.c_char_p),
93        ctypes.POINTER(ctypes.c_char_p), ctypes.c_int,
94        ctypes.CFUNCTYPE(None, ctypes.c_char_p)
95    ]
96    self._library.tflite_plugin_create_delegate.restype = ctypes.c_void_p
97
98    # Convert the options from a dictionary to lists of char pointers.
99    options = options or {}
100    options_keys = (ctypes.c_char_p * len(options))()
101    options_values = (ctypes.c_char_p * len(options))()
102    for idx, (key, value) in enumerate(options.items()):
103      options_keys[idx] = str(key).encode('utf-8')
104      options_values[idx] = str(value).encode('utf-8')
105
106    class ErrorMessageCapture(object):
107
108      def __init__(self):
109        self.message = ''
110
111      def report(self, x):
112        self.message += x if isinstance(x, str) else x.decode('utf-8')
113
114    capture = ErrorMessageCapture()
115    error_capturer_cb = ctypes.CFUNCTYPE(None, ctypes.c_char_p)(capture.report)
116    # Do not make a copy of _delegate_ptr. It is freed by Delegate's finalizer.
117    self._delegate_ptr = self._library.tflite_plugin_create_delegate(
118        options_keys, options_values, len(options), error_capturer_cb)
119    if self._delegate_ptr is None:
120      raise ValueError(capture.message)
121
122  def __del__(self):
123    # __del__ can not be called multiple times, so if the delegate is destroyed.
124    # don't try to destroy it twice.
125    if self._library is not None:
126      self._library.tflite_plugin_destroy_delegate.argtypes = [ctypes.c_void_p]
127      self._library.tflite_plugin_destroy_delegate(self._delegate_ptr)
128      self._library = None
129
130  def _get_native_delegate_pointer(self):
131    """Returns the native TfLiteDelegate pointer.
132
133    It is not safe to copy this pointer because it needs to be freed.
134
135    Returns:
136      TfLiteDelegate *
137    """
138    return self._delegate_ptr
139
140
141@_tf_export('lite.experimental.load_delegate')
142def load_delegate(library, options=None):
143  """Returns loaded Delegate object.
144
145  Args:
146    library: Name of shared library containing the
147      [TfLiteDelegate](https://www.tensorflow.org/lite/performance/delegates).
148    options: Dictionary of options that are required to load the delegate. All
149      keys and values in the dictionary should be convertible to str. Consult
150      the documentation of the specific delegate for required and legal options.
151      (default None)
152
153  Returns:
154    Delegate object.
155
156  Raises:
157    ValueError: Delegate failed to load.
158    RuntimeError: If delegate loading is used on unsupported platform.
159  """
160  try:
161    delegate = Delegate(library, options)
162  except ValueError as e:
163    raise ValueError('Failed to load delegate from {}\n{}'.format(
164        library, str(e)))
165  return delegate
166
167
168@_tf_export('lite.Interpreter')
169class Interpreter(object):
170  """Interpreter interface for TensorFlow Lite Models.
171
172  This makes the TensorFlow Lite interpreter accessible in Python.
173  It is possible to use this interpreter in a multithreaded Python environment,
174  but you must be sure to call functions of a particular instance from only
175  one thread at a time. So if you want to have 4 threads running different
176  inferences simultaneously, create  an interpreter for each one as thread-local
177  data. Similarly, if you are calling invoke() in one thread on a single
178  interpreter but you want to use tensor() on another thread once it is done,
179  you must use a synchronization primitive between the threads to ensure invoke
180  has returned before calling tensor().
181  """
182
183  def __init__(self,
184               model_path=None,
185               model_content=None,
186               experimental_delegates=None):
187    """Constructor.
188
189    Args:
190      model_path: Path to TF-Lite Flatbuffer file.
191      model_content: Content of model.
192      experimental_delegates: Experimental. Subject to change. List of
193        [TfLiteDelegate](https://www.tensorflow.org/lite/performance/delegates)
194        objects returned by lite.load_delegate().
195
196    Raises:
197      ValueError: If the interpreter was unable to create.
198    """
199    if not hasattr(self, '_custom_op_registerers'):
200      self._custom_op_registerers = []
201    if model_path and not model_content:
202      self._interpreter = (
203          _interpreter_wrapper.InterpreterWrapper_CreateWrapperCPPFromFile(
204              model_path, self._custom_op_registerers))
205      if not self._interpreter:
206        raise ValueError('Failed to open {}'.format(model_path))
207    elif model_content and not model_path:
208      # Take a reference, so the pointer remains valid.
209      # Since python strings are immutable then PyString_XX functions
210      # will always return the same pointer.
211      self._model_content = model_content
212      self._interpreter = (
213          _interpreter_wrapper.InterpreterWrapper_CreateWrapperCPPFromBuffer(
214              model_content, self._custom_op_registerers))
215    elif not model_path and not model_path:
216      raise ValueError('`model_path` or `model_content` must be specified.')
217    else:
218      raise ValueError('Can\'t both provide `model_path` and `model_content`')
219
220    # Each delegate is a wrapper that owns the delegates that have been loaded
221    # as plugins. The interpreter wrapper will be using them, but we need to
222    # hold them in a list so that the lifetime is preserved at least as long as
223    # the interpreter wrapper.
224    self._delegates = []
225    if experimental_delegates:
226      self._delegates = experimental_delegates
227      for delegate in self._delegates:
228        self._interpreter.ModifyGraphWithDelegate(
229            delegate._get_native_delegate_pointer())  # pylint: disable=protected-access
230
231  def __del__(self):
232    # Must make sure the interpreter is destroyed before things that
233    # are used by it like the delegates. NOTE this only works on CPython
234    # probably.
235    # TODO(b/136468453): Remove need for __del__ ordering needs of CPython
236    # by using explicit closes(). See implementation of Interpreter __del__.
237    self._interpreter = None
238    self._delegates = None
239
240  def allocate_tensors(self):
241    self._ensure_safe()
242    return self._interpreter.AllocateTensors()
243
244  def _safe_to_run(self):
245    """Returns true if there exist no numpy array buffers.
246
247    This means it is safe to run tflite calls that may destroy internally
248    allocated memory. This works, because in the wrapper.cc we have made
249    the numpy base be the self._interpreter.
250    """
251    # NOTE, our tensor() call in cpp will use _interpreter as a base pointer.
252    # If this environment is the only _interpreter, then the ref count should be
253    # 2 (1 in self and 1 in temporary of sys.getrefcount).
254    return sys.getrefcount(self._interpreter) == 2
255
256  def _ensure_safe(self):
257    """Makes sure no numpy arrays pointing to internal buffers are active.
258
259    This should be called from any function that will call a function on
260    _interpreter that may reallocate memory e.g. invoke(), ...
261
262    Raises:
263      RuntimeError: If there exist numpy objects pointing to internal memory
264        then we throw.
265    """
266    if not self._safe_to_run():
267      raise RuntimeError("""There is at least 1 reference to internal data
268      in the interpreter in the form of a numpy array or slice. Be sure to
269      only hold the function returned from tensor() if you are using raw
270      data access.""")
271
272  # Experimental and subject to change
273  def _get_op_details(self, op_index):
274    """Gets a dictionary with arrays of ids for tensors involved with an op.
275
276    Args:
277      op_index: Operation/node index of node to query.
278
279    Returns:
280      a dictionary containing the index, op name, and arrays with lists of the
281      indices for the inputs and outputs of the op/node.
282    """
283    op_index = int(op_index)
284    op_name = self._interpreter.NodeName(op_index)
285    op_inputs = self._interpreter.NodeInputs(op_index)
286    op_outputs = self._interpreter.NodeOutputs(op_index)
287
288    details = {
289        'index': op_index,
290        'op_name': op_name,
291        'inputs': op_inputs,
292        'outputs': op_outputs,
293    }
294
295    return details
296
297  def _get_tensor_details(self, tensor_index):
298    """Gets tensor details.
299
300    Args:
301      tensor_index: Tensor index of tensor to query.
302
303    Returns:
304      A dictionary containing the following fields of the tensor:
305        'name': The tensor name.
306        'index': The tensor index in the interpreter.
307        'shape': The shape of the tensor.
308        'quantization': Deprecated, use 'quantization_parameters'. This field
309            only works for per-tensor quantization, whereas
310            'quantization_parameters' works in all cases.
311        'quantization_parameters': The parameters used to quantize the tensor:
312          'scales': List of scales (one if per-tensor quantization)
313          'zero_points': List of zero_points (one if per-tensor quantization)
314          'quantized_dimension': Specifies the dimension of per-axis
315              quantization, in the case of multiple scales/zero_points.
316
317    Raises:
318      ValueError: If tensor_index is invalid.
319    """
320    tensor_index = int(tensor_index)
321    tensor_name = self._interpreter.TensorName(tensor_index)
322    tensor_size = self._interpreter.TensorSize(tensor_index)
323    tensor_size_signature = self._interpreter.TensorSizeSignature(tensor_index)
324    tensor_type = self._interpreter.TensorType(tensor_index)
325    tensor_quantization = self._interpreter.TensorQuantization(tensor_index)
326    tensor_quantization_params = self._interpreter.TensorQuantizationParameters(
327        tensor_index)
328
329    if not tensor_name or not tensor_type:
330      raise ValueError('Could not get tensor details')
331
332    details = {
333        'name': tensor_name,
334        'index': tensor_index,
335        'shape': tensor_size,
336        'shape_signature': tensor_size_signature,
337        'dtype': tensor_type,
338        'quantization': tensor_quantization,
339        'quantization_parameters': {
340            'scales': tensor_quantization_params[0],
341            'zero_points': tensor_quantization_params[1],
342            'quantized_dimension': tensor_quantization_params[2],
343        }
344    }
345
346    return details
347
348  # Experimental and subject to change
349  def _get_ops_details(self):
350    """Gets op details for every node.
351
352    Returns:
353      A list of dictionaries containing arrays with lists of tensor ids for
354      tensors involved in the op.
355    """
356    return [
357        self._get_op_details(idx) for idx in range(self._interpreter.NumNodes())
358    ]
359
360  def get_tensor_details(self):
361    """Gets tensor details for every tensor with valid tensor details.
362
363    Tensors where required information about the tensor is not found are not
364    added to the list. This includes temporary tensors without a name.
365
366    Returns:
367      A list of dictionaries containing tensor information.
368    """
369    tensor_details = []
370    for idx in range(self._interpreter.NumTensors()):
371      try:
372        tensor_details.append(self._get_tensor_details(idx))
373      except ValueError:
374        pass
375    return tensor_details
376
377  def get_input_details(self):
378    """Gets model input details.
379
380    Returns:
381      A list of input details.
382    """
383    return [
384        self._get_tensor_details(i) for i in self._interpreter.InputIndices()
385    ]
386
387  def set_tensor(self, tensor_index, value):
388    """Sets the value of the input tensor. Note this copies data in `value`.
389
390    If you want to avoid copying, you can use the `tensor()` function to get a
391    numpy buffer pointing to the input buffer in the tflite interpreter.
392
393    Args:
394      tensor_index: Tensor index of tensor to set. This value can be gotten from
395                    the 'index' field in get_input_details.
396      value: Value of tensor to set.
397
398    Raises:
399      ValueError: If the interpreter could not set the tensor.
400    """
401    self._interpreter.SetTensor(tensor_index, value)
402
403  def resize_tensor_input(self, input_index, tensor_size):
404    """Resizes an input tensor.
405
406    Args:
407      input_index: Tensor index of input to set. This value can be gotten from
408                   the 'index' field in get_input_details.
409      tensor_size: The tensor_shape to resize the input to.
410
411    Raises:
412      ValueError: If the interpreter could not resize the input tensor.
413    """
414    self._ensure_safe()
415    # `ResizeInputTensor` now only accepts int32 numpy array as `tensor_size
416    # parameter.
417    tensor_size = np.array(tensor_size, dtype=np.int32)
418    self._interpreter.ResizeInputTensor(input_index, tensor_size)
419
420  def get_output_details(self):
421    """Gets model output details.
422
423    Returns:
424      A list of output details.
425    """
426    return [
427        self._get_tensor_details(i) for i in self._interpreter.OutputIndices()
428    ]
429
430  def get_tensor(self, tensor_index):
431    """Gets the value of the input tensor (get a copy).
432
433    If you wish to avoid the copy, use `tensor()`. This function cannot be used
434    to read intermediate results.
435
436    Args:
437      tensor_index: Tensor index of tensor to get. This value can be gotten from
438                    the 'index' field in get_output_details.
439
440    Returns:
441      a numpy array.
442    """
443    return self._interpreter.GetTensor(tensor_index)
444
445  def tensor(self, tensor_index):
446    """Returns function that gives a numpy view of the current tensor buffer.
447
448    This allows reading and writing to this tensors w/o copies. This more
449    closely mirrors the C++ Interpreter class interface's tensor() member, hence
450    the name. Be careful to not hold these output references through calls
451    to `allocate_tensors()` and `invoke()`. This function cannot be used to read
452    intermediate results.
453
454    Usage:
455
456    ```
457    interpreter.allocate_tensors()
458    input = interpreter.tensor(interpreter.get_input_details()[0]["index"])
459    output = interpreter.tensor(interpreter.get_output_details()[0]["index"])
460    for i in range(10):
461      input().fill(3.)
462      interpreter.invoke()
463      print("inference %s" % output())
464    ```
465
466    Notice how this function avoids making a numpy array directly. This is
467    because it is important to not hold actual numpy views to the data longer
468    than necessary. If you do, then the interpreter can no longer be invoked,
469    because it is possible the interpreter would resize and invalidate the
470    referenced tensors. The NumPy API doesn't allow any mutability of the
471    the underlying buffers.
472
473    WRONG:
474
475    ```
476    input = interpreter.tensor(interpreter.get_input_details()[0]["index"])()
477    output = interpreter.tensor(interpreter.get_output_details()[0]["index"])()
478    interpreter.allocate_tensors()  # This will throw RuntimeError
479    for i in range(10):
480      input.fill(3.)
481      interpreter.invoke()  # this will throw RuntimeError since input,output
482    ```
483
484    Args:
485      tensor_index: Tensor index of tensor to get. This value can be gotten from
486                    the 'index' field in get_output_details.
487
488    Returns:
489      A function that can return a new numpy array pointing to the internal
490      TFLite tensor state at any point. It is safe to hold the function forever,
491      but it is not safe to hold the numpy array forever.
492    """
493    return lambda: self._interpreter.tensor(self._interpreter, tensor_index)
494
495  def invoke(self):
496    """Invoke the interpreter.
497
498    Be sure to set the input sizes, allocate tensors and fill values before
499    calling this. Also, note that this function releases the GIL so heavy
500    computation can be done in the background while the Python interpreter
501    continues. No other function on this object should be called while the
502    invoke() call has not finished.
503
504    Raises:
505      ValueError: When the underlying interpreter fails raise ValueError.
506    """
507    self._ensure_safe()
508    self._interpreter.Invoke()
509
510  def reset_all_variables(self):
511    return self._interpreter.ResetVariableTensors()
512
513
514class InterpreterWithCustomOps(Interpreter):
515  """Interpreter interface for TensorFlow Lite Models that accepts custom ops.
516
517  The interface provided by this class is experimenal and therefore not exposed
518  as part of the public API.
519
520  Wraps the tf.lite.Interpreter class and adds the ability to load custom ops
521  by providing the names of functions that take a pointer to a BuiltinOpResolver
522  and add a custom op.
523  """
524
525  def __init__(self,
526               model_path=None,
527               model_content=None,
528               experimental_delegates=None,
529               custom_op_registerers=None):
530    """Constructor.
531
532    Args:
533      model_path: Path to TF-Lite Flatbuffer file.
534      model_content: Content of model.
535      experimental_delegates: Experimental. Subject to change. List of
536        [TfLiteDelegate](https://www.tensorflow.org/lite/performance/delegates)
537          objects returned by lite.load_delegate().
538      custom_op_registerers: List of str, symbol names of functions that take a
539        pointer to a MutableOpResolver and register a custom op.
540
541    Raises:
542      ValueError: If the interpreter was unable to create.
543    """
544    self._custom_op_registerers = custom_op_registerers
545    super(InterpreterWithCustomOps, self).__init__(
546        model_path=model_path,
547        model_content=model_content,
548        experimental_delegates=experimental_delegates)
549