common.h 47 KB

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