micro_allocator.cc 42 KB

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