common.h 41 KB

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