micro_allocator.cc 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. ==============================================================================*/
  12. #include "tensorflow/lite/micro/micro_allocator.h"
  13. #include <cstddef>
  14. #include <cstdint>
  15. #include "tensorflow/lite/c/common.h"
  16. #include "tensorflow/lite/core/api/error_reporter.h"
  17. #include "tensorflow/lite/core/api/flatbuffer_conversions.h"
  18. #include "tensorflow/lite/core/api/op_resolver.h"
  19. #include "tensorflow/lite/core/api/tensor_utils.h"
  20. #include "tensorflow/lite/micro/compatibility.h"
  21. #include "tensorflow/lite/micro/memory_helpers.h"
  22. #include "tensorflow/lite/micro/memory_planner/greedy_memory_planner.h"
  23. #include "tensorflow/lite/micro/simple_memory_allocator.h"
  24. namespace tflite {
  25. namespace {
  26. // Used to hold information used during allocation calculations.
  27. struct AllocationInfo {
  28. size_t bytes;
  29. int first_created;
  30. int last_used;
  31. bool needs_allocating;
  32. void** output_ptr;
  33. };
  34. // We align tensor buffers to 16-byte boundaries, since this is a common
  35. // requirement for SIMD extensions.
  36. constexpr int kBufferAlignment = 16;
  37. class MicroBuiltinDataAllocator : public BuiltinDataAllocator {
  38. public:
  39. explicit MicroBuiltinDataAllocator(SimpleMemoryAllocator* memory_allocator)
  40. : memory_allocator_(memory_allocator) {}
  41. void* Allocate(size_t size, size_t alignment_hint) override {
  42. return memory_allocator_->AllocateFromTail(size, alignment_hint);
  43. }
  44. void Deallocate(void* data) override {
  45. // Do not deallocate, builtin data needs to be available for the life time
  46. // of the model.
  47. }
  48. private:
  49. SimpleMemoryAllocator* memory_allocator_;
  50. TF_LITE_REMOVE_VIRTUAL_DELETE
  51. };
  52. TfLiteStatus AllocateVariables(
  53. const flatbuffers::Vector<flatbuffers::Offset<Tensor>>* flatbuffer_tensors,
  54. TfLiteTensor* runtime_tensors, SimpleMemoryAllocator* allocator) {
  55. for (size_t i = 0; i < flatbuffer_tensors->size(); ++i) {
  56. if (flatbuffer_tensors->Get(i)->is_variable()) {
  57. runtime_tensors[i].data.data = allocator->AllocateFromTail(
  58. runtime_tensors[i].bytes, kBufferAlignment);
  59. // Allocation failure.
  60. if (runtime_tensors[i].data.data == nullptr) {
  61. return kTfLiteError;
  62. }
  63. }
  64. tflite::ResetVariableTensor(&(runtime_tensors[i]));
  65. }
  66. return kTfLiteOk;
  67. }
  68. // A helper class to construct AllocationInfo array. This array contains the
  69. // lifetime of tensors / scratch_buffer and will be used to calculate the memory
  70. // plan. Methods need to be called in order from `Init`, `Add*`, to `Finish`.
  71. class AllocationInfoBuilder {
  72. public:
  73. AllocationInfoBuilder(ErrorReporter* reporter,
  74. SimpleMemoryAllocator* allocator)
  75. : reporter_(reporter), allocator_(allocator) {}
  76. // Initializes the builder by allocating AllocationInfo array from the
  77. // simple memory allocator.
  78. TfLiteStatus Init(size_t tensor_count, size_t scratch_buffer_count) {
  79. tensor_count_ = tensor_count;
  80. buffer_count_ = scratch_buffer_count;
  81. return Allocate();
  82. }
  83. // Add allocaiton information for the tensors.
  84. TfLiteStatus AddTensors(const SubGraph* subgraph,
  85. TfLiteTensor* runtime_tensors);
  86. // Add allocation information for the scratch buffers.
  87. TfLiteStatus AddScratchBuffers(internal::ScratchBufferHandle* buffer_handles);
  88. // Returns a pointer to the built AllocationInfo array.
  89. const AllocationInfo* Finish() const { return info_; }
  90. size_t Size() const { return tensor_count_ + buffer_count_; }
  91. private:
  92. // Allocate the output AllocationInfo array from the allocator_;
  93. TfLiteStatus Allocate();
  94. ErrorReporter* reporter_ = nullptr;
  95. SimpleMemoryAllocator* allocator_ = nullptr;
  96. size_t tensor_count_ = 0;
  97. size_t buffer_count_ = 0;
  98. AllocationInfo* info_ = nullptr;
  99. };
  100. TfLiteStatus AllocationInfoBuilder::Allocate() {
  101. size_t bytes = sizeof(AllocationInfo) * Size();
  102. info_ = reinterpret_cast<AllocationInfo*>(
  103. allocator_->AllocateFromTail(bytes, alignof(AllocationInfo)));
  104. if (info_ == nullptr) {
  105. TF_LITE_REPORT_ERROR(
  106. reporter_,
  107. "Failed to allocate memory for allocation_info, %d bytes required",
  108. bytes);
  109. return kTfLiteError;
  110. }
  111. return kTfLiteOk;
  112. }
  113. TfLiteStatus AllocationInfoBuilder::AddTensors(const SubGraph* subgraph,
  114. TfLiteTensor* runtime_tensors) {
  115. // Set up allocation info for all tensors.
  116. for (size_t i = 0; i < tensor_count_; ++i) {
  117. AllocationInfo* current = &info_[i];
  118. // TfLiteTensor.uint8 field is deprecated so use .data field instead.
  119. current->output_ptr = &(runtime_tensors[i].data.data);
  120. current->bytes = runtime_tensors[i].bytes;
  121. current->first_created = -1;
  122. current->last_used = -1;
  123. current->needs_allocating = (runtime_tensors[i].data.data == nullptr) &&
  124. (!subgraph->tensors()->Get(i)->is_variable());
  125. }
  126. for (size_t i = 0; i < subgraph->inputs()->size(); ++i) {
  127. const int tensor_index = subgraph->inputs()->Get(i);
  128. AllocationInfo* current = &info_[tensor_index];
  129. current->first_created = 0;
  130. }
  131. // Mark all outputs as persistent to the end of the invocation.
  132. for (size_t i = 0; i < subgraph->outputs()->size(); ++i) {
  133. const int tensor_index = subgraph->outputs()->Get(i);
  134. AllocationInfo* current = &info_[tensor_index];
  135. current->last_used = subgraph->operators()->size() - 1;
  136. }
  137. // Figure out when the first and last use of each tensor is.
  138. for (int i = (subgraph->operators()->size() - 1); i >= 0; --i) {
  139. const auto* op = subgraph->operators()->Get(i);
  140. for (size_t n = 0; n < op->inputs()->size(); ++n) {
  141. const int tensor_index = op->inputs()->Get(n);
  142. AllocationInfo* current = &info_[tensor_index];
  143. if (((current->last_used == -1) || (current->last_used < i))) {
  144. current->last_used = i;
  145. }
  146. }
  147. for (size_t n = 0; n < op->outputs()->size(); ++n) {
  148. const int tensor_index = op->outputs()->Get(n);
  149. AllocationInfo* current = &info_[tensor_index];
  150. if ((current->first_created == -1) || (current->first_created > i)) {
  151. current->first_created = i;
  152. }
  153. }
  154. }
  155. // Work out which tensors need to be allocated.
  156. for (size_t i = 0; i < tensor_count_; ++i) {
  157. AllocationInfo* current = &info_[i];
  158. const bool is_read_only =
  159. (current->first_created == -1) && (current->last_used != -1);
  160. if (is_read_only) {
  161. current->needs_allocating = false;
  162. }
  163. const bool has_partial_lifetime =
  164. !is_read_only &&
  165. ((current->first_created == -1) || (current->last_used == -1));
  166. if (has_partial_lifetime && current->needs_allocating) {
  167. TF_LITE_REPORT_ERROR(
  168. reporter_,
  169. "Logic error in memory planner, tensor %d has an invalid lifetime: "
  170. "first_created: %d, last_used: %d",
  171. i, current->first_created, current->last_used);
  172. return kTfLiteError;
  173. }
  174. }
  175. return kTfLiteOk;
  176. }
  177. TfLiteStatus AllocationInfoBuilder::AddScratchBuffers(
  178. internal::ScratchBufferHandle* buffer_handles) {
  179. // Set up allocation info for buffers.
  180. for (size_t i = tensor_count_; i < tensor_count_ + buffer_count_; ++i) {
  181. AllocationInfo* current = &info_[i];
  182. internal::ScratchBufferHandle* handle =
  183. &(buffer_handles[i - tensor_count_]);
  184. current->output_ptr = reinterpret_cast<void**>(&handle->data);
  185. current->bytes = handle->bytes;
  186. current->first_created = handle->node_idx;
  187. current->last_used = handle->node_idx;
  188. current->needs_allocating = true;
  189. }
  190. return kTfLiteOk;
  191. }
  192. TfLiteStatus CreatePlan(ErrorReporter* error_reporter, MemoryPlanner* planner,
  193. const AllocationInfo* allocation_info,
  194. size_t allocation_info_size) {
  195. // Add the tensors to our allocation plan.
  196. for (size_t i = 0; i < allocation_info_size; ++i) {
  197. const AllocationInfo* current = &allocation_info[i];
  198. if (current->needs_allocating) {
  199. size_t aligned_bytes_required =
  200. AlignSizeUp(current->bytes, kBufferAlignment);
  201. TF_LITE_ENSURE_STATUS(
  202. planner->AddBuffer(error_reporter, aligned_bytes_required,
  203. current->first_created, current->last_used));
  204. }
  205. }
  206. return kTfLiteOk;
  207. }
  208. TfLiteStatus CommitPlan(ErrorReporter* error_reporter, MemoryPlanner* planner,
  209. uint8_t* starting_point,
  210. const AllocationInfo* allocation_info,
  211. size_t allocation_info_size) {
  212. // Figure out the actual memory addresses for each buffer, based on the plan.
  213. int planner_index = 0;
  214. for (size_t i = 0; i < allocation_info_size; ++i) {
  215. const AllocationInfo* current = &allocation_info[i];
  216. if (current->needs_allocating) {
  217. int offset = -1;
  218. TF_LITE_ENSURE_STATUS(
  219. planner->GetOffsetForBuffer(error_reporter, planner_index, &offset));
  220. *current->output_ptr = reinterpret_cast<void*>(starting_point + offset);
  221. ++planner_index;
  222. }
  223. }
  224. return kTfLiteOk;
  225. }
  226. } // namespace
  227. namespace internal {
  228. TfLiteStatus InitializeRuntimeTensor(
  229. SimpleMemoryAllocator* allocator, const tflite::Tensor& flatbuffer_tensor,
  230. const flatbuffers::Vector<flatbuffers::Offset<Buffer>>* buffers,
  231. ErrorReporter* error_reporter, TfLiteTensor* result) {
  232. *result = {};
  233. // Make sure the serialized type is one we know how to deal with, and convert
  234. // it from a flatbuffer enum into a constant used by the kernel C API.
  235. TF_LITE_ENSURE_STATUS(ConvertTensorType(flatbuffer_tensor.type(),
  236. &result->type, error_reporter));
  237. // Make sure we remember if the serialized tensor is designated as a variable.
  238. result->is_variable = flatbuffer_tensor.is_variable();
  239. // We need to figure out where the actual contents of this tensor are stored
  240. // in memory. We'll check to see if there's a serialized buffer (pretty much
  241. // the same as a constant op in TensorFlow) associated with this tensor first,
  242. // and if there is update the runtime structure to point to its location in
  243. // memory.
  244. // First see if there's any buffer information in the serialized tensor.
  245. if (auto* buffer = (*buffers)[flatbuffer_tensor.buffer()]) {
  246. // If we've found a buffer, does it have any data?
  247. if (auto* array = buffer->data()) {
  248. // If it has any data, is the data size larger than zero?
  249. if (array->size()) {
  250. // We've found a buffer with valid data, so update the runtime tensor
  251. // data structure to point to it.
  252. result->data.data =
  253. const_cast<void*>(static_cast<const void*>(array->data()));
  254. // We set the data from a serialized buffer, so record tha.
  255. result->allocation_type = kTfLiteMmapRo;
  256. }
  257. }
  258. // TODO(petewarden): It's not clear in what circumstances we could have a
  259. // buffer in the serialized tensor, but it doesn't have any data in it. Is
  260. // that a validly-generated file, and if so what does it mean, or is it an
  261. // error condition? It would be good to tighten up the specification to make
  262. // it less ambiguous.
  263. }
  264. // TODO(petewarden): Some of these paths aren't getting enough testing
  265. // coverage, so we should figure out some tests that exercise them.
  266. if (result->data.data == nullptr) {
  267. // The tensor contents haven't been set from a serialized buffer, so
  268. // make a note that they will be allocated from memory. The actual
  269. // allocation won't happen until later.
  270. result->allocation_type = kTfLiteArenaRw;
  271. }
  272. // Figure out what the size in bytes of the buffer is and store it.
  273. size_t type_size;
  274. TF_LITE_ENSURE_STATUS(BytesRequiredForTensor(
  275. flatbuffer_tensor, &result->bytes, &type_size, error_reporter));
  276. // TFLM doesn't allow reshaping the tensor which requires dynamic memory
  277. // allocation so it is safe to drop the const qualifier. In the future, if we
  278. // really want to update the tensor shape, we can always pass in a new
  279. // TfLiteIntArray - especially we have to do so if the dimension is changed.
  280. result->dims = const_cast<TfLiteIntArray*>(
  281. reinterpret_cast<const TfLiteIntArray*>(flatbuffer_tensor.shape()));
  282. // Copy the quantization information from the serialized data.
  283. const auto* src_quantization = flatbuffer_tensor.quantization();
  284. if (src_quantization && src_quantization->scale() &&
  285. (src_quantization->scale()->size() > 0) &&
  286. src_quantization->zero_point() &&
  287. (src_quantization->zero_point()->size() > 0)) {
  288. // Always populate the TfLiteTensor.params field, even if there are
  289. // per-channel quantization parameters.
  290. result->params.scale = src_quantization->scale()->Get(0);
  291. // Note that the zero_point field in the FlatBuffers schema is a 64-bit
  292. // integer, but the zero_point field in the TfLiteQuantizationParams struct
  293. // is a 32-bit integer.
  294. result->params.zero_point =
  295. static_cast<int32_t>(src_quantization->zero_point()->Get(0));
  296. // Populate per-channel quantization params.
  297. int channels = src_quantization->scale()->size();
  298. TfLiteAffineQuantization* quantization =
  299. reinterpret_cast<TfLiteAffineQuantization*>(
  300. allocator->AllocateFromTail(sizeof(TfLiteAffineQuantization),
  301. alignof(TfLiteAffineQuantization)));
  302. if (quantization == nullptr) {
  303. TF_LITE_REPORT_ERROR(error_reporter,
  304. "Unable to allocate TfLiteAffineQuantization.\n");
  305. return kTfLiteError;
  306. }
  307. quantization->zero_point =
  308. reinterpret_cast<TfLiteIntArray*>(allocator->AllocateFromTail(
  309. TfLiteIntArrayGetSizeInBytes(channels), alignof(TfLiteIntArray)));
  310. if (quantization->zero_point == nullptr) {
  311. TF_LITE_REPORT_ERROR(error_reporter,
  312. "Unable to allocate quantization->zero_point.\n");
  313. return kTfLiteError;
  314. }
  315. quantization->scale = reinterpret_cast<TfLiteFloatArray*>(
  316. allocator->AllocateFromTail(TfLiteFloatArrayGetSizeInBytes(channels),
  317. alignof(TfLiteFloatArray)));
  318. if (quantization->scale == nullptr) {
  319. TF_LITE_REPORT_ERROR(error_reporter,
  320. "Unable to allocate quantization->scale.\n");
  321. return kTfLiteError;
  322. }
  323. quantization->zero_point->size = channels;
  324. quantization->scale->size = channels;
  325. int* zero_point_data = quantization->zero_point->data;
  326. float* scale_data = quantization->scale->data;
  327. for (int i = 0; i < channels; i++) {
  328. zero_point_data[i] = src_quantization->zero_point()->Get(i);
  329. scale_data[i] = src_quantization->scale()->Get(i);
  330. }
  331. // TODO(rocky): Need to add a micro_allocator test case that fails when
  332. // this is not copied:
  333. quantization->quantized_dimension = src_quantization->quantized_dimension();
  334. result->quantization = {kTfLiteAffineQuantization, quantization};
  335. }
  336. if (flatbuffer_tensor.name() != nullptr) {
  337. result->name = flatbuffer_tensor.name()->c_str();
  338. }
  339. return kTfLiteOk;
  340. }
  341. } // namespace internal
  342. TfLiteStatus MicroAllocator::Init() {
  343. auto* subgraphs = model_->subgraphs();
  344. if (subgraphs->size() != 1) {
  345. TF_LITE_REPORT_ERROR(error_reporter_,
  346. "Only 1 subgraph is currently supported.\n");
  347. return kTfLiteError;
  348. }
  349. subgraph_ = (*subgraphs)[0];
  350. tensors_ = subgraph_->tensors();
  351. operators_ = subgraph_->operators();
  352. context_->tensors_size = tensors_->size();
  353. context_->tensors =
  354. reinterpret_cast<TfLiteTensor*>(memory_allocator_->AllocateFromTail(
  355. sizeof(TfLiteTensor) * context_->tensors_size,
  356. alignof(TfLiteTensor)));
  357. if (context_->tensors == nullptr) {
  358. TF_LITE_REPORT_ERROR(
  359. error_reporter_,
  360. "Failed to allocate memory for context->tensors, %d bytes required",
  361. sizeof(TfLiteTensor) * context_->tensors_size);
  362. return kTfLiteError;
  363. }
  364. // Initialize runtime tensors in context_ using the flatbuffer.
  365. for (size_t i = 0; i < tensors_->size(); ++i) {
  366. TfLiteStatus status = internal::InitializeRuntimeTensor(
  367. memory_allocator_, *tensors_->Get(i), model_->buffers(),
  368. error_reporter_, &context_->tensors[i]);
  369. if (status != kTfLiteOk) {
  370. TF_LITE_REPORT_ERROR(error_reporter_, "Failed to initialize tensor %d",
  371. i);
  372. return kTfLiteError;
  373. }
  374. }
  375. return kTfLiteOk;
  376. }
  377. MicroAllocator::MicroAllocator(TfLiteContext* context, const Model* model,
  378. uint8_t* tensor_arena, size_t arena_size,
  379. ErrorReporter* error_reporter)
  380. : model_(model), error_reporter_(error_reporter), context_(context) {
  381. uint8_t* aligned_arena = AlignPointerUp(tensor_arena, kBufferAlignment);
  382. if (aligned_arena != tensor_arena) {
  383. TF_LITE_REPORT_ERROR(
  384. error_reporter_,
  385. "%d bytes lost due to alignment. To avoid this loss, please make sure "
  386. "the tensor_arena is 16 bytes aligned.",
  387. aligned_arena - tensor_arena);
  388. }
  389. size_t aligned_arena_size = tensor_arena + arena_size - aligned_arena;
  390. // Creates a root memory allocator managing the arena. The allocator itself
  391. // also locates in the arena buffer. This allocator doesn't need to be
  392. // destructed as it's the root allocator.
  393. memory_allocator_ = CreateInPlaceSimpleMemoryAllocator(
  394. error_reporter, aligned_arena, aligned_arena_size);
  395. TfLiteStatus status = Init();
  396. // TODO(b/147871299): Consider improving this code. A better way of handling
  397. // failures in the constructor is to have a static function that returns a
  398. // pointer to the class. If allocation failed, a nullptr will be returned.
  399. if (status != kTfLiteOk) {
  400. TF_LITE_REPORT_ERROR(error_reporter_,
  401. "MicroAllocator: Failed to initialize.");
  402. active_ = false;
  403. } else {
  404. active_ = true;
  405. }
  406. }
  407. TfLiteStatus MicroAllocator::AllocateNodeAndRegistrations(
  408. const OpResolver& op_resolver,
  409. NodeAndRegistration** node_and_registrations) {
  410. if (!active_) {
  411. return kTfLiteError;
  412. }
  413. auto* output = reinterpret_cast<NodeAndRegistration*>(
  414. memory_allocator_->AllocateFromTail(
  415. sizeof(NodeAndRegistration) * operators_->size(),
  416. alignof(NodeAndRegistration)));
  417. if (output == nullptr) {
  418. TF_LITE_REPORT_ERROR(
  419. error_reporter_,
  420. "Failed to allocate memory for node_and_registrations.");
  421. return kTfLiteError;
  422. }
  423. TfLiteStatus status = kTfLiteOk;
  424. auto* opcodes = model_->operator_codes();
  425. MicroBuiltinDataAllocator builtin_data_allocator(memory_allocator_);
  426. for (size_t i = 0; i < operators_->size(); ++i) {
  427. const auto* op = operators_->Get(i);
  428. size_t index = op->opcode_index();
  429. if (index >= opcodes->size()) {
  430. TF_LITE_REPORT_ERROR(error_reporter_,
  431. "Missing registration for opcode_index %d\n", index);
  432. return kTfLiteError;
  433. }
  434. auto* opcode = (*opcodes)[index];
  435. status = GetRegistrationFromOpCode(opcode, op_resolver, error_reporter_,
  436. &(output[i].registration));
  437. if (status != kTfLiteOk) {
  438. TF_LITE_REPORT_ERROR(error_reporter_,
  439. "Failed to get registration from op code %s\n ",
  440. EnumNameBuiltinOperator(opcode->builtin_code()));
  441. return status;
  442. }
  443. const auto* registration = output[i].registration;
  444. if (registration == nullptr) {
  445. TF_LITE_REPORT_ERROR(error_reporter_, "Skipping op for opcode_index %d\n",
  446. index);
  447. return kTfLiteError;
  448. }
  449. BuiltinOperator op_type =
  450. static_cast<BuiltinOperator>(registration->builtin_code);
  451. if (op_type != BuiltinOperator_CUSTOM && op->custom_options()) {
  452. TF_LITE_REPORT_ERROR(
  453. error_reporter_,
  454. "Unsupported behavior: found builtin operator %s with custom "
  455. "options.\n",
  456. EnumNameBuiltinOperator(op_type));
  457. return kTfLiteError;
  458. }
  459. const char* custom_data = nullptr;
  460. size_t custom_data_size = 0;
  461. unsigned char* builtin_data = nullptr;
  462. if (op->custom_options()) {
  463. custom_data = reinterpret_cast<const char*>(op->custom_options()->data());
  464. custom_data_size = op->custom_options()->size();
  465. } else {
  466. TF_LITE_ENSURE_STATUS(ParseOpData(op, op_type, error_reporter_,
  467. &builtin_data_allocator,
  468. (void**)(&builtin_data)));
  469. }
  470. // Disregard const qualifier to workaround with existing API.
  471. TfLiteIntArray* inputs_array = const_cast<TfLiteIntArray*>(
  472. reinterpret_cast<const TfLiteIntArray*>(op->inputs()));
  473. TfLiteIntArray* outputs_array = const_cast<TfLiteIntArray*>(
  474. reinterpret_cast<const TfLiteIntArray*>(op->outputs()));
  475. TfLiteNode* node = &(output[i].node);
  476. *node = {};
  477. node->inputs = inputs_array;
  478. node->outputs = outputs_array;
  479. node->builtin_data = reinterpret_cast<void*>(builtin_data);
  480. node->custom_initial_data = custom_data;
  481. node->custom_initial_data_size = custom_data_size;
  482. }
  483. *node_and_registrations = output;
  484. return kTfLiteOk;
  485. }
  486. TfLiteStatus MicroAllocator::FinishTensorAllocation() {
  487. if (!active_) {
  488. return kTfLiteError;
  489. }
  490. // Create static memory plan
  491. // 1. Calculate AllocationInfo to know the lifetime of each tensor/buffer.
  492. // 2. Add them into the planner (such as the GreedyMemoryPlanner).
  493. // 3. Static memory planning using the planner.
  494. // 4. Set tensor/buffer pointers based on the offsets from the previous step.
  495. // Note that AllocationInfo is only needed for creating the plan. It will be
  496. // thrown away when the child allocator (tmp_allocator) goes out of scope.
  497. {
  498. SimpleMemoryAllocator tmp_allocator(error_reporter_,
  499. memory_allocator_->GetHead(),
  500. memory_allocator_->GetTail());
  501. AllocationInfoBuilder builder(error_reporter_, &tmp_allocator);
  502. TF_LITE_ENSURE_STATUS(
  503. builder.Init(tensors_->size(), scratch_buffer_count_));
  504. TF_LITE_ENSURE_STATUS(builder.AddTensors(subgraph_, context_->tensors));
  505. TF_LITE_ENSURE_STATUS(builder.AddScratchBuffers(scratch_buffer_handles_));
  506. const AllocationInfo* allocation_info = builder.Finish();
  507. // Remaining arena size that memory planner can use for calculating offsets.
  508. size_t remaining_arena_size = tmp_allocator.GetAvailableMemory();
  509. uint8_t* planner_arena =
  510. tmp_allocator.AllocateFromHead(remaining_arena_size, /*alignment=*/1);
  511. TF_LITE_ENSURE(error_reporter_, planner_arena != nullptr);
  512. GreedyMemoryPlanner planner(planner_arena, remaining_arena_size);
  513. TF_LITE_ENSURE_STATUS(
  514. CreatePlan(error_reporter_, &planner, allocation_info, builder.Size()));
  515. size_t actual_available_arena_size =
  516. memory_allocator_->GetAvailableMemory();
  517. // Make sure we have enough arena size.
  518. if (planner.GetMaximumMemorySize() > actual_available_arena_size) {
  519. TF_LITE_REPORT_ERROR(
  520. error_reporter_,
  521. "Arena size is too small for activation buffers. Needed %d but only "
  522. "%d was available.",
  523. planner.GetMaximumMemorySize(), actual_available_arena_size);
  524. return kTfLiteError;
  525. }
  526. // Commit the plan.
  527. TF_LITE_ENSURE_STATUS(CommitPlan(error_reporter_, &planner,
  528. memory_allocator_->GetHead(),
  529. allocation_info, builder.Size()));
  530. // Allocate the planned area, so the allocator knows it's used.
  531. uint8_t* allocated_tensor_memory =
  532. memory_allocator_->AllocateFromHead(planner.GetMaximumMemorySize(),
  533. /*alignment=*/1);
  534. TF_LITE_ENSURE(error_reporter_, allocated_tensor_memory != nullptr);
  535. }
  536. // Data in variables need to be kept for the next invocation so allocating
  537. // them from the tail (persistent area).
  538. if (AllocateVariables(tensors_, context_->tensors, memory_allocator_) !=
  539. kTfLiteOk) {
  540. TF_LITE_REPORT_ERROR(
  541. error_reporter_,
  542. "Failed to allocate variables. Please increase arena size.");
  543. return kTfLiteError;
  544. }
  545. active_ = false;
  546. return kTfLiteOk;
  547. }
  548. TfLiteStatus MicroAllocator::AllocatePersistentBuffer(size_t bytes,
  549. void** ptr) {
  550. uint8_t* data = memory_allocator_->AllocateFromTail(bytes, kBufferAlignment);
  551. if (data == nullptr) {
  552. TF_LITE_REPORT_ERROR(error_reporter_,
  553. "Failed to allocate persistent buffer of size %d",
  554. bytes);
  555. return kTfLiteError;
  556. }
  557. (*ptr) = data;
  558. return kTfLiteOk;
  559. }
  560. TfLiteStatus MicroAllocator::RequestScratchBufferInArena(int node_id,
  561. size_t bytes,
  562. int* buffer_idx) {
  563. // A sanity check to make sure scratch_buffer_handles_ is contiguous i.e.
  564. // scratch_buffer_handles_ is pointing to the last allocation from memory
  565. // allocator.
  566. if (scratch_buffer_handles_ != nullptr &&
  567. reinterpret_cast<uint8_t*>(scratch_buffer_handles_) !=
  568. memory_allocator_->GetTail()) {
  569. TF_LITE_REPORT_ERROR(error_reporter_,
  570. "Internal error: AllocateFromTail can not be called "
  571. "between two RequestScratchBufferInArena calls.");
  572. return kTfLiteError;
  573. }
  574. internal::ScratchBufferHandle* handle =
  575. reinterpret_cast<internal::ScratchBufferHandle*>(
  576. memory_allocator_->AllocateFromTail(
  577. sizeof(internal::ScratchBufferHandle),
  578. alignof(internal::ScratchBufferHandle)));
  579. if (handle == nullptr) {
  580. TF_LITE_REPORT_ERROR(error_reporter_,
  581. "Failed to register scratch buffer handle for node %s",
  582. node_id);
  583. return kTfLiteError;
  584. }
  585. *handle = {};
  586. handle->bytes = bytes;
  587. handle->node_idx = node_id;
  588. *buffer_idx = scratch_buffer_count_;
  589. scratch_buffer_count_ += 1;
  590. // scratch_buffer_handles_ is in reverse order. The following code ensures
  591. // that scratch_buffers[0] is pointing to the newly allocated handle.
  592. scratch_buffer_handles_ = handle;
  593. return kTfLiteOk;
  594. }
  595. void* MicroAllocator::GetScratchBuffer(int buffer_idx) const {
  596. if (static_cast<size_t>(buffer_idx) >= scratch_buffer_count_) {
  597. TF_LITE_REPORT_ERROR(error_reporter_,
  598. "Buffer %d not found. %d buffers available.",
  599. buffer_idx, scratch_buffer_count_);
  600. return nullptr;
  601. }
  602. // scratch_buffer_handles_ is in reverse order.
  603. return scratch_buffer_handles_[scratch_buffer_count_ - buffer_idx - 1].data;
  604. }
  605. } // namespace tflite