common.h 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  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 and user defined data, not
  401. // 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. } TfLiteNode;
  428. #else // defined(TF_LITE_STATIC_MEMORY)?
  429. // NOTE: This flag is opt-in only at compile time.
  430. //
  431. // Specific reduced TfLiteTensor struct for TF Micro runtime. This struct
  432. // contains only the minimum fields required to initialize and prepare a micro
  433. // inference graph. The fields in this struct have been ordered from
  434. // largest-to-smallest for optimal struct sizeof.
  435. //
  436. // This struct does not use:
  437. // - allocation
  438. // - buffer_handle
  439. // - data_is_stale
  440. // - delegate
  441. // - dims_signature
  442. // - name
  443. // - sparsity
  444. typedef struct TfLiteTensor {
  445. // TODO(b/155784997): Consider consolidating these quantization fields:
  446. // Quantization information. Replaces params field above.
  447. TfLiteQuantization quantization;
  448. // Quantization information.
  449. TfLiteQuantizationParams params;
  450. // A union of data pointers. The appropriate type should be used for a typed
  451. // tensor based on `type`.
  452. TfLitePtrUnion data;
  453. // A pointer to a structure representing the dimensionality interpretation
  454. // that the buffer should have. NOTE: the product of elements of `dims`
  455. // and the element datatype size should be equal to `bytes` below.
  456. TfLiteIntArray* dims;
  457. // The number of bytes required to store the data of this Tensor. I.e.
  458. // (bytes of each element) * dims[0] * ... * dims[n-1]. For example, if
  459. // type is kTfLiteFloat32 and dims = {3, 2} then
  460. // bytes = sizeof(float) * 3 * 2 = 4 * 3 * 2 = 24.
  461. size_t bytes;
  462. // The data type specification for data stored in `data`. This affects
  463. // what member of `data` union should be used.
  464. TfLiteType type;
  465. // How memory is mapped
  466. // kTfLiteMmapRo: Memory mapped read only.
  467. // i.e. weights
  468. // kTfLiteArenaRw: Arena allocated read write memory
  469. // (i.e. temporaries, outputs).
  470. TfLiteAllocationType allocation_type;
  471. // True if the tensor is a variable.
  472. bool is_variable;
  473. } TfLiteTensor;
  474. // Specific reduced TfLiteNode struct for TF Micro runtime. This struct contains
  475. // only the minimum fields required to represent a node.
  476. //
  477. // This struct does not use:
  478. // - delegate
  479. // - intermediates
  480. // - temporaries
  481. typedef struct TfLiteNode {
  482. // Inputs to this node expressed as indices into the simulator's tensors.
  483. TfLiteIntArray* inputs;
  484. // Outputs to this node expressed as indices into the simulator's tensors.
  485. TfLiteIntArray* outputs;
  486. // Opaque data provided by the node implementer through `Registration.init`.
  487. void* user_data;
  488. // Opaque data provided to the node if the node is a builtin. This is usually
  489. // a structure defined in builtin_op_data.h
  490. void* builtin_data;
  491. // Custom initial data. This is the opaque data provided in the flatbuffer.
  492. // WARNING: This is an experimental interface that is subject to change.
  493. const void* custom_initial_data;
  494. int custom_initial_data_size;
  495. } TfLiteNode;
  496. #endif // TF_LITE_STATIC_MEMORY
  497. // Light-weight tensor struct for TF Micro runtime. Provides the minimal amount
  498. // of information required for a kernel to run during TfLiteRegistration::Eval.
  499. // TODO(b/160955687): Move this field into TF_LITE_STATIC_MEMORY when TFLM
  500. // builds with this flag by default internally.
  501. typedef struct TfLiteEvalTensor {
  502. // A union of data pointers. The appropriate type should be used for a typed
  503. // tensor based on `type`.
  504. TfLitePtrUnion data;
  505. // A pointer to a structure representing the dimensionality interpretation
  506. // that the buffer should have.
  507. TfLiteIntArray* dims;
  508. // The data type specification for data stored in `data`. This affects
  509. // what member of `data` union should be used.
  510. TfLiteType type;
  511. } TfLiteEvalTensor;
  512. #ifndef TF_LITE_STATIC_MEMORY
  513. // Free data memory of tensor `t`.
  514. void TfLiteTensorDataFree(TfLiteTensor* t);
  515. // Free quantization data.
  516. void TfLiteQuantizationFree(TfLiteQuantization* quantization);
  517. // Free sparsity parameters.
  518. void TfLiteSparsityFree(TfLiteSparsity* sparsity);
  519. // Free memory of tensor `t`.
  520. void TfLiteTensorFree(TfLiteTensor* t);
  521. // Set all of a tensor's fields (and free any previously allocated data).
  522. void TfLiteTensorReset(TfLiteType type, const char* name, TfLiteIntArray* dims,
  523. TfLiteQuantizationParams quantization, char* buffer,
  524. size_t size, TfLiteAllocationType allocation_type,
  525. const void* allocation, bool is_variable,
  526. TfLiteTensor* tensor);
  527. // Resize the allocated data of a (dynamic) tensor. Tensors with allocation
  528. // types other than kTfLiteDynamic will be ignored.
  529. void TfLiteTensorRealloc(size_t num_bytes, TfLiteTensor* tensor);
  530. #endif // TF_LITE_STATIC_MEMORY
  531. // WARNING: This is an experimental interface that is subject to change.
  532. //
  533. // Currently, TfLiteDelegateParams has to be allocated in a way that it's
  534. // trivially destructable. It will be stored as `builtin_data` field in
  535. // `TfLiteNode` of the delegate node.
  536. //
  537. // See also the `CreateDelegateParams` function in `interpreter.cc` details.
  538. typedef struct TfLiteDelegateParams {
  539. struct TfLiteDelegate* delegate;
  540. TfLiteIntArray* nodes_to_replace;
  541. TfLiteIntArray* input_tensors;
  542. TfLiteIntArray* output_tensors;
  543. } TfLiteDelegateParams;
  544. typedef struct TfLiteContext {
  545. // Number of tensors in the context.
  546. size_t tensors_size;
  547. // The execution plan contains a list of the node indices in execution
  548. // order. execution_plan->size is the current number of nodes. And,
  549. // execution_plan->data[0] is the first node that needs to be run.
  550. // TfLiteDelegates can traverse the current execution plan by iterating
  551. // through each member of this array and using GetNodeAndRegistration() to
  552. // access details about a node. i.e.
  553. // TfLiteIntArray* execution_plan;
  554. // TF_LITE_ENSURE_STATUS(context->GetExecutionPlan(context, &execution_plan));
  555. // for (int exec_index = 0; exec_index < execution_plan->size; exec_index++) {
  556. // int node_index = execution_plan->data[exec_index];
  557. // TfLiteNode* node;
  558. // TfLiteRegistration* reg;
  559. // context->GetNodeAndRegistration(context, node_index, &node, &reg);
  560. // }
  561. // WARNING: This is an experimental interface that is subject to change.
  562. TfLiteStatus (*GetExecutionPlan)(struct TfLiteContext* context,
  563. TfLiteIntArray** execution_plan);
  564. // An array of tensors in the interpreter context (of length `tensors_size`)
  565. TfLiteTensor* tensors;
  566. // opaque full context ptr (an opaque c++ data structure)
  567. void* impl_;
  568. // Request memory pointer be resized. Updates dimensions on the tensor.
  569. // NOTE: ResizeTensor takes ownership of newSize.
  570. TfLiteStatus (*ResizeTensor)(struct TfLiteContext*, TfLiteTensor* tensor,
  571. TfLiteIntArray* new_size);
  572. // Request that an error be reported with format string msg.
  573. void (*ReportError)(struct TfLiteContext*, const char* msg, ...);
  574. // Add `tensors_to_add` tensors, preserving pre-existing Tensor entries. If
  575. // non-null, the value pointed to by `first_new_tensor_index` will be set to
  576. // the index of the first new tensor.
  577. TfLiteStatus (*AddTensors)(struct TfLiteContext*, int tensors_to_add,
  578. int* first_new_tensor_index);
  579. // Get a Tensor node by node_index.
  580. // WARNING: This is an experimental interface that is subject to change.
  581. TfLiteStatus (*GetNodeAndRegistration)(
  582. struct TfLiteContext*, int node_index, TfLiteNode** node,
  583. struct TfLiteRegistration** registration);
  584. // Replace ops with one or more stub delegate operations. This function
  585. // does not take ownership of `nodes_to_replace`.
  586. TfLiteStatus (*ReplaceNodeSubsetsWithDelegateKernels)(
  587. struct TfLiteContext*, struct TfLiteRegistration registration,
  588. const TfLiteIntArray* nodes_to_replace, struct TfLiteDelegate* delegate);
  589. // Number of threads that are recommended to subsystems like gemmlowp and
  590. // eigen.
  591. int recommended_num_threads;
  592. // Access external contexts by type.
  593. // WARNING: This is an experimental interface that is subject to change.
  594. TfLiteExternalContext* (*GetExternalContext)(struct TfLiteContext*,
  595. TfLiteExternalContextType);
  596. // Set the value of a external context. Does not take ownership of the
  597. // pointer.
  598. // WARNING: This is an experimental interface that is subject to change.
  599. void (*SetExternalContext)(struct TfLiteContext*, TfLiteExternalContextType,
  600. TfLiteExternalContext*);
  601. // Flag for allowing float16 precision for FP32 calculation.
  602. // default: false.
  603. // WARNING: This is an experimental API and subject to change.
  604. bool allow_fp32_relax_to_fp16;
  605. // Pointer to the op-level profiler, if set; nullptr otherwise.
  606. void* profiler;
  607. // Allocate persistent buffer which has the same life time as the interpreter.
  608. // Returns nullptr on failure.
  609. // The memory is allocated from heap for TFL, and from tail in TFLM.
  610. // This method is only available in Init or Prepare stage.
  611. // WARNING: This is an experimental interface that is subject to change.
  612. void* (*AllocatePersistentBuffer)(struct TfLiteContext* ctx, size_t bytes);
  613. // Allocate a buffer which will be deallocated right after invoke phase.
  614. // The memory is allocated from heap in TFL, and from volatile arena in TFLM.
  615. // This method is only available in invoke stage.
  616. // NOTE: If possible use RequestScratchBufferInArena method to avoid memory
  617. // allocation during inference time.
  618. // WARNING: This is an experimental interface that is subject to change.
  619. TfLiteStatus (*AllocateBufferForEval)(struct TfLiteContext* ctx, size_t bytes,
  620. void** ptr);
  621. // Request a scratch buffer in the arena through static memory planning.
  622. // This method is only available in Prepare stage and the buffer is allocated
  623. // by the interpreter between Prepare and Eval stage. In Eval stage,
  624. // GetScratchBuffer API can be used to fetch the address.
  625. // WARNING: This is an experimental interface that is subject to change.
  626. TfLiteStatus (*RequestScratchBufferInArena)(struct TfLiteContext* ctx,
  627. size_t bytes, int* buffer_idx);
  628. // Get the scratch buffer pointer.
  629. // This method is only available in Eval stage.
  630. // WARNING: This is an experimental interface that is subject to change.
  631. void* (*GetScratchBuffer)(struct TfLiteContext* ctx, int buffer_idx);
  632. // Resize the memory pointer of the `tensor`. This method behaves the same as
  633. // `ResizeTensor`, except that it makes a copy of the shape array internally
  634. // so the shape array could be deallocated right afterwards.
  635. // WARNING: This is an experimental interface that is subject to change.
  636. TfLiteStatus (*ResizeTensorExplicit)(struct TfLiteContext* ctx,
  637. TfLiteTensor* tensor, int dims,
  638. const int* shape);
  639. // This method provides a preview of post-delegation partitioning. Each
  640. // TfLiteDelegateParams in the referenced array corresponds to one instance of
  641. // the delegate kernel.
  642. // Example usage:
  643. //
  644. // TfLiteIntArray* nodes_to_replace = ...;
  645. // TfLiteDelegateParams* params_array;
  646. // int num_partitions = 0;
  647. // TF_LITE_ENSURE_STATUS(context->PreviewDelegatePartitioning(
  648. // context, delegate, nodes_to_replace, &params_array, &num_partitions));
  649. // for (int idx = 0; idx < num_partitions; idx++) {
  650. // const auto& partition_params = params_array[idx];
  651. // ...
  652. // }
  653. //
  654. // NOTE: The context owns the memory referenced by partition_params_array. It
  655. // will be cleared with another call to PreviewDelegateParitioning, or after
  656. // TfLiteDelegateParams::Prepare returns.
  657. //
  658. // WARNING: This is an experimental interface that is subject to change.
  659. TfLiteStatus (*PreviewDelegatePartitioning)(
  660. struct TfLiteContext* context, const TfLiteIntArray* nodes_to_replace,
  661. TfLiteDelegateParams** partition_params_array, int* num_partitions);
  662. // Returns a TfLiteTensor struct for a given index.
  663. // WARNING: This is an experimental interface that is subject to change.
  664. // WARNING: This method may not be available on all platforms.
  665. TfLiteTensor* (*GetTensor)(const struct TfLiteContext* context,
  666. int tensor_idx);
  667. // Returns a TfLiteEvalTensor struct for a given index.
  668. // WARNING: This is an experimental interface that is subject to change.
  669. // WARNING: This method may not be available on all platforms.
  670. TfLiteEvalTensor* (*GetEvalTensor)(const struct TfLiteContext* context,
  671. int tensor_idx);
  672. } TfLiteContext;
  673. typedef struct TfLiteRegistration {
  674. // Initializes the op from serialized data.
  675. // If a built-in op:
  676. // `buffer` is the op's params data (TfLiteLSTMParams*).
  677. // `length` is zero.
  678. // If custom op:
  679. // `buffer` is the op's `custom_options`.
  680. // `length` is the size of the buffer.
  681. //
  682. // Returns a type-punned (i.e. void*) opaque data (e.g. a primitive pointer
  683. // or an instance of a struct).
  684. //
  685. // The returned pointer will be stored with the node in the `user_data` field,
  686. // accessible within prepare and invoke functions below.
  687. // NOTE: if the data is already in the desired format, simply implement this
  688. // function to return `nullptr` and implement the free function to be a no-op.
  689. void* (*init)(TfLiteContext* context, const char* buffer, size_t length);
  690. // The pointer `buffer` is the data previously returned by an init invocation.
  691. void (*free)(TfLiteContext* context, void* buffer);
  692. // prepare is called when the inputs this node depends on have been resized.
  693. // context->ResizeTensor() can be called to request output tensors to be
  694. // resized.
  695. //
  696. // Returns kTfLiteOk on success.
  697. TfLiteStatus (*prepare)(TfLiteContext* context, TfLiteNode* node);
  698. // Execute the node (should read node->inputs and output to node->outputs).
  699. // Returns kTfLiteOk on success.
  700. TfLiteStatus (*invoke)(TfLiteContext* context, TfLiteNode* node);
  701. // profiling_string is called during summarization of profiling information
  702. // in order to group executions together. Providing a value here will cause a
  703. // given op to appear multiple times is the profiling report. This is
  704. // particularly useful for custom ops that can perform significantly
  705. // different calculations depending on their `user-data`.
  706. const char* (*profiling_string)(const TfLiteContext* context,
  707. const TfLiteNode* node);
  708. // Builtin codes. If this kernel refers to a builtin this is the code
  709. // of the builtin. This is so we can do marshaling to other frameworks like
  710. // NN API.
  711. // Note: It is the responsibility of the registration binder to set this
  712. // properly.
  713. int32_t builtin_code;
  714. // Custom op name. If the op is a builtin, this will be null.
  715. // Note: It is the responsibility of the registration binder to set this
  716. // properly.
  717. // WARNING: This is an experimental interface that is subject to change.
  718. const char* custom_name;
  719. // The version of the op.
  720. // Note: It is the responsibility of the registration binder to set this
  721. // properly.
  722. int version;
  723. } TfLiteRegistration;
  724. // The flags used in `TfLiteDelegate`. Note that this is a bitmask, so the
  725. // values should be 1, 2, 4, 8, ...etc.
  726. typedef enum TfLiteDelegateFlags {
  727. kTfLiteDelegateFlagsNone = 0,
  728. // The flag is set if the delegate can handle dynamic sized tensors.
  729. // For example, the output shape of a `Resize` op with non-constant shape
  730. // can only be inferred when the op is invoked.
  731. // In this case, the Delegate is responsible for calling
  732. // `SetTensorToDynamic` to mark the tensor as a dynamic tensor, and calling
  733. // `ResizeTensor` when invoking the op.
  734. //
  735. // If the delegate isn't capable to handle dynamic tensors, this flag need
  736. // to be set to false.
  737. kTfLiteDelegateFlagsAllowDynamicTensors = 1,
  738. // This flag can be used by delegates (that allow dynamic tensors) to ensure
  739. // applicable tensor shapes are automatically propagated in the case of tensor
  740. // resizing.
  741. // This means that non-dynamic (allocation_type != kTfLiteDynamic) I/O tensors
  742. // of a delegate kernel will have correct shapes before its Prepare() method
  743. // is called. The runtime leverages TFLite builtin ops in the original
  744. // execution plan to propagate shapes.
  745. //
  746. // A few points to note:
  747. // 1. This requires kTfLiteDelegateFlagsAllowDynamicTensors. If that flag is
  748. // false, this one is redundant since the delegate kernels are re-initialized
  749. // every time tensors are resized.
  750. // 2. Enabling this flag adds some overhead to AllocateTensors(), since extra
  751. // work is required to prepare the original execution plan.
  752. // 3. This flag requires that the original execution plan only have ops with
  753. // valid registrations (and not 'dummy' custom ops like with Flex).
  754. // WARNING: This feature is experimental and subject to change.
  755. kTfLiteDelegateFlagsRequirePropagatedShapes = 2
  756. } TfLiteDelegateFlags;
  757. // WARNING: This is an experimental interface that is subject to change.
  758. typedef struct TfLiteDelegate {
  759. // Data that delegate needs to identify itself. This data is owned by the
  760. // delegate. The delegate is owned in the user code, so the delegate is
  761. // responsible for doing this when it is destroyed.
  762. void* data_;
  763. // Invoked by ModifyGraphWithDelegate. This prepare is called, giving the
  764. // delegate a view of the current graph through TfLiteContext*. It typically
  765. // will look at the nodes and call ReplaceNodeSubsetsWithDelegateKernels()
  766. // to ask the TensorFlow lite runtime to create macro-nodes to represent
  767. // delegated subgraphs of the original graph.
  768. TfLiteStatus (*Prepare)(TfLiteContext* context,
  769. struct TfLiteDelegate* delegate);
  770. // Copy the data from delegate buffer handle into raw memory of the given
  771. // 'tensor'. Note that the delegate is allowed to allocate the raw bytes as
  772. // long as it follows the rules for kTfLiteDynamic tensors, in which case this
  773. // cannot be null.
  774. TfLiteStatus (*CopyFromBufferHandle)(TfLiteContext* context,
  775. struct TfLiteDelegate* delegate,
  776. TfLiteBufferHandle buffer_handle,
  777. TfLiteTensor* tensor);
  778. // Copy the data from raw memory of the given 'tensor' to delegate buffer
  779. // handle. This can be null if the delegate doesn't use its own buffer.
  780. TfLiteStatus (*CopyToBufferHandle)(TfLiteContext* context,
  781. struct TfLiteDelegate* delegate,
  782. TfLiteBufferHandle buffer_handle,
  783. TfLiteTensor* tensor);
  784. // Free the Delegate Buffer Handle. Note: This only frees the handle, but
  785. // this doesn't release the underlying resource (e.g. textures). The
  786. // resources are either owned by application layer or the delegate.
  787. // This can be null if the delegate doesn't use its own buffer.
  788. void (*FreeBufferHandle)(TfLiteContext* context,
  789. struct TfLiteDelegate* delegate,
  790. TfLiteBufferHandle* handle);
  791. // Bitmask flags. See the comments in `TfLiteDelegateFlags`.
  792. int64_t flags;
  793. } TfLiteDelegate;
  794. // Build a 'null' delegate, with all the fields properly set to their default
  795. // values.
  796. TfLiteDelegate TfLiteDelegateCreate();
  797. #ifdef __cplusplus
  798. } // extern "C"
  799. #endif // __cplusplus
  800. #endif // TENSORFLOW_LITE_C_COMMON_H_