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   // Opaque data provided by the node implementer through `Registration.init`.
566   void* user_data;
567 
568   // Opaque data provided to the node if the node is a builtin. This is usually
569   // a structure defined in builtin_op_data.h
570   void* builtin_data;
571 
572   // Custom initial data. This is the opaque data provided in the flatbuffer.
573   // WARNING: This is an experimental interface that is subject to change.
574   const void* custom_initial_data;
575   int custom_initial_data_size;
576 } TfLiteNode;
577 #endif  // TF_LITE_STATIC_MEMORY
578 
579 // Light-weight tensor struct for TF Micro runtime. Provides the minimal amount
580 // of information required for a kernel to run during TfLiteRegistration::Eval.
581 // TODO(b/160955687): Move this field into TF_LITE_STATIC_MEMORY when TFLM
582 // builds with this flag by default internally.
583 typedef struct TfLiteEvalTensor {
584   // A union of data pointers. The appropriate type should be used for a typed
585   // tensor based on `type`.
586   TfLitePtrUnion data;
587 
588   // A pointer to a structure representing the dimensionality interpretation
589   // that the buffer should have.
590   TfLiteIntArray* dims;
591 
592   // The data type specification for data stored in `data`. This affects
593   // what member of `data` union should be used.
594   TfLiteType type;
595 } TfLiteEvalTensor;
596 
597 #ifndef TF_LITE_STATIC_MEMORY
598 // Free data memory of tensor `t`.
599 void TfLiteTensorDataFree(TfLiteTensor* t);
600 
601 // Free quantization data.
602 void TfLiteQuantizationFree(TfLiteQuantization* quantization);
603 
604 // Free sparsity parameters.
605 void TfLiteSparsityFree(TfLiteSparsity* sparsity);
606 
607 // Free memory of tensor `t`.
608 void TfLiteTensorFree(TfLiteTensor* t);
609 
610 // Set all of a tensor's fields (and free any previously allocated data).
611 void TfLiteTensorReset(TfLiteType type, const char* name, TfLiteIntArray* dims,
612                        TfLiteQuantizationParams quantization, char* buffer,
613                        size_t size, TfLiteAllocationType allocation_type,
614                        const void* allocation, bool is_variable,
615                        TfLiteTensor* tensor);
616 
617 // Resize the allocated data of a (dynamic) tensor. Tensors with allocation
618 // types other than kTfLiteDynamic will be ignored.
619 void TfLiteTensorRealloc(size_t num_bytes, TfLiteTensor* tensor);
620 #endif  // TF_LITE_STATIC_MEMORY
621 
622 // WARNING: This is an experimental interface that is subject to change.
623 //
624 // Currently, TfLiteDelegateParams has to be allocated in a way that it's
625 // trivially destructable. It will be stored as `builtin_data` field in
626 // `TfLiteNode` of the delegate node.
627 //
628 // See also the `CreateDelegateParams` function in `interpreter.cc` details.
629 typedef struct TfLiteDelegateParams {
630   struct TfLiteDelegate* delegate;
631   TfLiteIntArray* nodes_to_replace;
632   TfLiteIntArray* input_tensors;
633   TfLiteIntArray* output_tensors;
634 } TfLiteDelegateParams;
635 
636 typedef struct TfLiteContext {
637   // Number of tensors in the context.
638   size_t tensors_size;
639 
640   // The execution plan contains a list of the node indices in execution
641   // order. execution_plan->size is the current number of nodes. And,
642   // execution_plan->data[0] is the first node that needs to be run.
643   // TfLiteDelegates can traverse the current execution plan by iterating
644   // through each member of this array and using GetNodeAndRegistration() to
645   // access details about a node. i.e.
646   //
647   // TfLiteIntArray* execution_plan;
648   // TF_LITE_ENSURE_STATUS(context->GetExecutionPlan(context, &execution_plan));
649   // for (int exec_index = 0; exec_index < execution_plan->size; exec_index++) {
650   //    int node_index = execution_plan->data[exec_index];
651   //    TfLiteNode* node;
652   //    TfLiteRegistration* reg;
653   //    context->GetNodeAndRegistration(context, node_index, &node, &reg);
654   // }
655   // Note: the memory pointed by '`*execution_plan` is OWNED by TfLite runtime.
656   // Future calls to GetExecutionPlan invalidates earlier outputs. The following
657   // code snippet shows the issue of such an invocation pattern. After calling
658   // CheckNode, subsequent access to `plan_1st` is undefined.
659   //
660   // void CheckNode(const TfLiteNode* node) {
661   //   ...
662   //   TfLiteIntArray* plan_2nd;
663   //   TF_LITE_ENSURE_STATUS(context->GetExecutionPlan(context, &plan_2nd));
664   //   ...
665   // }
666   //
667   // TfLiteIntArray* plan_1st;
668   // TF_LITE_ENSURE_STATUS(context->GetExecutionPlan(context, &plan_1st));
669   // for (int exec_index = 0; exec_index < plan_1st->size; exec_index++) {
670   //    int node_index = plan_1st->data[exec_index];
671   //    TfLiteNode* node;
672   //    TfLiteRegistration* reg;
673   //    context->GetNodeAndRegistration(context, node_index, &node, &reg);
674   //    CheckNode(node);
675   // }
676   //
677   // WARNING: This is an experimental interface that is subject to change.
678   TfLiteStatus (*GetExecutionPlan)(struct TfLiteContext* context,
679                                    TfLiteIntArray** execution_plan);
680 
681   // An array of tensors in the interpreter context (of length `tensors_size`)
682   TfLiteTensor* tensors;
683 
684   // opaque full context ptr (an opaque c++ data structure)
685   void* impl_;
686 
687   // Request memory pointer be resized. Updates dimensions on the tensor.
688   // NOTE: ResizeTensor takes ownership of newSize.
689   TfLiteStatus (*ResizeTensor)(struct TfLiteContext*, TfLiteTensor* tensor,
690                                TfLiteIntArray* new_size);
691   // Request that an error be reported with format string msg.
692   void (*ReportError)(struct TfLiteContext*, const char* msg, ...);
693 
694   // Add `tensors_to_add` tensors, preserving pre-existing Tensor entries.  If
695   // non-null, the value pointed to by `first_new_tensor_index` will be set to
696   // the index of the first new tensor.
697   TfLiteStatus (*AddTensors)(struct TfLiteContext*, int tensors_to_add,
698                              int* first_new_tensor_index);
699 
700   // Get a Tensor node by node_index.
701   // WARNING: This is an experimental interface that is subject to change.
702   TfLiteStatus (*GetNodeAndRegistration)(
703       struct TfLiteContext*, int node_index, TfLiteNode** node,
704       struct TfLiteRegistration** registration);
705 
706   // Replace ops with one or more stub delegate operations. This function
707   // does not take ownership of `nodes_to_replace`.
708   TfLiteStatus (*ReplaceNodeSubsetsWithDelegateKernels)(
709       struct TfLiteContext*, struct TfLiteRegistration registration,
710       const TfLiteIntArray* nodes_to_replace, struct TfLiteDelegate* delegate);
711 
712   // Number of threads that are recommended to subsystems like gemmlowp and
713   // eigen.
714   int recommended_num_threads;
715 
716   // Access external contexts by type.
717   // WARNING: This is an experimental interface that is subject to change.
718   TfLiteExternalContext* (*GetExternalContext)(struct TfLiteContext*,
719                                                TfLiteExternalContextType);
720   // Set the value of a external context. Does not take ownership of the
721   // pointer.
722   // WARNING: This is an experimental interface that is subject to change.
723   void (*SetExternalContext)(struct TfLiteContext*, TfLiteExternalContextType,
724                              TfLiteExternalContext*);
725 
726   // Flag for allowing float16 precision for FP32 calculation.
727   // default: false.
728   // WARNING: This is an experimental API and subject to change.
729   bool allow_fp32_relax_to_fp16;
730 
731   // Pointer to the op-level profiler, if set; nullptr otherwise.
732   void* profiler;
733 
734   // Allocate persistent buffer which has the same life time as the interpreter.
735   // Returns nullptr on failure.
736   // The memory is allocated from heap for TFL, and from tail in TFLM.
737   // This method is only available in Init or Prepare stage.
738   // WARNING: This is an experimental interface that is subject to change.
739   void* (*AllocatePersistentBuffer)(struct TfLiteContext* ctx, size_t bytes);
740 
741   // Allocate a buffer which will be deallocated right after invoke phase.
742   // The memory is allocated from heap in TFL, and from volatile arena in TFLM.
743   // This method is only available in invoke stage.
744   // NOTE: If possible use RequestScratchBufferInArena method to avoid memory
745   // allocation during inference time.
746   // WARNING: This is an experimental interface that is subject to change.
747   TfLiteStatus (*AllocateBufferForEval)(struct TfLiteContext* ctx, size_t bytes,
748                                         void** ptr);
749 
750   // Request a scratch buffer in the arena through static memory planning.
751   // This method is only available in Prepare stage and the buffer is allocated
752   // by the interpreter between Prepare and Eval stage. In Eval stage,
753   // GetScratchBuffer API can be used to fetch the address.
754   // WARNING: This is an experimental interface that is subject to change.
755   TfLiteStatus (*RequestScratchBufferInArena)(struct TfLiteContext* ctx,
756                                               size_t bytes, int* buffer_idx);
757 
758   // Get the scratch buffer pointer.
759   // This method is only available in Eval stage.
760   // WARNING: This is an experimental interface that is subject to change.
761   void* (*GetScratchBuffer)(struct TfLiteContext* ctx, int buffer_idx);
762 
763   // Resize the memory pointer of the `tensor`. This method behaves the same as
764   // `ResizeTensor`, except that it makes a copy of the shape array internally
765   // so the shape array could be deallocated right afterwards.
766   // WARNING: This is an experimental interface that is subject to change.
767   TfLiteStatus (*ResizeTensorExplicit)(struct TfLiteContext* ctx,
768                                        TfLiteTensor* tensor, int dims,
769                                        const int* shape);
770 
771   // This method provides a preview of post-delegation partitioning. Each
772   // TfLiteDelegateParams in the referenced array corresponds to one instance of
773   // the delegate kernel.
774   // Example usage:
775   //
776   // TfLiteIntArray* nodes_to_replace = ...;
777   // TfLiteDelegateParams* params_array;
778   // int num_partitions = 0;
779   // TF_LITE_ENSURE_STATUS(context->PreviewDelegatePartitioning(
780   //    context, delegate, nodes_to_replace, &params_array, &num_partitions));
781   // for (int idx = 0; idx < num_partitions; idx++) {
782   //    const auto& partition_params = params_array[idx];
783   //    ...
784   // }
785   //
786   // NOTE: The context owns the memory referenced by partition_params_array. It
787   // will be cleared with another call to PreviewDelegateParitioning, or after
788   // TfLiteDelegateParams::Prepare returns.
789   //
790   // WARNING: This is an experimental interface that is subject to change.
791   TfLiteStatus (*PreviewDelegatePartitioning)(
792       struct TfLiteContext* context, const TfLiteIntArray* nodes_to_replace,
793       TfLiteDelegateParams** partition_params_array, int* num_partitions);
794 
795   // Returns a TfLiteTensor struct for a given index.
796   // WARNING: This is an experimental interface that is subject to change.
797   // WARNING: This method may not be available on all platforms.
798   TfLiteTensor* (*GetTensor)(const struct TfLiteContext* context,
799                              int tensor_idx);
800 
801   // Returns a TfLiteEvalTensor struct for a given index.
802   // WARNING: This is an experimental interface that is subject to change.
803   // WARNING: This method may not be available on all platforms.
804   TfLiteEvalTensor* (*GetEvalTensor)(const struct TfLiteContext* context,
805                                      int tensor_idx);
806 } TfLiteContext;
807 
808 typedef struct TfLiteRegistration {
809   // Initializes the op from serialized data.
810   // If a built-in op:
811   //   `buffer` is the op's params data (TfLiteLSTMParams*).
812   //   `length` is zero.
813   // If custom op:
814   //   `buffer` is the op's `custom_options`.
815   //   `length` is the size of the buffer.
816   //
817   // Returns a type-punned (i.e. void*) opaque data (e.g. a primitive pointer
818   // or an instance of a struct).
819   //
820   // The returned pointer will be stored with the node in the `user_data` field,
821   // accessible within prepare and invoke functions below.
822   // NOTE: if the data is already in the desired format, simply implement this
823   // function to return `nullptr` and implement the free function to be a no-op.
824   void* (*init)(TfLiteContext* context, const char* buffer, size_t length);
825 
826   // The pointer `buffer` is the data previously returned by an init invocation.
827   void (*free)(TfLiteContext* context, void* buffer);
828 
829   // prepare is called when the inputs this node depends on have been resized.
830   // context->ResizeTensor() can be called to request output tensors to be
831   // resized.
832   //
833   // Returns kTfLiteOk on success.
834   TfLiteStatus (*prepare)(TfLiteContext* context, TfLiteNode* node);
835 
836   // Execute the node (should read node->inputs and output to node->outputs).
837   // Returns kTfLiteOk on success.
838   TfLiteStatus (*invoke)(TfLiteContext* context, TfLiteNode* node);
839 
840   // profiling_string is called during summarization of profiling information
841   // in order to group executions together. Providing a value here will cause a
842   // given op to appear multiple times is the profiling report. This is
843   // particularly useful for custom ops that can perform significantly
844   // different calculations depending on their `user-data`.
845   const char* (*profiling_string)(const TfLiteContext* context,
846                                   const TfLiteNode* node);
847 
848   // Builtin codes. If this kernel refers to a builtin this is the code
849   // of the builtin. This is so we can do marshaling to other frameworks like
850   // NN API.
851   // Note: It is the responsibility of the registration binder to set this
852   // properly.
853   int32_t builtin_code;
854 
855   // Custom op name. If the op is a builtin, this will be null.
856   // Note: It is the responsibility of the registration binder to set this
857   // properly.
858   // WARNING: This is an experimental interface that is subject to change.
859   const char* custom_name;
860 
861   // The version of the op.
862   // Note: It is the responsibility of the registration binder to set this
863   // properly.
864   int version;
865 } TfLiteRegistration;
866 
867 // The flags used in `TfLiteDelegate`. Note that this is a bitmask, so the
868 // values should be 1, 2, 4, 8, ...etc.
869 typedef enum TfLiteDelegateFlags {
870   kTfLiteDelegateFlagsNone = 0,
871   // The flag is set if the delegate can handle dynamic sized tensors.
872   // For example, the output shape of a `Resize` op with non-constant shape
873   // can only be inferred when the op is invoked.
874   // In this case, the Delegate is responsible for calling
875   // `SetTensorToDynamic` to mark the tensor as a dynamic tensor, and calling
876   // `ResizeTensor` when invoking the op.
877   //
878   // If the delegate isn't capable to handle dynamic tensors, this flag need
879   // to be set to false.
880   kTfLiteDelegateFlagsAllowDynamicTensors = 1,
881 
882   // This flag can be used by delegates (that allow dynamic tensors) to ensure
883   // applicable tensor shapes are automatically propagated in the case of tensor
884   // resizing.
885   // This means that non-dynamic (allocation_type != kTfLiteDynamic) I/O tensors
886   // of a delegate kernel will have correct shapes before its Prepare() method
887   // is called. The runtime leverages TFLite builtin ops in the original
888   // execution plan to propagate shapes.
889   //
890   // A few points to note:
891   // 1. This requires kTfLiteDelegateFlagsAllowDynamicTensors. If that flag is
892   // false, this one is redundant since the delegate kernels are re-initialized
893   // every time tensors are resized.
894   // 2. Enabling this flag adds some overhead to AllocateTensors(), since extra
895   // work is required to prepare the original execution plan.
896   // 3. This flag requires that the original execution plan only have ops with
897   // valid registrations (and not 'dummy' custom ops like with Flex).
898   // WARNING: This feature is experimental and subject to change.
899   kTfLiteDelegateFlagsRequirePropagatedShapes = 2
900 } TfLiteDelegateFlags;
901 
902 // WARNING: This is an experimental interface that is subject to change.
903 typedef struct TfLiteDelegate {
904   // Data that delegate needs to identify itself. This data is owned by the
905   // delegate. The delegate is owned in the user code, so the delegate is
906   // responsible for doing this when it is destroyed.
907   void* data_;
908 
909   // Invoked by ModifyGraphWithDelegate. This prepare is called, giving the
910   // delegate a view of the current graph through TfLiteContext*. It typically
911   // will look at the nodes and call ReplaceNodeSubsetsWithDelegateKernels()
912   // to ask the TensorFlow lite runtime to create macro-nodes to represent
913   // delegated subgraphs of the original graph.
914   TfLiteStatus (*Prepare)(TfLiteContext* context,
915                           struct TfLiteDelegate* delegate);
916 
917   // Copy the data from delegate buffer handle into raw memory of the given
918   // 'tensor'. Note that the delegate is allowed to allocate the raw bytes as
919   // long as it follows the rules for kTfLiteDynamic tensors, in which case this
920   // cannot be null.
921   TfLiteStatus (*CopyFromBufferHandle)(TfLiteContext* context,
922                                        struct TfLiteDelegate* delegate,
923                                        TfLiteBufferHandle buffer_handle,
924                                        TfLiteTensor* tensor);
925 
926   // Copy the data from raw memory of the given 'tensor' to delegate buffer
927   // handle. This can be null if the delegate doesn't use its own buffer.
928   TfLiteStatus (*CopyToBufferHandle)(TfLiteContext* context,
929                                      struct TfLiteDelegate* delegate,
930                                      TfLiteBufferHandle buffer_handle,
931                                      TfLiteTensor* tensor);
932 
933   // Free the Delegate Buffer Handle. Note: This only frees the handle, but
934   // this doesn't release the underlying resource (e.g. textures). The
935   // resources are either owned by application layer or the delegate.
936   // This can be null if the delegate doesn't use its own buffer.
937   void (*FreeBufferHandle)(TfLiteContext* context,
938                            struct TfLiteDelegate* delegate,
939                            TfLiteBufferHandle* handle);
940 
941   // Bitmask flags. See the comments in `TfLiteDelegateFlags`.
942   int64_t flags;
943 } TfLiteDelegate;
944 
945 // Build a 'null' delegate, with all the fields properly set to their default
946 // values.
947 TfLiteDelegate TfLiteDelegateCreate();
948 
949 #ifdef __cplusplus
950 }  // extern "C"
951 #endif  // __cplusplus
952 #endif  // TENSORFLOW_LITE_C_COMMON_H_
953