• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 // This file defines common C types and APIs for implementing operations,
17 // delegates and other constructs in TensorFlow Lite. The actual operations and
18 // delegates can be defined using C++, but the interface between the interpreter
19 // and the operations are C.
20 //
21 // Summary of abstractions
22 // TF_LITE_ENSURE - Self-sufficient error checking
23 // TfLiteStatus - Status reporting
24 // TfLiteIntArray - stores tensor shapes (dims),
25 // TfLiteContext - allows an op to access the tensors
26 // TfLiteTensor - tensor (a multidimensional array)
27 // TfLiteNode - a single node or operation
28 // TfLiteRegistration - the implementation of a conceptual operation.
29 // TfLiteDelegate - allows delegation of nodes to alternative backends.
30 //
31 // Some abstractions in this file are created and managed by Interpreter.
32 //
33 // NOTE: The order of values in these structs are "semi-ABI stable". New values
34 // should be added only to the end of structs and never reordered.
35 
36 #ifndef TENSORFLOW_LITE_C_COMMON_H_
37 #define TENSORFLOW_LITE_C_COMMON_H_
38 
39 #include <stdbool.h>
40 #include <stddef.h>
41 #include <stdint.h>
42 
43 #include "tensorflow/lite/c/c_api_types.h"  // IWYU pragma: export
44 
45 #ifdef __cplusplus
46 extern "C" {
47 #endif  // __cplusplus
48 
49 // The list of external context types known to TF Lite. This list exists solely
50 // to avoid conflicts and to ensure ops can share the external contexts they
51 // need. Access to the external contexts is controlled by one of the
52 // corresponding support files.
53 typedef enum TfLiteExternalContextType {
54   kTfLiteEigenContext = 0,       // include eigen_support.h to use.
55   kTfLiteGemmLowpContext = 1,    // include gemm_support.h to use.
56   kTfLiteEdgeTpuContext = 2,     // Placeholder for Edge TPU support.
57   kTfLiteCpuBackendContext = 3,  // include cpu_backend_context.h to use.
58   kTfLiteMaxExternalContexts = 4
59 } TfLiteExternalContextType;
60 
61 // Forward declare so dependent structs and methods can reference these types
62 // prior to the struct definitions.
63 struct TfLiteContext;
64 struct TfLiteDelegate;
65 struct TfLiteRegistration;
66 
67 // An external context is a collection of information unrelated to the TF Lite
68 // framework, but useful to a subset of the ops. TF Lite knows very little
69 // about the actual contexts, but it keeps a list of them, and is able to
70 // refresh them if configurations like the number of recommended threads
71 // change.
72 typedef struct TfLiteExternalContext {
73   TfLiteExternalContextType type;
74   TfLiteStatus (*Refresh)(struct TfLiteContext* context);
75 } TfLiteExternalContext;
76 
77 #define kTfLiteOptionalTensor (-1)
78 
79 // Fixed size list of integers. Used for dimensions and inputs/outputs tensor
80 // indices
81 typedef struct TfLiteIntArray {
82   int size;
83 // gcc 6.1+ have a bug where flexible members aren't properly handled
84 // https://github.com/google/re2/commit/b94b7cd42e9f02673cd748c1ac1d16db4052514c
85 #if (!defined(__clang__) && defined(__GNUC__) && __GNUC__ == 6 && \
86      __GNUC_MINOR__ >= 1) ||                                      \
87     defined(HEXAGON) ||                                           \
88     (defined(__clang__) && __clang_major__ == 7 && __clang_minor__ == 1)
89   int data[0];
90 #else
91   int data[];
92 #endif
93 } TfLiteIntArray;
94 
95 // Given the size (number of elements) in a TfLiteIntArray, calculate its size
96 // in bytes.
97 int TfLiteIntArrayGetSizeInBytes(int size);
98 
99 #ifndef TF_LITE_STATIC_MEMORY
100 // Create a array of a given `size` (uninitialized entries).
101 // This returns a pointer, that you must free using TfLiteIntArrayFree().
102 TfLiteIntArray* TfLiteIntArrayCreate(int size);
103 #endif
104 
105 // Check if two intarrays are equal. Returns 1 if they are equal, 0 otherwise.
106 int TfLiteIntArrayEqual(const TfLiteIntArray* a, const TfLiteIntArray* b);
107 
108 // Check if an intarray equals an array. Returns 1 if equals, 0 otherwise.
109 int TfLiteIntArrayEqualsArray(const TfLiteIntArray* a, int b_size,
110                               const int b_data[]);
111 
112 #ifndef TF_LITE_STATIC_MEMORY
113 // Create a copy of an array passed as `src`.
114 // You are expected to free memory with TfLiteIntArrayFree
115 TfLiteIntArray* TfLiteIntArrayCopy(const TfLiteIntArray* src);
116 
117 // Free memory of array `a`.
118 void TfLiteIntArrayFree(TfLiteIntArray* a);
119 #endif  // TF_LITE_STATIC_MEMORY
120 
121 // Fixed size list of floats. Used for per-channel quantization.
122 typedef struct TfLiteFloatArray {
123   int size;
124 // gcc 6.1+ have a bug where flexible members aren't properly handled
125 // https://github.com/google/re2/commit/b94b7cd42e9f02673cd748c1ac1d16db4052514c
126 // This also applies to the toolchain used for Qualcomm Hexagon DSPs.
127 #if !defined(__clang__) && defined(__GNUC__) && __GNUC__ == 6 && \
128     __GNUC_MINOR__ >= 1
129   float data[0];
130 #else
131   float data[];
132 #endif
133 } TfLiteFloatArray;
134 
135 // Given the size (number of elements) in a TfLiteFloatArray, calculate its size
136 // in bytes.
137 int TfLiteFloatArrayGetSizeInBytes(int size);
138 
139 #ifndef TF_LITE_STATIC_MEMORY
140 // Create a array of a given `size` (uninitialized entries).
141 // This returns a pointer, that you must free using TfLiteFloatArrayFree().
142 TfLiteFloatArray* TfLiteFloatArrayCreate(int size);
143 
144 // Free memory of array `a`.
145 void TfLiteFloatArrayFree(TfLiteFloatArray* a);
146 #endif  // TF_LITE_STATIC_MEMORY
147 
148 // Since we must not depend on any libraries, define a minimal subset of
149 // error macros while avoiding names that have pre-conceived meanings like
150 // assert and check.
151 
152 // Try to make all reporting calls through TF_LITE_KERNEL_LOG rather than
153 // calling the context->ReportError function directly, so that message strings
154 // can be stripped out if the binary size needs to be severely optimized.
155 #ifndef TF_LITE_STRIP_ERROR_STRINGS
156 #define TF_LITE_KERNEL_LOG(context, ...)            \
157   do {                                              \
158     (context)->ReportError((context), __VA_ARGS__); \
159   } while (false)
160 
161 #define TF_LITE_MAYBE_KERNEL_LOG(context, ...)        \
162   do {                                                \
163     if ((context) != nullptr) {                       \
164       (context)->ReportError((context), __VA_ARGS__); \
165     }                                                 \
166   } while (false)
167 #else  // TF_LITE_STRIP_ERROR_STRINGS
168 #define TF_LITE_KERNEL_LOG(context, ...)
169 #define TF_LITE_MAYBE_KERNEL_LOG(context, ...)
170 #endif  // TF_LITE_STRIP_ERROR_STRINGS
171 
172 // Check whether value is true, and if not return kTfLiteError from
173 // the current function (and report the error string msg).
174 #define TF_LITE_ENSURE_MSG(context, value, msg)        \
175   do {                                                 \
176     if (!(value)) {                                    \
177       TF_LITE_KERNEL_LOG((context), __FILE__ " " msg); \
178       return kTfLiteError;                             \
179     }                                                  \
180   } while (0)
181 
182 // Check whether the value `a` is true, and if not return kTfLiteError from
183 // the current function, while also reporting the location of the error.
184 #define TF_LITE_ENSURE(context, a)                                      \
185   do {                                                                  \
186     if (!(a)) {                                                         \
187       TF_LITE_KERNEL_LOG((context), "%s:%d %s was not true.", __FILE__, \
188                          __LINE__, #a);                                 \
189       return kTfLiteError;                                              \
190     }                                                                   \
191   } while (0)
192 
193 #define TF_LITE_ENSURE_STATUS(a) \
194   do {                           \
195     const TfLiteStatus s = (a);  \
196     if (s != kTfLiteOk) {        \
197       return s;                  \
198     }                            \
199   } while (0)
200 
201 // Check whether the value `a == b` is true, and if not return kTfLiteError from
202 // the current function, while also reporting the location of the error.
203 // `a` and `b` may be evaluated more than once, so no side effects or
204 // extremely expensive computations should be done.
205 // NOTE: Use TF_LITE_ENSURE_TYPES_EQ if comparing TfLiteTypes.
206 #define TF_LITE_ENSURE_EQ(context, a, b)                                   \
207   do {                                                                     \
208     if ((a) != (b)) {                                                      \
209       TF_LITE_KERNEL_LOG((context), "%s:%d %s != %s (%d != %d)", __FILE__, \
210                          __LINE__, #a, #b, (a), (b));                      \
211       return kTfLiteError;                                                 \
212     }                                                                      \
213   } while (0)
214 
215 #define TF_LITE_ENSURE_TYPES_EQ(context, a, b)                             \
216   do {                                                                     \
217     if ((a) != (b)) {                                                      \
218       TF_LITE_KERNEL_LOG((context), "%s:%d %s != %s (%s != %s)", __FILE__, \
219                          __LINE__, #a, #b, TfLiteTypeGetName(a),           \
220                          TfLiteTypeGetName(b));                            \
221       return kTfLiteError;                                                 \
222     }                                                                      \
223   } while (0)
224 
225 #define TF_LITE_ENSURE_NEAR(context, a, b, epsilon)                          \
226   do {                                                                       \
227     auto delta = ((a) > (b)) ? ((a) - (b)) : ((b) - (a));                    \
228     if (delta > epsilon) {                                                   \
229       TF_LITE_KERNEL_LOG((context), "%s:%d %s not near %s (%f != %f)",       \
230                          __FILE__, __LINE__, #a, #b, static_cast<double>(a), \
231                          static_cast<double>(b));                            \
232       return kTfLiteError;                                                   \
233     }                                                                        \
234   } while (0)
235 
236 #define TF_LITE_ENSURE_OK(context, status) \
237   do {                                     \
238     const TfLiteStatus s = (status);       \
239     if ((s) != kTfLiteOk) {                \
240       return s;                            \
241     }                                      \
242   } while (0)
243 
244 // Single-precision complex data type compatible with the C99 definition.
245 typedef struct TfLiteComplex64 {
246   float re, im;  // real and imaginary parts, respectively.
247 } TfLiteComplex64;
248 
249 // Double-precision complex data type compatible with the C99 definition.
250 typedef struct TfLiteComplex128 {
251   double re, im;  // real and imaginary parts, respectively.
252 } TfLiteComplex128;
253 
254 // Half precision data type compatible with the C99 definition.
255 typedef struct TfLiteFloat16 {
256   uint16_t data;
257 } TfLiteFloat16;
258 
259 // Return the name of a given type, for error reporting purposes.
260 const char* TfLiteTypeGetName(TfLiteType type);
261 
262 // SupportedQuantizationTypes.
263 typedef enum TfLiteQuantizationType {
264   // No quantization.
265   kTfLiteNoQuantization = 0,
266   // Affine quantization (with support for per-channel quantization).
267   // Corresponds to TfLiteAffineQuantization.
268   kTfLiteAffineQuantization = 1,
269 } TfLiteQuantizationType;
270 
271 // Structure specifying the quantization used by the tensor, if-any.
272 typedef struct TfLiteQuantization {
273   // The type of quantization held by params.
274   TfLiteQuantizationType type;
275   // Holds an optional reference to a quantization param structure. The actual
276   // type depends on the value of the `type` field (see the comment there for
277   // the values and corresponding types).
278   void* params;
279 } TfLiteQuantization;
280 
281 // Parameters for asymmetric quantization across a dimension (i.e per output
282 // channel quantization).
283 // quantized_dimension specifies which dimension the scales and zero_points
284 // correspond to.
285 // For a particular value in quantized_dimension, quantized values can be
286 // converted back to float using:
287 //     real_value = scale * (quantized_value - zero_point)
288 typedef struct TfLiteAffineQuantization {
289   TfLiteFloatArray* scale;
290   TfLiteIntArray* zero_point;
291   int32_t quantized_dimension;
292 } TfLiteAffineQuantization;
293 
294 /* A union of pointers that points to memory for a given tensor. */
295 typedef union TfLitePtrUnion {
296   /* Do not access these members directly, if possible, use
297    * GetTensorData<TYPE>(tensor) instead, otherwise only access .data, as other
298    * members are deprecated. */
299   int32_t* i32;
300   uint32_t* u32;
301   int64_t* i64;
302   uint64_t* u64;
303   float* f;
304   TfLiteFloat16* f16;
305   double* f64;
306   char* raw;
307   const char* raw_const;
308   uint8_t* uint8;
309   bool* b;
310   int16_t* i16;
311   TfLiteComplex64* c64;
312   TfLiteComplex128* c128;
313   int8_t* int8;
314   /* Only use this member. */
315   void* data;
316 } TfLitePtrUnion;
317 
318 // Memory allocation strategies.
319 //  * kTfLiteMmapRo: Read-only memory-mapped data, or data externally allocated.
320 //  * kTfLiteArenaRw: Arena allocated with no guarantees about persistence,
321 //        and available during eval.
322 //  * kTfLiteArenaRwPersistent: Arena allocated but persistent across eval, and
323 //        only available during eval.
324 //  * kTfLiteDynamic: Allocated during eval, or for string tensors.
325 //  * kTfLitePersistentRo: Allocated and populated during prepare. This is
326 //        useful for tensors that can be computed during prepare and treated
327 //        as constant inputs for downstream ops (also in prepare).
328 //  * kTfLiteCustom: Custom memory allocation provided by the user. See
329 //        TfLiteCustomAllocation below.
330 typedef enum TfLiteAllocationType {
331   kTfLiteMemNone = 0,
332   kTfLiteMmapRo,
333   kTfLiteArenaRw,
334   kTfLiteArenaRwPersistent,
335   kTfLiteDynamic,
336   kTfLitePersistentRo,
337   kTfLiteCustom,
338 } TfLiteAllocationType;
339 
340 // The delegates should use zero or positive integers to represent handles.
341 // -1 is reserved from unallocated status.
342 typedef int TfLiteBufferHandle;
343 enum {
344   kTfLiteNullBufferHandle = -1,
345 };
346 
347 // Storage format of each dimension in a sparse tensor.
348 typedef enum TfLiteDimensionType {
349   kTfLiteDimDense = 0,
350   kTfLiteDimSparseCSR,
351 } TfLiteDimensionType;
352 
353 // Metadata to encode each dimension in a sparse tensor.
354 typedef struct TfLiteDimensionMetadata {
355   TfLiteDimensionType format;
356   int dense_size;
357   TfLiteIntArray* array_segments;
358   TfLiteIntArray* array_indices;
359 } TfLiteDimensionMetadata;
360 
361 // Parameters used to encode a sparse tensor. For detailed explanation of each
362 // field please refer to lite/schema/schema.fbs.
363 typedef struct TfLiteSparsity {
364   TfLiteIntArray* traversal_order;
365   TfLiteIntArray* block_map;
366   TfLiteDimensionMetadata* dim_metadata;
367   int dim_metadata_size;
368 } TfLiteSparsity;
369 
370 // Defines a custom memory allocation not owned by the runtime.
371 // `data` should be aligned to kDefaultTensorAlignment defined in
372 // lite/util.h. (Currently 64 bytes)
373 // NOTE: See Interpreter.SetCustomAllocationForTensor for details on usage.
374 typedef struct TfLiteCustomAllocation {
375   void* data;
376   size_t bytes;
377 } TfLiteCustomAllocation;
378 
379 // The flags used in `Interpreter::SetCustomAllocationForTensor`.
380 // Note that this is a bitmask, so the values should be 1, 2, 4, 8, ...etc.
381 typedef enum TfLiteCustomAllocationFlags {
382   kTfLiteCustomAllocationFlagsNone = 0,
383   // Skips checking whether allocation.data points to an aligned buffer as
384   // expected by the TFLite runtime.
385   // NOTE: Setting this flag can cause crashes when calling Invoke().
386   // Use with caution.
387   kTfLiteCustomAllocationFlagsSkipAlignCheck = 1,
388 } TfLiteCustomAllocationFlags;
389 
390 // A tensor in the interpreter system which is a wrapper around a buffer of
391 // data including a dimensionality (or NULL if not currently defined).
392 #ifndef TF_LITE_STATIC_MEMORY
393 typedef struct TfLiteTensor {
394   // The data type specification for data stored in `data`. This affects
395   // what member of `data` union should be used.
396   TfLiteType type;
397   // A union of data pointers. The appropriate type should be used for a typed
398   // tensor based on `type`.
399   TfLitePtrUnion data;
400   // A pointer to a structure representing the dimensionality interpretation
401   // that the buffer should have. NOTE: the product of elements of `dims`
402   // and the element datatype size should be equal to `bytes` below.
403   TfLiteIntArray* dims;
404   // Quantization information.
405   TfLiteQuantizationParams params;
406   // How memory is mapped
407   //  kTfLiteMmapRo: Memory mapped read only.
408   //  i.e. weights
409   //  kTfLiteArenaRw: Arena allocated read write memory
410   //  (i.e. temporaries, outputs).
411   TfLiteAllocationType allocation_type;
412   // The number of bytes required to store the data of this Tensor. I.e.
413   // (bytes of each element) * dims[0] * ... * dims[n-1].  For example, if
414   // type is kTfLiteFloat32 and dims = {3, 2} then
415   // bytes = sizeof(float) * 3 * 2 = 4 * 3 * 2 = 24.
416   size_t bytes;
417 
418   // An opaque pointer to a tflite::MMapAllocation
419   const void* allocation;
420 
421   // Null-terminated name of this tensor.
422   const char* name;
423 
424   // The delegate which knows how to handle `buffer_handle`.
425   // WARNING: This is an experimental interface that is subject to change.
426   struct TfLiteDelegate* delegate;
427 
428   // An integer buffer handle that can be handled by `delegate`.
429   // The value is valid only when delegate is not null.
430   // WARNING: This is an experimental interface that is subject to change.
431   TfLiteBufferHandle buffer_handle;
432 
433   // If the delegate uses its own buffer (e.g. GPU memory), the delegate is
434   // responsible to set data_is_stale to true.
435   // `delegate->CopyFromBufferHandle` can be called to copy the data from
436   // delegate buffer.
437   // WARNING: This is an // experimental interface that is subject to change.
438   bool data_is_stale;
439 
440   // True if the tensor is a variable.
441   bool is_variable;
442 
443   // Quantization information. Replaces params field above.
444   TfLiteQuantization quantization;
445 
446   // Parameters used to encode a sparse tensor.
447   // This is optional. The field is NULL if a tensor is dense.
448   // WARNING: This is an experimental interface that is subject to change.
449   TfLiteSparsity* sparsity;
450 
451   // Optional. Encodes shapes with unknown dimensions with -1. This field is
452   // only populated when unknown dimensions exist in a read-write tensor (i.e.
453   // an input or output tensor). (e.g.  `dims` contains [1, 1, 1, 3] and
454   // `dims_signature` contains [1, -1, -1, 3]).
455   const TfLiteIntArray* dims_signature;
456 } TfLiteTensor;
457 
458 // A structure representing an instance of a node.
459 // This structure only exhibits the inputs, outputs, user defined data and some
460 // node properties (like statefulness), not other features like the type.
461 typedef struct TfLiteNode {
462   // Inputs to this node expressed as indices into the simulator's tensors.
463   TfLiteIntArray* inputs;
464 
465   // Outputs to this node expressed as indices into the simulator's tensors.
466   TfLiteIntArray* outputs;
467 
468   // intermediate tensors to this node expressed as indices into the simulator's
469   // tensors.
470   TfLiteIntArray* intermediates;
471 
472   // Temporary tensors uses during the computations. This usually contains no
473   // tensors, but ops are allowed to change that if they need scratch space of
474   // any sort.
475   TfLiteIntArray* temporaries;
476 
477   // Opaque data provided by the node implementer through `Registration.init`.
478   void* user_data;
479 
480   // Opaque data provided to the node if the node is a builtin. This is usually
481   // a structure defined in builtin_op_data.h
482   void* builtin_data;
483 
484   // Custom initial data. This is the opaque data provided in the flatbuffer.
485   // WARNING: This is an experimental interface that is subject to change.
486   const void* custom_initial_data;
487   int custom_initial_data_size;
488 
489   // The pointer to the delegate. This is non-null only when the node is
490   // created by calling `interpreter.ModifyGraphWithDelegate`.
491   // WARNING: This is an experimental interface that is subject to change.
492   struct TfLiteDelegate* delegate;
493 
494   // Whether this op might have side effect (e.g. stateful op).
495   bool might_have_side_effect;
496 } TfLiteNode;
497 #else   // defined(TF_LITE_STATIC_MEMORY)?
498 // NOTE: This flag is opt-in only at compile time.
499 //
500 // Specific reduced TfLiteTensor struct for TF Micro runtime. This struct
501 // contains only the minimum fields required to initialize and prepare a micro
502 // inference graph. The fields in this struct have been ordered from
503 // largest-to-smallest for optimal struct sizeof.
504 //
505 // This struct does not use:
506 // - allocation
507 // - buffer_handle
508 // - data_is_stale
509 // - delegate
510 // - dims_signature
511 // - name
512 // - sparsity
513 typedef struct TfLiteTensor {
514   // TODO(b/155784997): Consider consolidating these quantization fields:
515   // Quantization information. Replaces params field above.
516   TfLiteQuantization quantization;
517 
518   // Quantization information.
519   TfLiteQuantizationParams params;
520 
521   // A union of data pointers. The appropriate type should be used for a typed
522   // tensor based on `type`.
523   TfLitePtrUnion data;
524 
525   // A pointer to a structure representing the dimensionality interpretation
526   // that the buffer should have. NOTE: the product of elements of `dims`
527   // and the element datatype size should be equal to `bytes` below.
528   TfLiteIntArray* dims;
529 
530   // The number of bytes required to store the data of this Tensor. I.e.
531   // (bytes of each element) * dims[0] * ... * dims[n-1].  For example, if
532   // type is kTfLiteFloat32 and dims = {3, 2} then
533   // bytes = sizeof(float) * 3 * 2 = 4 * 3 * 2 = 24.
534   size_t bytes;
535 
536   // The data type specification for data stored in `data`. This affects
537   // what member of `data` union should be used.
538   TfLiteType type;
539 
540   // How memory is mapped
541   //  kTfLiteMmapRo: Memory mapped read only.
542   //  i.e. weights
543   //  kTfLiteArenaRw: Arena allocated read write memory
544   //  (i.e. temporaries, outputs).
545   TfLiteAllocationType allocation_type;
546 
547   // True if the tensor is a variable.
548   bool is_variable;
549 } TfLiteTensor;
550 
551 // Specific reduced TfLiteNode struct for TF Micro runtime. This struct contains
552 // only the minimum fields required to represent a node.
553 //
554 // This struct does not use:
555 // - delegate
556 // - intermediates
557 // - temporaries
558 typedef struct TfLiteNode {
559   // Inputs to this node expressed as indices into the simulator's tensors.
560   TfLiteIntArray* inputs;
561 
562   // Outputs to this node expressed as indices into the simulator's tensors.
563   TfLiteIntArray* outputs;
564 
565   // intermediate tensors to this node expressed as indices into the simulator's
566   // tensors.
567   TfLiteIntArray* intermediates;
568 
569   // Opaque data provided by the node implementer through `Registration.init`.
570   void* user_data;
571 
572   // Opaque data provided to the node if the node is a builtin. This is usually
573   // a structure defined in builtin_op_data.h
574   void* builtin_data;
575 
576   // Custom initial data. This is the opaque data provided in the flatbuffer.
577   // WARNING: This is an experimental interface that is subject to change.
578   const void* custom_initial_data;
579   int custom_initial_data_size;
580 } TfLiteNode;
581 #endif  // TF_LITE_STATIC_MEMORY
582 
583 // Light-weight tensor struct for TF Micro runtime. Provides the minimal amount
584 // of information required for a kernel to run during TfLiteRegistration::Eval.
585 // TODO(b/160955687): Move this field into TF_LITE_STATIC_MEMORY when TFLM
586 // builds with this flag by default internally.
587 typedef struct TfLiteEvalTensor {
588   // A union of data pointers. The appropriate type should be used for a typed
589   // tensor based on `type`.
590   TfLitePtrUnion data;
591 
592   // A pointer to a structure representing the dimensionality interpretation
593   // that the buffer should have.
594   TfLiteIntArray* dims;
595 
596   // The data type specification for data stored in `data`. This affects
597   // what member of `data` union should be used.
598   TfLiteType type;
599 } TfLiteEvalTensor;
600 
601 #ifndef TF_LITE_STATIC_MEMORY
602 // Free data memory of tensor `t`.
603 void TfLiteTensorDataFree(TfLiteTensor* t);
604 
605 // Free quantization data.
606 void TfLiteQuantizationFree(TfLiteQuantization* quantization);
607 
608 // Free sparsity parameters.
609 void TfLiteSparsityFree(TfLiteSparsity* sparsity);
610 
611 // Free memory of tensor `t`.
612 void TfLiteTensorFree(TfLiteTensor* t);
613 
614 // Set all of a tensor's fields (and free any previously allocated data).
615 void TfLiteTensorReset(TfLiteType type, const char* name, TfLiteIntArray* dims,
616                        TfLiteQuantizationParams quantization, char* buffer,
617                        size_t size, TfLiteAllocationType allocation_type,
618                        const void* allocation, bool is_variable,
619                        TfLiteTensor* tensor);
620 
621 // Resize the allocated data of a (dynamic) tensor. Tensors with allocation
622 // types other than kTfLiteDynamic will be ignored.
623 void TfLiteTensorRealloc(size_t num_bytes, TfLiteTensor* tensor);
624 #endif  // TF_LITE_STATIC_MEMORY
625 
626 // WARNING: This is an experimental interface that is subject to change.
627 //
628 // Currently, TfLiteDelegateParams has to be allocated in a way that it's
629 // trivially destructable. It will be stored as `builtin_data` field in
630 // `TfLiteNode` of the delegate node.
631 //
632 // See also the `CreateDelegateParams` function in `interpreter.cc` details.
633 typedef struct TfLiteDelegateParams {
634   struct TfLiteDelegate* delegate;
635   TfLiteIntArray* nodes_to_replace;
636   TfLiteIntArray* input_tensors;
637   TfLiteIntArray* output_tensors;
638 } TfLiteDelegateParams;
639 
640 typedef struct TfLiteContext {
641   // Number of tensors in the context.
642   size_t tensors_size;
643 
644   // The execution plan contains a list of the node indices in execution
645   // order. execution_plan->size is the current number of nodes. And,
646   // execution_plan->data[0] is the first node that needs to be run.
647   // TfLiteDelegates can traverse the current execution plan by iterating
648   // through each member of this array and using GetNodeAndRegistration() to
649   // access details about a node. i.e.
650   //
651   // TfLiteIntArray* execution_plan;
652   // TF_LITE_ENSURE_STATUS(context->GetExecutionPlan(context, &execution_plan));
653   // for (int exec_index = 0; exec_index < execution_plan->size; exec_index++) {
654   //    int node_index = execution_plan->data[exec_index];
655   //    TfLiteNode* node;
656   //    TfLiteRegistration* reg;
657   //    context->GetNodeAndRegistration(context, node_index, &node, &reg);
658   // }
659   // Note: the memory pointed by '`*execution_plan` is OWNED by TfLite runtime.
660   // Future calls to GetExecutionPlan invalidates earlier outputs. The following
661   // code snippet shows the issue of such an invocation pattern. After calling
662   // CheckNode, subsequent access to `plan_1st` is undefined.
663   //
664   // void CheckNode(const TfLiteNode* node) {
665   //   ...
666   //   TfLiteIntArray* plan_2nd;
667   //   TF_LITE_ENSURE_STATUS(context->GetExecutionPlan(context, &plan_2nd));
668   //   ...
669   // }
670   //
671   // TfLiteIntArray* plan_1st;
672   // TF_LITE_ENSURE_STATUS(context->GetExecutionPlan(context, &plan_1st));
673   // for (int exec_index = 0; exec_index < plan_1st->size; exec_index++) {
674   //    int node_index = plan_1st->data[exec_index];
675   //    TfLiteNode* node;
676   //    TfLiteRegistration* reg;
677   //    context->GetNodeAndRegistration(context, node_index, &node, &reg);
678   //    CheckNode(node);
679   // }
680   //
681   // WARNING: This is an experimental interface that is subject to change.
682   TfLiteStatus (*GetExecutionPlan)(struct TfLiteContext* context,
683                                    TfLiteIntArray** execution_plan);
684 
685   // An array of tensors in the interpreter context (of length `tensors_size`)
686   TfLiteTensor* tensors;
687 
688   // opaque full context ptr (an opaque c++ data structure)
689   void* impl_;
690 
691   // Request memory pointer be resized. Updates dimensions on the tensor.
692   // NOTE: ResizeTensor takes ownership of newSize.
693   TfLiteStatus (*ResizeTensor)(struct TfLiteContext*, TfLiteTensor* tensor,
694                                TfLiteIntArray* new_size);
695   // Request that an error be reported with format string msg.
696   void (*ReportError)(struct TfLiteContext*, const char* msg, ...);
697 
698   // Add `tensors_to_add` tensors, preserving pre-existing Tensor entries.  If
699   // non-null, the value pointed to by `first_new_tensor_index` will be set to
700   // the index of the first new tensor.
701   TfLiteStatus (*AddTensors)(struct TfLiteContext*, int tensors_to_add,
702                              int* first_new_tensor_index);
703 
704   // Get a Tensor node by node_index.
705   // WARNING: This is an experimental interface that is subject to change.
706   TfLiteStatus (*GetNodeAndRegistration)(
707       struct TfLiteContext*, int node_index, TfLiteNode** node,
708       struct TfLiteRegistration** registration);
709 
710   // Replace ops with one or more stub delegate operations. This function
711   // does not take ownership of `nodes_to_replace`.
712   TfLiteStatus (*ReplaceNodeSubsetsWithDelegateKernels)(
713       struct TfLiteContext*, struct TfLiteRegistration registration,
714       const TfLiteIntArray* nodes_to_replace, struct TfLiteDelegate* delegate);
715 
716   // Number of threads that are recommended to subsystems like gemmlowp and
717   // eigen.
718   int recommended_num_threads;
719 
720   // Access external contexts by type.
721   // WARNING: This is an experimental interface that is subject to change.
722   TfLiteExternalContext* (*GetExternalContext)(struct TfLiteContext*,
723                                                TfLiteExternalContextType);
724   // Set the value of a external context. Does not take ownership of the
725   // pointer.
726   // WARNING: This is an experimental interface that is subject to change.
727   void (*SetExternalContext)(struct TfLiteContext*, TfLiteExternalContextType,
728                              TfLiteExternalContext*);
729 
730   // Flag for allowing float16 precision for FP32 calculation.
731   // default: false.
732   // WARNING: This is an experimental API and subject to change.
733   bool allow_fp32_relax_to_fp16;
734 
735   // Pointer to the op-level profiler, if set; nullptr otherwise.
736   void* profiler;
737 
738   // Allocate persistent buffer which has the same life time as the interpreter.
739   // Returns nullptr on failure.
740   // The memory is allocated from heap for TFL, and from tail in TFLM.
741   // This method is only available in Init or Prepare stage.
742   // WARNING: This is an experimental interface that is subject to change.
743   void* (*AllocatePersistentBuffer)(struct TfLiteContext* ctx, size_t bytes);
744 
745   // Allocate a buffer which will be deallocated right after invoke phase.
746   // The memory is allocated from heap in TFL, and from volatile arena in TFLM.
747   // This method is only available in invoke stage.
748   // NOTE: If possible use RequestScratchBufferInArena method to avoid memory
749   // allocation during inference time.
750   // WARNING: This is an experimental interface that is subject to change.
751   TfLiteStatus (*AllocateBufferForEval)(struct TfLiteContext* ctx, size_t bytes,
752                                         void** ptr);
753 
754   // Request a scratch buffer in the arena through static memory planning.
755   // This method is only available in Prepare stage and the buffer is allocated
756   // by the interpreter between Prepare and Eval stage. In Eval stage,
757   // GetScratchBuffer API can be used to fetch the address.
758   // WARNING: This is an experimental interface that is subject to change.
759   TfLiteStatus (*RequestScratchBufferInArena)(struct TfLiteContext* ctx,
760                                               size_t bytes, int* buffer_idx);
761 
762   // Get the scratch buffer pointer.
763   // This method is only available in Eval stage.
764   // WARNING: This is an experimental interface that is subject to change.
765   void* (*GetScratchBuffer)(struct TfLiteContext* ctx, int buffer_idx);
766 
767   // Resize the memory pointer of the `tensor`. This method behaves the same as
768   // `ResizeTensor`, except that it makes a copy of the shape array internally
769   // so the shape array could be deallocated right afterwards.
770   // WARNING: This is an experimental interface that is subject to change.
771   TfLiteStatus (*ResizeTensorExplicit)(struct TfLiteContext* ctx,
772                                        TfLiteTensor* tensor, int dims,
773                                        const int* shape);
774 
775   // This method provides a preview of post-delegation partitioning. Each
776   // TfLiteDelegateParams in the referenced array corresponds to one instance of
777   // the delegate kernel.
778   // Example usage:
779   //
780   // TfLiteIntArray* nodes_to_replace = ...;
781   // TfLiteDelegateParams* params_array;
782   // int num_partitions = 0;
783   // TF_LITE_ENSURE_STATUS(context->PreviewDelegatePartitioning(
784   //    context, delegate, nodes_to_replace, &params_array, &num_partitions));
785   // for (int idx = 0; idx < num_partitions; idx++) {
786   //    const auto& partition_params = params_array[idx];
787   //    ...
788   // }
789   //
790   // NOTE: The context owns the memory referenced by partition_params_array. It
791   // will be cleared with another call to PreviewDelegateParitioning, or after
792   // TfLiteDelegateParams::Prepare returns.
793   //
794   // WARNING: This is an experimental interface that is subject to change.
795   TfLiteStatus (*PreviewDelegatePartitioning)(
796       struct TfLiteContext* context, const TfLiteIntArray* nodes_to_replace,
797       TfLiteDelegateParams** partition_params_array, int* num_partitions);
798 
799   // Returns a TfLiteTensor struct for a given index.
800   // WARNING: This is an experimental interface that is subject to change.
801   // WARNING: This method may not be available on all platforms.
802   TfLiteTensor* (*GetTensor)(const struct TfLiteContext* context,
803                              int tensor_idx);
804 
805   // Returns a TfLiteEvalTensor struct for a given index.
806   // WARNING: This is an experimental interface that is subject to change.
807   // WARNING: This method may not be available on all platforms.
808   TfLiteEvalTensor* (*GetEvalTensor)(const struct TfLiteContext* context,
809                                      int tensor_idx);
810 
811   // Retrieves named metadata buffer from the TFLite model.
812   // Returns kTfLiteOk if metadata is successfully obtained from the flatbuffer
813   // Model: that is, there exists a `metadata` entry with given `name` string.
814   // (see TFLite's schema.fbs).
815   // The corresponding `buffer` information is populated in `ptr` & `bytes`.
816   // The data from `ptr` is valid for the lifetime of the Interpreter.
817   //
818   // WARNING: This is an experimental interface that is subject to change.
819   TfLiteStatus (*GetModelMetadata)(const struct TfLiteContext* context,
820                                    const char* name, const char** ptr,
821                                    size_t* bytes);
822 } TfLiteContext;
823 
824 typedef struct TfLiteRegistration {
825   // Initializes the op from serialized data.
826   // If a built-in op:
827   //   `buffer` is the op's params data (TfLiteLSTMParams*).
828   //   `length` is zero.
829   // If custom op:
830   //   `buffer` is the op's `custom_options`.
831   //   `length` is the size of the buffer.
832   //
833   // Returns a type-punned (i.e. void*) opaque data (e.g. a primitive pointer
834   // or an instance of a struct).
835   //
836   // The returned pointer will be stored with the node in the `user_data` field,
837   // accessible within prepare and invoke functions below.
838   // NOTE: if the data is already in the desired format, simply implement this
839   // function to return `nullptr` and implement the free function to be a no-op.
840   void* (*init)(TfLiteContext* context, const char* buffer, size_t length);
841 
842   // The pointer `buffer` is the data previously returned by an init invocation.
843   void (*free)(TfLiteContext* context, void* buffer);
844 
845   // prepare is called when the inputs this node depends on have been resized.
846   // context->ResizeTensor() can be called to request output tensors to be
847   // resized.
848   //
849   // Returns kTfLiteOk on success.
850   TfLiteStatus (*prepare)(TfLiteContext* context, TfLiteNode* node);
851 
852   // Execute the node (should read node->inputs and output to node->outputs).
853   // Returns kTfLiteOk on success.
854   TfLiteStatus (*invoke)(TfLiteContext* context, TfLiteNode* node);
855 
856   // profiling_string is called during summarization of profiling information
857   // in order to group executions together. Providing a value here will cause a
858   // given op to appear multiple times is the profiling report. This is
859   // particularly useful for custom ops that can perform significantly
860   // different calculations depending on their `user-data`.
861   const char* (*profiling_string)(const TfLiteContext* context,
862                                   const TfLiteNode* node);
863 
864   // Builtin codes. If this kernel refers to a builtin this is the code
865   // of the builtin. This is so we can do marshaling to other frameworks like
866   // NN API.
867   // Note: It is the responsibility of the registration binder to set this
868   // properly.
869   int32_t builtin_code;
870 
871   // Custom op name. If the op is a builtin, this will be null.
872   // Note: It is the responsibility of the registration binder to set this
873   // properly.
874   // WARNING: This is an experimental interface that is subject to change.
875   const char* custom_name;
876 
877   // The version of the op.
878   // Note: It is the responsibility of the registration binder to set this
879   // properly.
880   int version;
881 } TfLiteRegistration;
882 
883 // The flags used in `TfLiteDelegate`. Note that this is a bitmask, so the
884 // values should be 1, 2, 4, 8, ...etc.
885 typedef enum TfLiteDelegateFlags {
886   kTfLiteDelegateFlagsNone = 0,
887   // The flag is set if the delegate can handle dynamic sized tensors.
888   // For example, the output shape of a `Resize` op with non-constant shape
889   // can only be inferred when the op is invoked.
890   // In this case, the Delegate is responsible for calling
891   // `SetTensorToDynamic` to mark the tensor as a dynamic tensor, and calling
892   // `ResizeTensor` when invoking the op.
893   //
894   // If the delegate isn't capable to handle dynamic tensors, this flag need
895   // to be set to false.
896   kTfLiteDelegateFlagsAllowDynamicTensors = 1,
897 
898   // This flag can be used by delegates (that allow dynamic tensors) to ensure
899   // applicable tensor shapes are automatically propagated in the case of tensor
900   // resizing.
901   // This means that non-dynamic (allocation_type != kTfLiteDynamic) I/O tensors
902   // of a delegate kernel will have correct shapes before its Prepare() method
903   // is called. The runtime leverages TFLite builtin ops in the original
904   // execution plan to propagate shapes.
905   //
906   // A few points to note:
907   // 1. This requires kTfLiteDelegateFlagsAllowDynamicTensors. If that flag is
908   // false, this one is redundant since the delegate kernels are re-initialized
909   // every time tensors are resized.
910   // 2. Enabling this flag adds some overhead to AllocateTensors(), since extra
911   // work is required to prepare the original execution plan.
912   // 3. This flag requires that the original execution plan only have ops with
913   // valid registrations (and not 'dummy' custom ops like with Flex).
914   // WARNING: This feature is experimental and subject to change.
915   kTfLiteDelegateFlagsRequirePropagatedShapes = 2
916 } TfLiteDelegateFlags;
917 
918 // WARNING: This is an experimental interface that is subject to change.
919 typedef struct TfLiteDelegate {
920   // Data that delegate needs to identify itself. This data is owned by the
921   // delegate. The delegate is owned in the user code, so the delegate is
922   // responsible for doing this when it is destroyed.
923   void* data_;
924 
925   // Invoked by ModifyGraphWithDelegate. This prepare is called, giving the
926   // delegate a view of the current graph through TfLiteContext*. It typically
927   // will look at the nodes and call ReplaceNodeSubsetsWithDelegateKernels()
928   // to ask the TensorFlow lite runtime to create macro-nodes to represent
929   // delegated subgraphs of the original graph.
930   TfLiteStatus (*Prepare)(TfLiteContext* context,
931                           struct TfLiteDelegate* delegate);
932 
933   // Copy the data from delegate buffer handle into raw memory of the given
934   // 'tensor'. Note that the delegate is allowed to allocate the raw bytes as
935   // long as it follows the rules for kTfLiteDynamic tensors, in which case this
936   // cannot be null.
937   TfLiteStatus (*CopyFromBufferHandle)(TfLiteContext* context,
938                                        struct TfLiteDelegate* delegate,
939                                        TfLiteBufferHandle buffer_handle,
940                                        TfLiteTensor* tensor);
941 
942   // Copy the data from raw memory of the given 'tensor' to delegate buffer
943   // handle. This can be null if the delegate doesn't use its own buffer.
944   TfLiteStatus (*CopyToBufferHandle)(TfLiteContext* context,
945                                      struct TfLiteDelegate* delegate,
946                                      TfLiteBufferHandle buffer_handle,
947                                      TfLiteTensor* tensor);
948 
949   // Free the Delegate Buffer Handle. Note: This only frees the handle, but
950   // this doesn't release the underlying resource (e.g. textures). The
951   // resources are either owned by application layer or the delegate.
952   // This can be null if the delegate doesn't use its own buffer.
953   void (*FreeBufferHandle)(TfLiteContext* context,
954                            struct TfLiteDelegate* delegate,
955                            TfLiteBufferHandle* handle);
956 
957   // Bitmask flags. See the comments in `TfLiteDelegateFlags`.
958   int64_t flags;
959 } TfLiteDelegate;
960 
961 // Build a 'null' delegate, with all the fields properly set to their default
962 // values.
963 TfLiteDelegate TfLiteDelegateCreate(void);
964 
965 #ifdef __cplusplus
966 }  // extern "C"
967 #endif  // __cplusplus
968 #endif  // TENSORFLOW_LITE_C_COMMON_H_
969