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