common.h 32 KB

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