common.h 38 KB

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