micro_allocator.cc 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  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. #include "tensorflow/lite/micro/micro_allocator.h"
  13. #include <cstddef>
  14. #include <cstdint>
  15. #include "flatbuffers/flatbuffers.h" // from @flatbuffers
  16. #include "tensorflow/lite/c/c_api_types.h"
  17. #include "tensorflow/lite/c/common.h"
  18. #include "tensorflow/lite/core/api/error_reporter.h"
  19. #include "tensorflow/lite/core/api/flatbuffer_conversions.h"
  20. #include "tensorflow/lite/core/api/op_resolver.h"
  21. #include "tensorflow/lite/core/api/tensor_utils.h"
  22. #include "tensorflow/lite/kernels/internal/compatibility.h"
  23. #include "tensorflow/lite/micro/compatibility.h"
  24. #include "tensorflow/lite/micro/flatbuffer_utils.h"
  25. #include "tensorflow/lite/micro/memory_helpers.h"
  26. #include "tensorflow/lite/micro/memory_planner/greedy_memory_planner.h"
  27. #include "tensorflow/lite/micro/memory_planner/micro_memory_planner.h"
  28. #include "tensorflow/lite/micro/micro_allocation_info.h"
  29. #include "tensorflow/lite/micro/micro_arena_constants.h"
  30. #include "tensorflow/lite/micro/micro_error_reporter.h"
  31. #include "tensorflow/lite/micro/simple_memory_allocator.h"
  32. #include "tensorflow/lite/schema/schema_generated.h"
  33. #include "tensorflow/lite/schema/schema_utils.h"
  34. namespace tflite {
  35. namespace {
  36. // Maximum number of scratch buffer requests per operator. Operator kernels that
  37. // request more than this value will receive an exception.
  38. constexpr size_t kMaxScratchBuffersPerOp = 12;
  39. // Sentinel value used as a placeholder to mark a ScratchBufferRequest request
  40. // needs a node id assignment.
  41. constexpr int kUnassignedScratchBufferRequestIndex = -1;
  42. const TfLiteIntArray kZeroLengthIntArray = {};
  43. class MicroBuiltinDataAllocator : public BuiltinDataAllocator {
  44. public:
  45. explicit MicroBuiltinDataAllocator(
  46. IPersistentBufferAllocator* persistent_allocator)
  47. : persistent_allocator_(persistent_allocator) {}
  48. void* Allocate(size_t size, size_t alignment_hint) override {
  49. return persistent_allocator_->AllocatePersistentBuffer(size,
  50. alignment_hint);
  51. }
  52. void Deallocate(void* data) override {
  53. // Do not deallocate, builtin data needs to be available for the life time
  54. // of the model.
  55. }
  56. TF_LITE_REMOVE_VIRTUAL_DELETE
  57. private:
  58. IPersistentBufferAllocator* persistent_allocator_;
  59. };
  60. TfLiteStatus CreatePlan(ErrorReporter* error_reporter,
  61. MicroMemoryPlanner* planner,
  62. const AllocationInfo* allocation_info,
  63. size_t allocation_info_size) {
  64. // Add the tensors to our allocation plan.
  65. for (size_t i = 0; i < allocation_info_size; ++i) {
  66. const AllocationInfo* current = &allocation_info[i];
  67. if (current->needs_allocating) {
  68. size_t aligned_bytes_required =
  69. AlignSizeUp(current->bytes, MicroArenaBufferAlignment());
  70. if (current->offline_offset == kOnlinePlannedBuffer) {
  71. TF_LITE_ENSURE_STATUS(
  72. planner->AddBuffer(error_reporter, aligned_bytes_required,
  73. current->first_created, current->last_used));
  74. } else {
  75. TF_LITE_ENSURE_STATUS(planner->AddBuffer(
  76. error_reporter, aligned_bytes_required, current->first_created,
  77. current->last_used, current->offline_offset));
  78. }
  79. }
  80. }
  81. return kTfLiteOk;
  82. }
  83. TfLiteStatus CommitPlan(ErrorReporter* error_reporter,
  84. MicroMemoryPlanner* planner, uint8_t* starting_point,
  85. const AllocationInfo* allocation_info,
  86. size_t allocation_info_size) {
  87. // Figure out the actual memory addresses for each buffer, based on the plan.
  88. int planner_index = 0;
  89. for (size_t i = 0; i < allocation_info_size; ++i) {
  90. const AllocationInfo* current = &allocation_info[i];
  91. if (current->needs_allocating) {
  92. int offset = -1;
  93. TF_LITE_ENSURE_STATUS(
  94. planner->GetOffsetForBuffer(error_reporter, planner_index, &offset));
  95. *current->output_ptr = reinterpret_cast<void*>(starting_point + offset);
  96. ++planner_index;
  97. }
  98. }
  99. return kTfLiteOk;
  100. }
  101. } // namespace
  102. namespace internal {
  103. // Returns a pointer to any buffer associated with the flatbuffer tensor. Can
  104. // return nullptr if no buffer is found.
  105. void* GetFlatbufferTensorBuffer(
  106. const tflite::Tensor& flatbuffer_tensor,
  107. const flatbuffers::Vector<flatbuffers::Offset<Buffer>>* buffers) {
  108. // We need to figure out where the actual contents of this tensor are stored
  109. // in memory. We'll check to see if there's a serialized buffer (pretty much
  110. // the same as a constant op in TensorFlow) associated with this tensor first,
  111. // and if there is update the runtime structure to point to its location in
  112. // memory.
  113. // First see if there's any buffer information in the serialized tensor.
  114. // TODO(b/170379532): Add better unit tests to validate flatbuffer values.
  115. void* out_buffer = nullptr;
  116. if (auto* buffer = (*buffers)[flatbuffer_tensor.buffer()]) {
  117. // If we've found a buffer, does it have any data?
  118. if (auto* array = buffer->data()) {
  119. // If it has any data, is the data size larger than zero?
  120. if (array->size()) {
  121. // We've found a buffer with valid data, so update the runtime tensor
  122. // data structure to point to it.
  123. out_buffer = const_cast<void*>(static_cast<const void*>(array->data()));
  124. }
  125. }
  126. // TODO(petewarden): It's not clear in what circumstances we could have a
  127. // buffer in the serialized tensor, but it doesn't have any data in it. Is
  128. // that a validly-generated file, and if so what does it mean, or is it an
  129. // error condition? It would be good to tighten up the specification to make
  130. // it less ambiguous.
  131. }
  132. return out_buffer;
  133. }
  134. TfLiteStatus InitializeTfLiteTensorFromFlatbuffer(
  135. IPersistentBufferAllocator* persistent_buffer_allocator,
  136. INonPersistentBufferAllocator* non_persistent_buffer_allocator,
  137. bool allocate_temp, const tflite::Tensor& flatbuffer_tensor,
  138. const flatbuffers::Vector<flatbuffers::Offset<Buffer>>* buffers,
  139. ErrorReporter* error_reporter, TfLiteTensor* result) {
  140. TFLITE_DCHECK(result != nullptr);
  141. *result = {};
  142. // Make sure the serialized type is one we know how to deal with, and convert
  143. // it from a flatbuffer enum into a constant used by the kernel C API.
  144. TF_LITE_ENSURE_STATUS(ConvertTensorType(flatbuffer_tensor.type(),
  145. &result->type, error_reporter));
  146. // Make sure we remember if the serialized tensor is designated as a variable.
  147. result->is_variable = flatbuffer_tensor.is_variable();
  148. result->data.data = GetFlatbufferTensorBuffer(flatbuffer_tensor, buffers);
  149. // TODO(petewarden): Some of these paths aren't getting enough testing
  150. // coverage, so we should figure out some tests that exercise them.
  151. if (result->data.data == nullptr) {
  152. // The tensor contents haven't been set from a serialized buffer, so
  153. // make a note that they will be allocated from memory. The actual
  154. // allocation won't happen until later.
  155. result->allocation_type = kTfLiteArenaRw;
  156. } else {
  157. // We set the data from a serialized buffer, so record tha.
  158. result->allocation_type = kTfLiteMmapRo;
  159. }
  160. // Figure out what the size in bytes of the buffer is and store it.
  161. size_t type_size;
  162. TF_LITE_ENSURE_STATUS(BytesRequiredForTensor(
  163. flatbuffer_tensor, &result->bytes, &type_size, error_reporter));
  164. if (flatbuffer_tensor.shape() == nullptr) {
  165. // flatbuffer_tensor.shape() can return a nullptr in the case of a scalar
  166. // tensor.
  167. // TODO(b/188459715): figure out why const_cast is required here.
  168. result->dims = const_cast<TfLiteIntArray*>(&kZeroLengthIntArray);
  169. } else {
  170. // TFLM doesn't allow reshaping the tensor which requires dynamic memory
  171. // allocation so it is safe to drop the const qualifier. In the future, if
  172. // we really want to update the tensor shape, we can always pass in a new
  173. // TfLiteIntArray - especially we have to do so if the dimension is
  174. result->dims = FlatBufferVectorToTfLiteTypeArray(flatbuffer_tensor.shape());
  175. }
  176. // Copy the quantization information from the serialized data.
  177. const auto* src_quantization = flatbuffer_tensor.quantization();
  178. if (src_quantization && src_quantization->scale() &&
  179. (src_quantization->scale()->size() > 0) &&
  180. src_quantization->zero_point() &&
  181. (src_quantization->zero_point()->size() > 0)) {
  182. // Always populate the TfLiteTensor.params field, even if there are
  183. // per-channel quantization parameters.
  184. result->params.scale = src_quantization->scale()->Get(0);
  185. // Note that the zero_point field in the FlatBuffers schema is a 64-bit
  186. // integer, but the zero_point field in the TfLiteQuantizationParams struct
  187. // is a 32-bit integer.
  188. result->params.zero_point =
  189. static_cast<int32_t>(src_quantization->zero_point()->Get(0));
  190. // Populate per-channel quantization params.
  191. int channels = src_quantization->scale()->size();
  192. TfLiteAffineQuantization* quantization =
  193. allocate_temp
  194. ? reinterpret_cast<TfLiteAffineQuantization*>(
  195. non_persistent_buffer_allocator->AllocateTemp(
  196. sizeof(TfLiteAffineQuantization),
  197. alignof(TfLiteAffineQuantization)))
  198. : reinterpret_cast<TfLiteAffineQuantization*>(
  199. persistent_buffer_allocator->AllocatePersistentBuffer(
  200. sizeof(TfLiteAffineQuantization),
  201. alignof(TfLiteAffineQuantization)));
  202. if (quantization == nullptr) {
  203. TF_LITE_REPORT_ERROR(error_reporter,
  204. "Unable to allocate TfLiteAffineQuantization.\n");
  205. return kTfLiteError;
  206. }
  207. // TODO(b/153688719): Reduce tail allocation by using a global zero-point
  208. // buffer. This value can not be reused from the flatbuffer since the
  209. // zero_point is stored as a int64_t.
  210. quantization->zero_point =
  211. allocate_temp
  212. ? reinterpret_cast<TfLiteIntArray*>(
  213. non_persistent_buffer_allocator->AllocateTemp(
  214. TfLiteIntArrayGetSizeInBytes(channels),
  215. alignof(TfLiteIntArray)))
  216. : reinterpret_cast<TfLiteIntArray*>(
  217. persistent_buffer_allocator->AllocatePersistentBuffer(
  218. TfLiteIntArrayGetSizeInBytes(channels),
  219. alignof(TfLiteIntArray)));
  220. if (quantization->zero_point == nullptr) {
  221. TF_LITE_REPORT_ERROR(error_reporter,
  222. "Unable to allocate quantization->zero_point.\n");
  223. return kTfLiteError;
  224. }
  225. quantization->scale =
  226. FlatBufferVectorToTfLiteTypeArray(src_quantization->scale());
  227. quantization->zero_point->size = channels;
  228. int* zero_point_data = quantization->zero_point->data;
  229. for (int i = 0; i < channels; i++) {
  230. // As a space-saving optimization, zero point arrays for weights can be
  231. // reduced to a single value, since all zero points for weights are 0.
  232. zero_point_data[i] = src_quantization->zero_point()->size() ==
  233. src_quantization->scale()->size()
  234. ? src_quantization->zero_point()->Get(i)
  235. : src_quantization->zero_point()->Get(0);
  236. }
  237. // TODO(rocky): Need to add a micro_allocator test case that fails when
  238. // this is not copied:
  239. quantization->quantized_dimension = src_quantization->quantized_dimension();
  240. result->quantization = {kTfLiteAffineQuantization, quantization};
  241. }
  242. return kTfLiteOk;
  243. }
  244. TfLiteStatus InitializeTfLiteEvalTensorFromFlatbuffer(
  245. const tflite::Tensor& flatbuffer_tensor,
  246. const flatbuffers::Vector<flatbuffers::Offset<Buffer>>* buffers,
  247. ErrorReporter* error_reporter, TfLiteEvalTensor* result) {
  248. *result = {};
  249. // Make sure the serialized type is one we know how to deal with, and convert
  250. // it from a flatbuffer enum into a constant used by the kernel C API.
  251. TF_LITE_ENSURE_STATUS(ConvertTensorType(flatbuffer_tensor.type(),
  252. &result->type, error_reporter));
  253. result->data.data = GetFlatbufferTensorBuffer(flatbuffer_tensor, buffers);
  254. if (flatbuffer_tensor.shape() == nullptr) {
  255. // flatbuffer_tensor.shape() can return a nullptr in the case of a scalar
  256. // tensor.
  257. result->dims = const_cast<TfLiteIntArray*>(&kZeroLengthIntArray);
  258. } else {
  259. result->dims = FlatBufferVectorToTfLiteTypeArray(flatbuffer_tensor.shape());
  260. }
  261. return kTfLiteOk;
  262. }
  263. } // namespace internal
  264. size_t MicroAllocator::GetDefaultTailUsage(bool is_memory_planner_given) {
  265. // TODO(b/208703041): a template version of AlignSizeUp to make expression
  266. // shorter.
  267. size_t total_size =
  268. AlignSizeUp(sizeof(SimpleMemoryAllocator),
  269. alignof(SimpleMemoryAllocator)) +
  270. AlignSizeUp(sizeof(MicroAllocator), alignof(MicroAllocator)) +
  271. AlignSizeUp(sizeof(MicroBuiltinDataAllocator),
  272. alignof(MicroBuiltinDataAllocator)) +
  273. AlignSizeUp(sizeof(SubgraphAllocations), alignof(SubgraphAllocations));
  274. if (!is_memory_planner_given) {
  275. total_size +=
  276. AlignSizeUp(sizeof(GreedyMemoryPlanner), alignof(GreedyMemoryPlanner));
  277. }
  278. return total_size;
  279. }
  280. MicroAllocator::MicroAllocator(SimpleMemoryAllocator* memory_allocator,
  281. MicroMemoryPlanner* memory_planner,
  282. ErrorReporter* error_reporter)
  283. : non_persistent_buffer_allocator_(memory_allocator),
  284. persistent_buffer_allocator_(memory_allocator),
  285. memory_planner_(memory_planner),
  286. error_reporter_(error_reporter),
  287. model_is_allocating_(false) {}
  288. MicroAllocator::~MicroAllocator() {}
  289. MicroAllocator* MicroAllocator::Create(uint8_t* tensor_arena, size_t arena_size,
  290. MicroMemoryPlanner* memory_planner,
  291. ErrorReporter* error_reporter) {
  292. uint8_t* aligned_arena =
  293. AlignPointerUp(tensor_arena, MicroArenaBufferAlignment());
  294. size_t aligned_arena_size = tensor_arena + arena_size - aligned_arena;
  295. SimpleMemoryAllocator* memory_allocator = SimpleMemoryAllocator::Create(
  296. error_reporter, aligned_arena, aligned_arena_size);
  297. return Create(memory_allocator, memory_planner, error_reporter);
  298. }
  299. MicroAllocator* MicroAllocator::Create(uint8_t* tensor_arena, size_t arena_size,
  300. ErrorReporter* error_reporter) {
  301. uint8_t* aligned_arena =
  302. AlignPointerUp(tensor_arena, MicroArenaBufferAlignment());
  303. size_t aligned_arena_size = tensor_arena + arena_size - aligned_arena;
  304. SimpleMemoryAllocator* memory_allocator = SimpleMemoryAllocator::Create(
  305. error_reporter, aligned_arena, aligned_arena_size);
  306. // By default create GreedyMemoryPlanner.
  307. // If a different MemoryPlanner is needed, use the other api.
  308. uint8_t* memory_planner_buffer = memory_allocator->AllocatePersistentBuffer(
  309. sizeof(GreedyMemoryPlanner), alignof(GreedyMemoryPlanner));
  310. GreedyMemoryPlanner* memory_planner =
  311. new (memory_planner_buffer) GreedyMemoryPlanner();
  312. return Create(memory_allocator, memory_planner, error_reporter);
  313. }
  314. MicroAllocator* MicroAllocator::Create(SimpleMemoryAllocator* memory_allocator,
  315. MicroMemoryPlanner* memory_planner,
  316. ErrorReporter* error_reporter) {
  317. TFLITE_DCHECK(memory_allocator != nullptr);
  318. TFLITE_DCHECK(error_reporter != nullptr);
  319. TFLITE_DCHECK(memory_planner != nullptr);
  320. uint8_t* allocator_buffer = memory_allocator->AllocatePersistentBuffer(
  321. sizeof(MicroAllocator), alignof(MicroAllocator));
  322. MicroAllocator* allocator = new (allocator_buffer)
  323. MicroAllocator(memory_allocator, memory_planner, error_reporter);
  324. return allocator;
  325. }
  326. SubgraphAllocations* MicroAllocator::StartModelAllocation(const Model* model) {
  327. TFLITE_DCHECK(model != nullptr);
  328. if (model_is_allocating_) {
  329. TF_LITE_REPORT_ERROR(error_reporter_,
  330. "MicroAllocator: Model allocation started before "
  331. "finishing previously allocated model");
  332. return nullptr;
  333. }
  334. model_is_allocating_ = true;
  335. uint8_t* data_allocator_buffer =
  336. persistent_buffer_allocator_->AllocatePersistentBuffer(
  337. sizeof(MicroBuiltinDataAllocator),
  338. alignof(MicroBuiltinDataAllocator));
  339. builtin_data_allocator_ = new (data_allocator_buffer)
  340. MicroBuiltinDataAllocator(persistent_buffer_allocator_);
  341. if (InitScratchBufferData() != kTfLiteOk) {
  342. return nullptr;
  343. }
  344. // Allocate struct to store eval tensors, nodes and registrations.
  345. SubgraphAllocations* output = reinterpret_cast<SubgraphAllocations*>(
  346. persistent_buffer_allocator_->AllocatePersistentBuffer(
  347. sizeof(SubgraphAllocations) * model->subgraphs()->size(),
  348. alignof(SubgraphAllocations)));
  349. if (output == nullptr) {
  350. MicroPrintf("Failed to allocate memory for model metadata.");
  351. return nullptr;
  352. }
  353. if (AllocateTfLiteEvalTensors(model, output) != kTfLiteOk ||
  354. AllocateNodeAndRegistrations(model, output) != kTfLiteOk) {
  355. return nullptr;
  356. }
  357. return output;
  358. }
  359. TfLiteStatus MicroAllocator::FinishModelAllocation(
  360. const Model* model, SubgraphAllocations* subgraph_allocations,
  361. ScratchBufferHandle** scratch_buffer_handles) {
  362. if (!model_is_allocating_) {
  363. TF_LITE_REPORT_ERROR(error_reporter_,
  364. "MicroAllocator: Model allocation finished before "
  365. "starting allocating model");
  366. return kTfLiteError;
  367. }
  368. // Allocate scratch buffer metadata and buffers for variable tensors.
  369. for (size_t subgraph_idx = 0; subgraph_idx < model->subgraphs()->size();
  370. subgraph_idx++) {
  371. const SubGraph* subgraph = model->subgraphs()->Get(subgraph_idx);
  372. TFLITE_DCHECK(subgraph != nullptr);
  373. TF_LITE_ENSURE_STATUS(AllocateScratchBufferHandles(
  374. scratch_buffer_handles, scratch_buffer_request_count_));
  375. TF_LITE_ENSURE_STATUS(AllocateVariables(
  376. subgraph, subgraph_allocations[subgraph_idx].tensors));
  377. }
  378. // Plan all subgraphs and scratch buffers together.
  379. TF_LITE_ENSURE_STATUS(CommitStaticMemoryPlan(model, subgraph_allocations,
  380. *scratch_buffer_handles));
  381. model_is_allocating_ = false;
  382. return kTfLiteOk;
  383. }
  384. void* MicroAllocator::AllocatePersistentBuffer(size_t bytes) {
  385. return persistent_buffer_allocator_->AllocatePersistentBuffer(
  386. bytes, MicroArenaBufferAlignment());
  387. }
  388. TfLiteStatus MicroAllocator::RequestScratchBufferInArena(size_t bytes,
  389. int subgraph_idx,
  390. int* buffer_idx) {
  391. // All scratch buffer requests are stored in the head section of the arena
  392. // when a model is in the prepare phase. First align a scratch buffer request
  393. // pointer to the start of the head:
  394. internal::ScratchBufferRequest* requests = GetScratchBufferRequests();
  395. // Count the number of requested scratch buffers for the current node:
  396. size_t current_node_request_count = 0;
  397. for (size_t i = 0; i < scratch_buffer_request_count_; ++i) {
  398. if (requests[i].node_idx == kUnassignedScratchBufferRequestIndex) {
  399. ++current_node_request_count;
  400. }
  401. }
  402. // First, ensure that the per-kernel request has not exceeded the limit:
  403. if (current_node_request_count >= kMaxScratchBuffersPerOp) {
  404. TF_LITE_REPORT_ERROR(
  405. error_reporter_,
  406. "Scratch buffer request exeeds limit per operator (%d)",
  407. kMaxScratchBuffersPerOp);
  408. return kTfLiteError;
  409. }
  410. // Initialize and assign values for the request at the current index:
  411. internal::ScratchBufferRequest* current_request =
  412. &requests[scratch_buffer_request_count_];
  413. *current_request = {};
  414. // Assign -1 as a sentinel value that will be updated when the node finishes
  415. // allocating:
  416. current_request->bytes = bytes;
  417. current_request->node_idx = kUnassignedScratchBufferRequestIndex;
  418. current_request->subgraph_idx = subgraph_idx;
  419. // Assign the current request index to the out-param:
  420. *buffer_idx = scratch_buffer_request_count_;
  421. // Bump the request count to prepare for the next request:
  422. ++scratch_buffer_request_count_;
  423. return kTfLiteOk;
  424. }
  425. TfLiteStatus MicroAllocator::FinishPrepareNodeAllocations(int node_id) {
  426. // When a node has finished preparing, all temp allocations performed by the
  427. // kernel should be cleaned up:
  428. TF_LITE_ENSURE_STATUS(ResetTempAllocations());
  429. // Find and update any new scratch buffer requests for the current node:
  430. internal::ScratchBufferRequest* requests = GetScratchBufferRequests();
  431. for (size_t i = 0; i < scratch_buffer_request_count_; ++i) {
  432. // A request with a node_idx of -1 is a sentinel value used to indicate this
  433. // was a new request for the current node. The allocator finally knows the
  434. // node index at this point. Assign the value and update the list of new
  435. // requests so the head section can be adjusted to allow for the next kernel
  436. // to allocate at most kMaxScratchBuffersPerOp requests:
  437. if (requests[i].node_idx == kUnassignedScratchBufferRequestIndex) {
  438. requests[i].node_idx = node_id;
  439. }
  440. }
  441. // Ensure that the head is re-adjusted to allow for another at-most
  442. // kMaxScratchBuffersPerOp scratch buffer requests in the next operator:
  443. TF_LITE_ENSURE_STATUS(non_persistent_buffer_allocator_->ResizeBuffer(
  444. scratch_buffer_head_,
  445. sizeof(internal::ScratchBufferRequest) *
  446. (scratch_buffer_request_count_ + kMaxScratchBuffersPerOp),
  447. alignof(internal::ScratchBufferRequest)));
  448. return kTfLiteOk;
  449. }
  450. size_t MicroAllocator::used_bytes() const {
  451. return non_persistent_buffer_allocator_->GetNonPersistentUsedBytes() +
  452. persistent_buffer_allocator_->GetPersistentUsedBytes();
  453. }
  454. TfLiteStatus MicroAllocator::AllocateNodeAndRegistrations(
  455. const Model* model, SubgraphAllocations* subgraph_allocations) {
  456. TFLITE_DCHECK(subgraph_allocations != nullptr);
  457. for (size_t subgraph_idx = 0; subgraph_idx < model->subgraphs()->size();
  458. subgraph_idx++) {
  459. const SubGraph* subgraph = model->subgraphs()->Get(subgraph_idx);
  460. TFLITE_DCHECK(subgraph != nullptr);
  461. uint32_t operators_size = NumSubgraphOperators(subgraph);
  462. // Initialize NodeAndRegistrations for the subgraph.
  463. NodeAndRegistration* output = reinterpret_cast<NodeAndRegistration*>(
  464. persistent_buffer_allocator_->AllocatePersistentBuffer(
  465. sizeof(NodeAndRegistration) * operators_size,
  466. alignof(NodeAndRegistration)));
  467. if (output == nullptr) {
  468. TF_LITE_REPORT_ERROR(
  469. error_reporter_,
  470. "Failed to allocate memory for node_and_registrations.");
  471. return kTfLiteError;
  472. }
  473. subgraph_allocations[subgraph_idx].node_and_registrations = output;
  474. }
  475. return kTfLiteOk;
  476. }
  477. TfLiteTensor* MicroAllocator::AllocatePersistentTfLiteTensor(
  478. const Model* model, const SubgraphAllocations* subgraph_allocations,
  479. int tensor_index, int subgraph_index) {
  480. const SubGraph* subgraph = model->subgraphs()->Get(subgraph_index);
  481. TFLITE_DCHECK(subgraph != nullptr);
  482. // This value is allocated from persistent arena space. It is guaranteed to be
  483. // around for the lifetime of the application.
  484. TfLiteTensor* tensor = AllocatePersistentTfLiteTensorInternal();
  485. // Populate any fields from the flatbuffer, since this TfLiteTensor struct is
  486. // allocated in the persistent section of the arena, ensure that additional
  487. // allocations also take place in that section of the arena.
  488. if (PopulateTfLiteTensorFromFlatbuffer(
  489. model, tensor, tensor_index, subgraph_index,
  490. /*allocate_temp=*/false) != kTfLiteOk) {
  491. TF_LITE_REPORT_ERROR(error_reporter_,
  492. "Failed to populate a persistent TfLiteTensor struct "
  493. "from flatbuffer data!");
  494. return nullptr;
  495. }
  496. if (subgraph_allocations != nullptr) {
  497. // Tensor buffers that are allocated at runtime (e.g. non-weight buffers)
  498. // and not located in the flatbuffer are stored on the pre-allocated list of
  499. // TfLiteEvalTensors structs. These structs are the source of truth, simply
  500. // point the corresponding buffer to the new TfLiteTensor data value.
  501. tensor->data.data =
  502. subgraph_allocations[subgraph_index].tensors[tensor_index].data.data;
  503. // TfLiteEvalTensor structs must also be the source of truth for the
  504. // TfLiteTensor dims.
  505. tensor->dims =
  506. subgraph_allocations[subgraph_index].tensors[tensor_index].dims;
  507. }
  508. return tensor;
  509. }
  510. void MicroAllocator::DeallocateTempTfLiteTensor(TfLiteTensor* tensor) {
  511. TFLITE_DCHECK(tensor != nullptr);
  512. if (tensor->quantization.type == kTfLiteAffineQuantization) {
  513. TFLITE_DCHECK(tensor->quantization.params != nullptr);
  514. TfLiteAffineQuantization* quantization =
  515. reinterpret_cast<TfLiteAffineQuantization*>(
  516. tensor->quantization.params);
  517. non_persistent_buffer_allocator_->DeallocateTemp(
  518. reinterpret_cast<uint8_t*>(quantization->zero_point));
  519. non_persistent_buffer_allocator_->DeallocateTemp(
  520. reinterpret_cast<uint8_t*>(quantization));
  521. }
  522. // Clear the data in case someone still access tensor arena by mistake
  523. tensor->quantization.type = kTfLiteNoQuantization;
  524. tensor->quantization.params = nullptr;
  525. tensor->data.data = nullptr;
  526. tensor->dims = nullptr;
  527. non_persistent_buffer_allocator_->DeallocateTemp(
  528. reinterpret_cast<uint8_t*>(tensor));
  529. }
  530. TfLiteTensor* MicroAllocator::AllocateTempTfLiteTensor(
  531. const Model* model, const SubgraphAllocations* subgraph_allocations,
  532. int tensor_index, int subgraph_index) {
  533. const SubGraph* subgraph = model->subgraphs()->Get(subgraph_index);
  534. TFLITE_DCHECK(subgraph != nullptr);
  535. // This value is allocated from temporary arena space. It is guaranteed to be
  536. // around for at least the scope of the calling function. Since this struct
  537. // allocation takes place in temp space, no need to own or cleanup.
  538. TfLiteTensor* tensor = reinterpret_cast<TfLiteTensor*>(
  539. non_persistent_buffer_allocator_->AllocateTemp(sizeof(TfLiteTensor),
  540. alignof(TfLiteTensor)));
  541. // Populate any fields from the flatbuffer, since this TfLiteTensor struct is
  542. // allocated in the temp section of the arena, ensure that additional
  543. // allocations also take place in that section of the arena.
  544. if (PopulateTfLiteTensorFromFlatbuffer(model, tensor, tensor_index,
  545. subgraph_index,
  546. /*allocate_temp=*/true) != kTfLiteOk) {
  547. TF_LITE_REPORT_ERROR(
  548. error_reporter_,
  549. "Failed to populate a temp TfLiteTensor struct from flatbuffer data!");
  550. return nullptr;
  551. }
  552. if (subgraph_allocations != nullptr) {
  553. // Tensor buffers that are allocated at runtime (e.g. non-weight buffers)
  554. // and not located in the flatbuffer are stored on the pre-allocated list of
  555. // TfLiteEvalTensors structs. These structs are the source of truth, simply
  556. // point the corresponding buffer to the new TfLiteTensor data value.
  557. tensor->data.data =
  558. subgraph_allocations[subgraph_index].tensors[tensor_index].data.data;
  559. // TfLiteEvalTensor structs must also be the source of truth for the
  560. // TfLiteTensor dims.
  561. tensor->dims =
  562. subgraph_allocations[subgraph_index].tensors[tensor_index].dims;
  563. }
  564. return tensor;
  565. }
  566. TfLiteStatus MicroAllocator::ResetTempAllocations() {
  567. return non_persistent_buffer_allocator_->ResetTempAllocations();
  568. }
  569. bool MicroAllocator::IsAllTempDeallocated() {
  570. return non_persistent_buffer_allocator_->IsAllTempDeallocated();
  571. }
  572. TfLiteStatus MicroAllocator::AllocateTfLiteEvalTensors(
  573. const Model* model, SubgraphAllocations* subgraph_allocations) {
  574. TFLITE_DCHECK(subgraph_allocations != nullptr);
  575. for (size_t subgraph_idx = 0; subgraph_idx < model->subgraphs()->size();
  576. subgraph_idx++) {
  577. const SubGraph* subgraph = model->subgraphs()->Get(subgraph_idx);
  578. TFLITE_DCHECK(subgraph != nullptr);
  579. size_t alloc_count = subgraph->tensors()->size();
  580. TfLiteEvalTensor* tensors = reinterpret_cast<TfLiteEvalTensor*>(
  581. persistent_buffer_allocator_->AllocatePersistentBuffer(
  582. sizeof(TfLiteEvalTensor) * alloc_count, alignof(TfLiteEvalTensor)));
  583. if (tensors == nullptr) {
  584. TF_LITE_REPORT_ERROR(
  585. error_reporter_,
  586. "Failed to allocate memory for context->eval_tensors, "
  587. "%d bytes required",
  588. sizeof(TfLiteEvalTensor) * alloc_count);
  589. return kTfLiteError;
  590. }
  591. for (size_t i = 0; i < alloc_count; ++i) {
  592. TfLiteStatus status = internal::InitializeTfLiteEvalTensorFromFlatbuffer(
  593. *subgraph->tensors()->Get(i), model->buffers(), error_reporter_,
  594. &tensors[i]);
  595. if (status != kTfLiteOk) {
  596. TF_LITE_REPORT_ERROR(error_reporter_, "Failed to initialize tensor %d",
  597. i);
  598. return kTfLiteError;
  599. }
  600. }
  601. subgraph_allocations[subgraph_idx].tensors = tensors;
  602. }
  603. return kTfLiteOk;
  604. }
  605. TfLiteStatus MicroAllocator::AllocateVariables(const SubGraph* subgraph,
  606. TfLiteEvalTensor* eval_tensors) {
  607. for (size_t i = 0; i < subgraph->tensors()->size(); ++i) {
  608. auto* tensor = subgraph->tensors()->Get(i);
  609. if (tensor->is_variable()) {
  610. size_t buffer_size;
  611. TF_LITE_ENSURE_STATUS(
  612. TfLiteEvalTensorByteLength(&eval_tensors[i], &buffer_size));
  613. eval_tensors[i].data.data =
  614. persistent_buffer_allocator_->AllocatePersistentBuffer(
  615. buffer_size, MicroArenaBufferAlignment());
  616. if (eval_tensors[i].data.data == nullptr) {
  617. TF_LITE_REPORT_ERROR(error_reporter_,
  618. "Failed to allocate variable tensor of size %d",
  619. buffer_size);
  620. return kTfLiteError;
  621. }
  622. }
  623. }
  624. return kTfLiteOk;
  625. }
  626. TfLiteTensor* MicroAllocator::AllocatePersistentTfLiteTensorInternal() {
  627. return reinterpret_cast<TfLiteTensor*>(
  628. persistent_buffer_allocator_->AllocatePersistentBuffer(
  629. sizeof(TfLiteTensor), alignof(TfLiteTensor)));
  630. }
  631. TfLiteStatus MicroAllocator::PopulateTfLiteTensorFromFlatbuffer(
  632. const Model* model, TfLiteTensor* tensor, int tensor_index,
  633. int subgraph_idx, bool allocate_temp) {
  634. // TODO(b/162311891): This method serves as a stub to ensure quantized
  635. // allocations in the tail can be recorded. Once the interpreter has APIs for
  636. // accessing buffers on TfLiteEvalTensor this method can be dropped.
  637. return internal::InitializeTfLiteTensorFromFlatbuffer(
  638. persistent_buffer_allocator_, non_persistent_buffer_allocator_,
  639. allocate_temp,
  640. *model->subgraphs()->Get(subgraph_idx)->tensors()->Get(tensor_index),
  641. model->buffers(), error_reporter_, tensor);
  642. }
  643. ErrorReporter* MicroAllocator::error_reporter() const {
  644. return error_reporter_;
  645. }
  646. TfLiteStatus MicroAllocator::CommitStaticMemoryPlan(
  647. const Model* model, SubgraphAllocations* allocations,
  648. ScratchBufferHandle* scratch_buffer_handles) {
  649. size_t head_usage = 0;
  650. // Create static memory plan
  651. // 1. Calculate AllocationInfo to know the lifetime of each tensor/buffer.
  652. // 2. Add them into the planner (such as the GreedyMemoryPlanner).
  653. // 3. Static memory planning using the planner.
  654. // 4. Set tensor/buffer pointers based on the offsets from the previous step.
  655. //
  656. // Note that AllocationInfo is only needed for creating the plan. It will be
  657. // allocated from the temp section and cleaned up at the bottom of this
  658. // function.
  659. // Use the AllocationInfoBuilder class to help determine where buffers are
  660. // used in the subgraph.
  661. AllocationInfoBuilder builder(model, non_persistent_buffer_allocator_,
  662. error_reporter_);
  663. TF_LITE_ENSURE_STATUS(
  664. builder.CreateAllocationInfo(scratch_buffer_request_count_));
  665. const int32_t* offline_planner_offsets = nullptr;
  666. TF_LITE_ENSURE_STATUS(
  667. builder.GetOfflinePlannedOffsets(&offline_planner_offsets));
  668. TF_LITE_ENSURE_STATUS(
  669. builder.InitializeAllocationInfo(offline_planner_offsets, allocations));
  670. internal::ScratchBufferRequest* scratch_buffer_requests =
  671. GetScratchBufferRequests();
  672. TF_LITE_ENSURE_STATUS(builder.MarkAllocationLifetimes(
  673. 0, scratch_buffer_requests, scratch_buffer_handles, allocations));
  674. int allocation_info_count = builder.AllocationCount();
  675. AllocationInfo* allocation_info = builder.Finish();
  676. // Remaining arena size that memory planner can use for calculating offsets.
  677. size_t remaining_arena_size =
  678. non_persistent_buffer_allocator_->GetAvailableMemory(
  679. MicroArenaBufferAlignment());
  680. uint8_t* planner_arena = non_persistent_buffer_allocator_->AllocateTemp(
  681. remaining_arena_size, MicroArenaBufferAlignment());
  682. TF_LITE_ENSURE(error_reporter_, planner_arena != nullptr);
  683. memory_planner_->Init(planner_arena, remaining_arena_size);
  684. TF_LITE_ENSURE_STATUS(CreatePlan(error_reporter_, memory_planner_,
  685. allocation_info, allocation_info_count));
  686. // Commit the plan.
  687. TF_LITE_ENSURE_STATUS(
  688. CommitPlan(error_reporter_, memory_planner_,
  689. non_persistent_buffer_allocator_->GetOverlayMemoryAddress(),
  690. allocation_info, allocation_info_count));
  691. // Reset all temp allocations used above:
  692. builder.FreeAllocationInfo();
  693. non_persistent_buffer_allocator_->DeallocateTemp(planner_arena);
  694. TF_LITE_ENSURE_STATUS(
  695. non_persistent_buffer_allocator_->ResetTempAllocations());
  696. TF_LITE_ENSURE_STATUS(
  697. non_persistent_buffer_allocator_->DeallocateResizableBuffer(
  698. scratch_buffer_head_));
  699. #ifdef TF_LITE_SHOW_MEMORY_USE
  700. memory_planner_->PrintMemoryPlan();
  701. #endif
  702. head_usage = memory_planner_->GetMaximumMemorySize();
  703. // The head is used to store memory plans for one model at a time during the
  704. // model preparation stage, and is re-purposed to store scratch buffer handles
  705. // during model invocation. The head must be as large as the greater of the
  706. // largest model memory plan's size and the total space required for all
  707. // scratch buffer handles.
  708. if (max_head_buffer_usage_ < head_usage) {
  709. max_head_buffer_usage_ = head_usage;
  710. }
  711. // The head is used for storing scratch buffer allocations before finalizing a
  712. // memory plan in this function. Ensure that the head is set to the largest
  713. // memory plan sent through the allocator:
  714. TF_LITE_ENSURE_STATUS(
  715. non_persistent_buffer_allocator_->ReserveNonPersistentOverlayMemory(
  716. max_head_buffer_usage_, MicroArenaBufferAlignment()));
  717. return kTfLiteOk;
  718. }
  719. TfLiteStatus MicroAllocator::AllocateScratchBufferHandles(
  720. ScratchBufferHandle** scratch_buffer_handles, size_t handle_count) {
  721. TFLITE_DCHECK(scratch_buffer_handles != nullptr);
  722. if (scratch_buffer_request_count_ == 0) {
  723. // No scratch buffer requests were requested during model allocation.
  724. return kTfLiteOk;
  725. }
  726. // Allocate a consecutive block of memory store the scratch buffer handles.
  727. // This alignment ensures quick lookup during inference time for the model:
  728. *scratch_buffer_handles = reinterpret_cast<ScratchBufferHandle*>(
  729. persistent_buffer_allocator_->AllocatePersistentBuffer(
  730. sizeof(ScratchBufferHandle) * handle_count,
  731. alignof(ScratchBufferHandle)));
  732. return kTfLiteOk;
  733. }
  734. TfLiteStatus MicroAllocator::InitScratchBufferData() {
  735. // A model is preparing to allocate resources, ensure that scratch buffer
  736. // request counter is cleared:
  737. scratch_buffer_request_count_ = 0;
  738. // All requests will be stored in the head section. Each kernel is allowed at
  739. // most kMaxScratchBuffersPerOp requests. Adjust the head to reserve at most
  740. // that many requests to begin:
  741. scratch_buffer_head_ =
  742. non_persistent_buffer_allocator_->AllocateResizableBuffer(
  743. sizeof(internal::ScratchBufferRequest) * kMaxScratchBuffersPerOp,
  744. alignof(internal::ScratchBufferRequest));
  745. if (scratch_buffer_head_ == nullptr) {
  746. return kTfLiteError;
  747. }
  748. return kTfLiteOk;
  749. }
  750. internal::ScratchBufferRequest* MicroAllocator::GetScratchBufferRequests() {
  751. return reinterpret_cast<internal::ScratchBufferRequest*>(AlignPointerUp(
  752. scratch_buffer_head_, alignof(internal::ScratchBufferRequest)));
  753. }
  754. BuiltinDataAllocator* MicroAllocator::GetBuiltinDataAllocator() {
  755. return builtin_data_allocator_;
  756. }
  757. } // namespace tflite