micro_allocator.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. /* Copyright 2020 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. #ifndef TENSORFLOW_LITE_MICRO_MICRO_ALLOCATOR_H_
  13. #define TENSORFLOW_LITE_MICRO_MICRO_ALLOCATOR_H_
  14. #include <cstddef>
  15. #include <cstdint>
  16. #include "flatbuffers/flatbuffers.h" // from @flatbuffers
  17. #include "tensorflow/lite/c/common.h"
  18. #include "tensorflow/lite/core/api/error_reporter.h"
  19. #include "tensorflow/lite/micro/compatibility.h"
  20. #include "tensorflow/lite/micro/micro_op_resolver.h"
  21. #include "tensorflow/lite/micro/simple_memory_allocator.h"
  22. #include "tensorflow/lite/schema/schema_generated.h"
  23. namespace tflite {
  24. namespace internal {
  25. // Sets up all of the data structure members for a TfLiteTensor based on the
  26. // contents of a serialized tensor in the flatbuffer.
  27. // TODO(b/162311891): Drop this method when the interpreter has an API for
  28. // returning buffers on TfLiteEvalTensor.
  29. TfLiteStatus InitializeTfLiteTensorFromFlatbuffer(
  30. SimpleMemoryAllocator* allocator, bool allocate_temp,
  31. const tflite::Tensor& flatbuffer_tensor,
  32. const flatbuffers::Vector<flatbuffers::Offset<Buffer>>* buffers,
  33. ErrorReporter* error_reporter, TfLiteTensor* result);
  34. // Holds placeholder information for a scratch buffer request from a kernel.
  35. // This struct is only used during the model prepare stage. Each request from a
  36. // kernel is stored in the head section. During the prepare stage, the head
  37. // section will at least hold kMaxScratchBuffersPerOp number of requests plus
  38. // any requests from previous kernel requests.
  39. //
  40. // When the memory plan is finalized, these structs are no longer used in favor
  41. // of a sequential, array of ScratchBufferHandle allocations in the tail
  42. // section. These allocations are indexed by the request API defined in the
  43. // TfLiteContext struct.
  44. typedef struct {
  45. // Number of bytes required by the buffer. The actual allocated size might be
  46. // greater than `bytes` due to buffer alignment.
  47. size_t bytes;
  48. // Node where the buffer is allocated for. This provides useful information to
  49. // determine the lifetime of the buffer. In AllocationInfo, this buffer will
  50. // have `before` = node_idx and `after` = node_idx.
  51. int node_idx;
  52. } ScratchBufferRequest;
  53. } // namespace internal
  54. typedef struct {
  55. TfLiteNode node;
  56. const TfLiteRegistration* registration;
  57. } NodeAndRegistration;
  58. // Holds a pointer to a buffer for a scratch buffer requested by a kernel during
  59. // the model prepare stage. This struct is allocated in-place and allows for
  60. // quick pointer-indexed lookup for speed during model inference.
  61. typedef struct {
  62. // Pointer to location of the scratch buffer:
  63. uint8_t* data;
  64. } ScratchBufferHandle;
  65. // Allocator responsible for allocating memory for all intermediate tensors
  66. // necessary to invoke a model.
  67. //
  68. // The lifetime of the model, tensor arena and error reporter must be at
  69. // least as long as that of the allocator object, since the allocator needs
  70. // them to be accessible during its entire lifetime.
  71. //
  72. // The MicroAllocator simply plans out additional allocations that are required
  73. // to standup a model for inference in TF Micro. This class currently relies on
  74. // an additional allocator - SimpleMemoryAllocator - for all allocations from an
  75. // arena. These allocations are divided into head (non-persistent) and tail
  76. // (persistent) regions:
  77. //
  78. // Memory layout to help understand how it works
  79. // This information could change in the future version.
  80. // ************** .memory_allocator->GetBuffer()
  81. // Tensors/Scratch buffers (head)
  82. // ************** .head_watermark
  83. // unused memory
  84. // ************** .memory_allocator->GetBuffer() + ->GetMaxBufferSize()
  85. // - ->GetDataSize()
  86. // persistent area (tail)
  87. // ************** .memory_allocator->GetBuffer() + ->GetMaxBufferSize()
  88. class MicroAllocator {
  89. public:
  90. // Creates a MicroAllocator instance from a given tensor arena. This arena
  91. // will be managed by the created instance.
  92. // Note: Please use __declspec(align(16)) to make sure tensor_arena is 16
  93. // bytes aligned, otherwise some head room will be wasted.
  94. // TODO(b/157615197): Cleanup constructor + factory usage.
  95. static MicroAllocator* Create(uint8_t* tensor_arena, size_t arena_size,
  96. ErrorReporter* error_reporter);
  97. // Creates a MicroAllocator instance using the provided SimpleMemoryAllocator
  98. // intance. This allocator instance will use the SimpleMemoryAllocator
  99. // instance to manage allocations internally.
  100. static MicroAllocator* Create(SimpleMemoryAllocator* memory_allocator,
  101. ErrorReporter* error_reporter);
  102. // Begin allocating internal resources required for model inference.
  103. // This method will run through the flatbuffer data supplied in the model to
  104. // properly allocate tensor, node, and op registration data. This method is
  105. // expected to be followed with a call to FinishModelAllocation() before
  106. // resuming allocation with another model. All persistent tensor buffers are
  107. // stored in the out-param eval_tensors. This value is allocated from the
  108. // persistent memory arena and will be used to host runtime tensor buffers.
  109. TfLiteStatus StartModelAllocation(
  110. const Model* model, const MicroOpResolver& op_resolver,
  111. NodeAndRegistration** node_and_registrations,
  112. TfLiteEvalTensor** eval_tensors);
  113. // Finish allocating internal resources required for model inference.
  114. // This method will plan non-persistent buffers and commit a memory plan to
  115. // the 'head' section of the memory arena. All variable tensor data will also
  116. // be allocated. This method should be called after assigning model resources
  117. // in StartModelAllocation(). The eval_tensors pointer should be the value
  118. // passed into this class during StartModelAllocation(). Scratch buffer
  119. // handles are stored in the out-param `scratch_buffer_handles`. This value
  120. // will be used in `GetScratchBuffer` call to retrieve scratch buffers.
  121. TfLiteStatus FinishModelAllocation(
  122. const Model* model, TfLiteEvalTensor* eval_tensors,
  123. ScratchBufferHandle** scratch_buffer_handles);
  124. // Allocates a TfLiteTensor struct and populates the returned value with
  125. // properties from the model flatbuffer. This struct is allocated from
  126. // persistent arena memory is only guaranteed for the lifetime of the
  127. // application. The eval_tensors pointer should be the value passed into this
  128. // class during StartModelAllocation() and contains the source-of-truth for
  129. // buffers.
  130. virtual TfLiteTensor* AllocatePersistentTfLiteTensor(
  131. const Model* model, TfLiteEvalTensor* eval_tensors, int tensor_index);
  132. // Allocates a TfLiteTensor struct and populates the returned value with
  133. // properties from the model flatbuffer. This struct is allocated from
  134. // temporary arena memory is only guaranteed until a call is made to
  135. // ResetTempAllocations(). The eval_tensors pointer should be the value passed
  136. // into this class during StartModelAllocation() and contains the
  137. // source-of-truth for buffers.
  138. virtual TfLiteTensor* AllocateTempTfLiteTensor(const Model* model,
  139. TfLiteEvalTensor* eval_tensors,
  140. int tensor_index);
  141. // Resets all temporary allocations. This method should be called after a
  142. // chain of temp allocations (e.g. chain of TfLiteTensor objects via
  143. // AllocateTfLiteTensor()).
  144. virtual void ResetTempAllocations();
  145. // Allocates persistent buffer which has the same life time as the allocator.
  146. // The memory is immediately available and is allocated from the tail of the
  147. // arena.
  148. virtual void* AllocatePersistentBuffer(size_t bytes);
  149. // Register a scratch buffer of size `bytes` for Node with `node_id`.
  150. // This method only requests a buffer with a given size to be used after a
  151. // model has finished allocation via FinishModelAllocation(). All requested
  152. // buffers will be accessible by the out-param in that method.
  153. TfLiteStatus RequestScratchBufferInArena(size_t bytes, int* buffer_idx);
  154. // Finish allocating a specific NodeAndRegistration prepare block (kernel
  155. // entry for a model) with a given node ID. This call ensures that any scratch
  156. // buffer requests and temporary allocations are handled and ready for the
  157. // next node prepare block.
  158. TfLiteStatus FinishPrepareNodeAllocations(int node_id);
  159. // Returns the arena usage in bytes, only available after
  160. // `FinishModelAllocation`. Otherwise, it will return 0.
  161. size_t used_bytes() const;
  162. protected:
  163. MicroAllocator(SimpleMemoryAllocator* memory_allocator,
  164. ErrorReporter* error_reporter);
  165. virtual ~MicroAllocator();
  166. // Allocates an array in the arena to hold pointers to the node and
  167. // registration pointers required to represent the inference graph of the
  168. // model.
  169. virtual TfLiteStatus AllocateNodeAndRegistrations(
  170. const Model* model, NodeAndRegistration** node_and_registrations);
  171. // Populates node and registration pointers representing the inference graph
  172. // of the model from values inside the flatbuffer (loaded from the TfLiteModel
  173. // instance). Persistent data (e.g. operator data) is allocated from the
  174. // arena.
  175. virtual TfLiteStatus PrepareNodeAndRegistrationDataFromFlatbuffer(
  176. const Model* model, const MicroOpResolver& op_resolver,
  177. NodeAndRegistration* node_and_registrations);
  178. // Allocates the list of persistent TfLiteEvalTensors that are used for the
  179. // "eval" phase of model inference. These structs will be the source of truth
  180. // for all tensor buffers. Allocation results are stored in the out-param
  181. // eval_tensors.
  182. virtual TfLiteStatus AllocateTfLiteEvalTensors(
  183. const Model* model, TfLiteEvalTensor** eval_tensors);
  184. // Allocates persistent tensor buffers for variable tensors in the subgraph.
  185. virtual TfLiteStatus AllocateVariables(const SubGraph* subgraph,
  186. TfLiteEvalTensor* eval_tensors);
  187. // Allocate and return a persistent TfLiteTensor.
  188. // TODO(b/162311891): Drop this method when the interpreter has an API for
  189. // accessing TfLiteEvalTensor structs.
  190. virtual TfLiteTensor* AllocatePersistentTfLiteTensorInternal(
  191. const Model* model, TfLiteEvalTensor* eval_tensors, int tensor_index);
  192. // Populates a TfLiteTensor struct with data from the model flatbuffer. Any
  193. // quantization data is allocated from either the tail (persistent) or temp
  194. // sections of the arena based on the allocation flag.
  195. virtual TfLiteStatus PopulateTfLiteTensorFromFlatbuffer(
  196. const Model* model, const SubGraph* subgraph, TfLiteTensor* tensor,
  197. int tensor_index, bool allocate_temp);
  198. ErrorReporter* error_reporter() const;
  199. // Returns the first subgraph from the model.
  200. const SubGraph* GetSubGraphFromModel(const Model* model);
  201. private:
  202. // Commits a memory plan for all non-persistent buffer allocations in the
  203. // 'head' section of the memory arena. The eval_tensors pointer is the list of
  204. // pre-allocated TfLiteEvalTensor structs that will point to the buffers that
  205. // will be allocated into the head section in this function call. The
  206. // scratch_buffer_handles pointer is the array of pre-allocated
  207. // ScratchBufferHandle structs that will point to allocated buffers also in
  208. // the head section.
  209. virtual TfLiteStatus CommitStaticMemoryPlan(
  210. const Model* model, const SubGraph* subgraph,
  211. TfLiteEvalTensor* eval_tensors,
  212. ScratchBufferHandle* scratch_buffer_handles);
  213. // Allocates an array of ScratchBufferHandle structs in the tail section for a
  214. // given number of handles.
  215. virtual TfLiteStatus AllocateScratchBufferHandles(
  216. ScratchBufferHandle** scratch_buffer_handles, size_t handle_count);
  217. // Clears all internal scratch buffer request counts and resets the head to
  218. // prepare for kernels to request scratch buffer data when a model is
  219. // preparing.
  220. TfLiteStatus InitScratchBufferData();
  221. // Returns the pointer for the array of ScratchBufferRequest allocations in
  222. // the head section.
  223. internal::ScratchBufferRequest* GetScratchBufferRequests();
  224. // A simple memory allocator that always allocate from the arena tail or head.
  225. SimpleMemoryAllocator* memory_allocator_;
  226. ErrorReporter* error_reporter_;
  227. bool model_is_allocating_;
  228. // Holds the number of ScratchBufferRequest instances stored in the head
  229. // section when a model is allocating.
  230. size_t scratch_buffer_request_count_ = 0;
  231. // Holds the byte length of the memory plan with the largest head usage. Used
  232. // to ensure that multi-tenant allocations can share the head for buffers.
  233. size_t max_head_buffer_usage_ = 0;
  234. TF_LITE_REMOVE_VIRTUAL_DELETE
  235. };
  236. } // namespace tflite
  237. #endif // TENSORFLOW_LITE_MICRO_MICRO_ALLOCATOR_H_