micro_allocator.cc 44 KB

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