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