micro_allocator.cc 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  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_op_resolver.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 = 8;
  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. for (size_t i = 0; i < subgraph->inputs()->size(); ++i) {
  184. const int tensor_index = subgraph->inputs()->Get(i);
  185. AllocationInfo* current = &info_[tensor_index];
  186. current->first_created = 0;
  187. }
  188. // Mark all outputs as persistent to the end of the invocation.
  189. for (size_t i = 0; i < subgraph->outputs()->size(); ++i) {
  190. const int tensor_index = subgraph->outputs()->Get(i);
  191. AllocationInfo* current = &info_[tensor_index];
  192. current->last_used = subgraph->operators()->size() - 1;
  193. }
  194. // Figure out when the first and last use of each tensor is.
  195. for (int i = (subgraph->operators()->size() - 1); i >= 0; --i) {
  196. const auto* op = subgraph->operators()->Get(i);
  197. for (size_t n = 0; n < op->inputs()->size(); ++n) {
  198. const int tensor_index = op->inputs()->Get(n);
  199. AllocationInfo* current = &info_[tensor_index];
  200. if (((current->last_used == -1) || (current->last_used < i))) {
  201. current->last_used = i;
  202. }
  203. }
  204. for (size_t n = 0; n < op->outputs()->size(); ++n) {
  205. const int tensor_index = op->outputs()->Get(n);
  206. AllocationInfo* current = &info_[tensor_index];
  207. if ((current->first_created == -1) || (current->first_created > i)) {
  208. current->first_created = i;
  209. }
  210. }
  211. }
  212. // Sanity check for valid tensor lifetime.
  213. for (size_t i = 0; i < tensor_count_; ++i) {
  214. AllocationInfo* current = &info_[i];
  215. // Even though tensor appears to be read only it may still need to be
  216. // allocated.
  217. const bool appears_read_only =
  218. (current->first_created == -1) && (current->last_used != -1);
  219. const bool has_partial_lifetime =
  220. !appears_read_only &&
  221. ((current->first_created == -1) || (current->last_used == -1));
  222. if (has_partial_lifetime && current->needs_allocating) {
  223. TF_LITE_REPORT_ERROR(
  224. reporter_,
  225. "Logic error in memory planner, tensor %d has an invalid lifetime: "
  226. "first_created: %d, last_used: %d",
  227. i, current->first_created, current->last_used);
  228. return kTfLiteError;
  229. }
  230. }
  231. return kTfLiteOk;
  232. }
  233. // The tensor offsets will be encoded in the metadata:[Metadata] field of the
  234. // Model. The following encoding applies:
  235. //
  236. // | Metadata component | Value |
  237. // | name:string | “OfflineMemoryAllocation” |
  238. // | buffer:unit | Index of buffer containing memory allocation data |
  239. //
  240. // The buffer contents for the memory allocation is a list of 32-bit integers.
  241. // The number of tensors, n, must be equal to the number of tensors defined in
  242. // the model. The following encoding applies:
  243. //
  244. // | Offset | Value |
  245. // | 0 | Offline allocation format version – set to 0 |
  246. // | 1 | Subgraph index to which this allocation applies |
  247. // | 2 | Number offsets following: n |
  248. // | 3 | Arena byte offset of tensor #0 or -1 to allocate at runtime |
  249. // | 4 | Arena byte offset of tensor #1 or -1 to allocate at runtime |
  250. // | 3+(n-1) | Arena byte offset of tensor #(n-1) or -1 to allocate at runtime |
  251. TfLiteStatus AllocationInfoBuilder::GetOfflinePlannedOffsets(
  252. const Model* model, const int32_t** offline_planner_offsets) {
  253. if (model->metadata()) {
  254. for (size_t i = 0; i < model->metadata()->size(); ++i) {
  255. auto metadata = model->metadata()->Get(i);
  256. if (strncmp(metadata->name()->c_str(), kOfflineMemAllocMetadata,
  257. strlen(kOfflineMemAllocMetadata)) == 0) {
  258. const flatbuffers::Vector<flatbuffers::Offset<Buffer>>* buffers =
  259. model->buffers();
  260. auto* buffer = (*buffers)[metadata->buffer()];
  261. auto* array = buffer->data();
  262. const uint32_t* metadata_buffer =
  263. reinterpret_cast<const uint32_t*>(array->data());
  264. const size_t nbr_tensors = static_cast<size_t>(metadata_buffer[2]);
  265. *offline_planner_offsets =
  266. reinterpret_cast<const int32_t*>(&metadata_buffer[3]);
  267. if (tensor_count_ != nbr_tensors) {
  268. TF_LITE_REPORT_ERROR(reporter_,
  269. "Nbr of offline buffer offsets (%d) in metadata "
  270. "not equal nbr tensors (%d)\n",
  271. nbr_tensors, tensor_count_);
  272. return kTfLiteError;
  273. }
  274. }
  275. }
  276. }
  277. return kTfLiteOk;
  278. }
  279. TfLiteStatus AllocationInfoBuilder::AddScratchBuffers(
  280. internal::ScratchBufferRequest* scratch_buffer_requests,
  281. ScratchBufferHandle* scratch_buffer_handles) {
  282. // Set up allocation info for buffers.
  283. for (size_t i = tensor_count_; i < tensor_count_ + buffer_count_; ++i) {
  284. internal::ScratchBufferRequest* current_request =
  285. &(scratch_buffer_requests[i - tensor_count_]);
  286. ScratchBufferHandle* current_handle =
  287. &(scratch_buffer_handles[i - tensor_count_]);
  288. AllocationInfo* current = &info_[i];
  289. current->output_ptr = reinterpret_cast<void**>(&current_handle->data);
  290. current->bytes = current_request->bytes;
  291. current->first_created = current_request->node_idx;
  292. current->last_used = current_request->node_idx;
  293. current->offline_offset = kOnlinePlannedBuffer;
  294. current->needs_allocating = true;
  295. }
  296. return kTfLiteOk;
  297. }
  298. TfLiteStatus CreatePlan(ErrorReporter* error_reporter,
  299. GreedyMemoryPlanner* planner,
  300. const AllocationInfo* allocation_info,
  301. size_t allocation_info_size) {
  302. // Add the tensors to our allocation plan.
  303. for (size_t i = 0; i < allocation_info_size; ++i) {
  304. const AllocationInfo* current = &allocation_info[i];
  305. if (current->needs_allocating) {
  306. size_t aligned_bytes_required =
  307. AlignSizeUp(current->bytes, kBufferAlignment);
  308. if (current->offline_offset == kOnlinePlannedBuffer) {
  309. TF_LITE_ENSURE_STATUS(
  310. planner->AddBuffer(error_reporter, aligned_bytes_required,
  311. current->first_created, current->last_used));
  312. } else {
  313. TF_LITE_ENSURE_STATUS(planner->AddBuffer(
  314. error_reporter, aligned_bytes_required, current->first_created,
  315. current->last_used, current->offline_offset));
  316. }
  317. }
  318. }
  319. return kTfLiteOk;
  320. }
  321. TfLiteStatus CommitPlan(ErrorReporter* error_reporter, MemoryPlanner* planner,
  322. uint8_t* starting_point,
  323. const AllocationInfo* allocation_info,
  324. size_t allocation_info_size) {
  325. // Figure out the actual memory addresses for each buffer, based on the plan.
  326. int planner_index = 0;
  327. for (size_t i = 0; i < allocation_info_size; ++i) {
  328. const AllocationInfo* current = &allocation_info[i];
  329. if (current->needs_allocating) {
  330. int offset = -1;
  331. TF_LITE_ENSURE_STATUS(
  332. planner->GetOffsetForBuffer(error_reporter, planner_index, &offset));
  333. *current->output_ptr = reinterpret_cast<void*>(starting_point + offset);
  334. ++planner_index;
  335. }
  336. }
  337. return kTfLiteOk;
  338. }
  339. } // namespace
  340. namespace internal {
  341. // Handles architecture safe mapping of flatbuffer vectors to a TfLite*Array
  342. // struct. Matching types are required (e.g. float and TfLiteFloatArray).
  343. // Big-endian systems will always allocate dimension array data in the tail
  344. // (persistent) section.
  345. template <typename kFlatBufferVectorType, typename kTfLiteArrayType>
  346. TfLiteStatus FlatBufferVectorToTfLiteTypeArray(
  347. SimpleMemoryAllocator* allocator, ErrorReporter* error_reporter,
  348. const flatbuffers::Vector<kFlatBufferVectorType>* flatbuffer_array,
  349. kTfLiteArrayType** result) {
  350. TFLITE_DCHECK(error_reporter != nullptr);
  351. TFLITE_DCHECK(flatbuffer_array != nullptr);
  352. // TODO(b/159668691): Consider adding type assertion or breaking this function
  353. // into multiple functions for each type. std::is_same is c++11 and has a
  354. // special updated constructor in c++17 that requires a string argument.
  355. if (FLATBUFFERS_LITTLEENDIAN) {
  356. // On little-endian machines, TfLite*Array happens to have the same memory
  357. // layout as flatbuffers:Vector<kFlatBufferVectorType>, so we can
  358. // reinterpret_cast the flatbuffer vector and avoid a copy and malloc.
  359. *result = const_cast<kTfLiteArrayType*>(
  360. reinterpret_cast<const kTfLiteArrayType*>(flatbuffer_array));
  361. } else {
  362. // Big-endian architecture can not use the same memory layout as
  363. // flatbuffers::Vector<kFlatBufferVectorType>. Allocate from the tail and
  364. // copy values from the flatbuffer into the newly allocated chunk.
  365. kTfLiteArrayType* array =
  366. reinterpret_cast<kTfLiteArrayType*>(allocator->AllocateFromTail(
  367. TfLiteIntArrayGetSizeInBytes(flatbuffer_array->Length()),
  368. alignof(kTfLiteArrayType)));
  369. if (array == nullptr) {
  370. TF_LITE_REPORT_ERROR(
  371. error_reporter,
  372. "Failed to allocate %d bytes of memory to copy an array.",
  373. TfLiteIntArrayGetSizeInBytes(flatbuffer_array->Length()));
  374. return kTfLiteError;
  375. }
  376. array->size = flatbuffer_array->Length();
  377. for (int i = 0; i < array->size; ++i) {
  378. array->data[i] = flatbuffer_array->Get(i);
  379. }
  380. *result = array;
  381. }
  382. return kTfLiteOk;
  383. }
  384. // Returns a pointer to any buffer associated with the flatbuffer tensor. Can
  385. // return nullptr if no buffer is found.
  386. void* GetFlatbufferTensorBuffer(
  387. const tflite::Tensor& flatbuffer_tensor,
  388. const flatbuffers::Vector<flatbuffers::Offset<Buffer>>* buffers) {
  389. // We need to figure out where the actual contents of this tensor are stored
  390. // in memory. We'll check to see if there's a serialized buffer (pretty much
  391. // the same as a constant op in TensorFlow) associated with this tensor first,
  392. // and if there is update the runtime structure to point to its location in
  393. // memory.
  394. // First see if there's any buffer information in the serialized tensor.
  395. // TODO(b/170379532): Add better unit tests to validate flatbuffer values.
  396. void* out_buffer = nullptr;
  397. if (auto* buffer = (*buffers)[flatbuffer_tensor.buffer()]) {
  398. // If we've found a buffer, does it have any data?
  399. if (auto* array = buffer->data()) {
  400. // If it has any data, is the data size larger than zero?
  401. if (array->size()) {
  402. // We've found a buffer with valid data, so update the runtime tensor
  403. // data structure to point to it.
  404. out_buffer = const_cast<void*>(static_cast<const void*>(array->data()));
  405. }
  406. }
  407. // TODO(petewarden): It's not clear in what circumstances we could have a
  408. // buffer in the serialized tensor, but it doesn't have any data in it. Is
  409. // that a validly-generated file, and if so what does it mean, or is it an
  410. // error condition? It would be good to tighten up the specification to make
  411. // it less ambiguous.
  412. }
  413. return out_buffer;
  414. }
  415. TfLiteStatus InitializeTfLiteTensorFromFlatbuffer(
  416. SimpleMemoryAllocator* allocator, bool allocate_temp,
  417. const tflite::Tensor& flatbuffer_tensor,
  418. const flatbuffers::Vector<flatbuffers::Offset<Buffer>>* buffers,
  419. ErrorReporter* error_reporter, TfLiteTensor* result) {
  420. TFLITE_DCHECK(result != nullptr);
  421. *result = {};
  422. // Make sure the serialized type is one we know how to deal with, and convert
  423. // it from a flatbuffer enum into a constant used by the kernel C API.
  424. TF_LITE_ENSURE_STATUS(ConvertTensorType(flatbuffer_tensor.type(),
  425. &result->type, error_reporter));
  426. // Make sure we remember if the serialized tensor is designated as a variable.
  427. result->is_variable = flatbuffer_tensor.is_variable();
  428. result->data.data = GetFlatbufferTensorBuffer(flatbuffer_tensor, buffers);
  429. // TODO(petewarden): Some of these paths aren't getting enough testing
  430. // coverage, so we should figure out some tests that exercise them.
  431. if (result->data.data == nullptr) {
  432. // The tensor contents haven't been set from a serialized buffer, so
  433. // make a note that they will be allocated from memory. The actual
  434. // allocation won't happen until later.
  435. result->allocation_type = kTfLiteArenaRw;
  436. } else {
  437. // We set the data from a serialized buffer, so record tha.
  438. result->allocation_type = kTfLiteMmapRo;
  439. }
  440. // Figure out what the size in bytes of the buffer is and store it.
  441. size_t type_size;
  442. TF_LITE_ENSURE_STATUS(BytesRequiredForTensor(
  443. flatbuffer_tensor, &result->bytes, &type_size, error_reporter));
  444. if (flatbuffer_tensor.shape() == nullptr) {
  445. // flatbuffer_tensor.shape() can return a nullptr in the case of a scalar
  446. // tensor.
  447. result->dims = const_cast<TfLiteIntArray*>(&kZeroLengthIntArray);
  448. } else {
  449. // TFLM doesn't allow reshaping the tensor which requires dynamic memory
  450. // allocation so it is safe to drop the const qualifier. In the future, if
  451. // we really want to update the tensor shape, we can always pass in a new
  452. // TfLiteIntArray - especially we have to do so if the dimension is
  453. TF_LITE_ENSURE_STATUS(FlatBufferVectorToTfLiteTypeArray(
  454. allocator, error_reporter, flatbuffer_tensor.shape(), &(result->dims)));
  455. }
  456. // Copy the quantization information from the serialized data.
  457. const auto* src_quantization = flatbuffer_tensor.quantization();
  458. if (src_quantization && src_quantization->scale() &&
  459. (src_quantization->scale()->size() > 0) &&
  460. src_quantization->zero_point() &&
  461. (src_quantization->zero_point()->size() > 0)) {
  462. // Always populate the TfLiteTensor.params field, even if there are
  463. // per-channel quantization parameters.
  464. result->params.scale = src_quantization->scale()->Get(0);
  465. // Note that the zero_point field in the FlatBuffers schema is a 64-bit
  466. // integer, but the zero_point field in the TfLiteQuantizationParams struct
  467. // is a 32-bit integer.
  468. result->params.zero_point =
  469. static_cast<int32_t>(src_quantization->zero_point()->Get(0));
  470. // Populate per-channel quantization params.
  471. int channels = src_quantization->scale()->size();
  472. TfLiteAffineQuantization* quantization =
  473. allocate_temp
  474. ? reinterpret_cast<TfLiteAffineQuantization*>(
  475. allocator->AllocateTemp(sizeof(TfLiteAffineQuantization),
  476. alignof(TfLiteAffineQuantization)))
  477. : reinterpret_cast<TfLiteAffineQuantization*>(
  478. allocator->AllocateFromTail(
  479. sizeof(TfLiteAffineQuantization),
  480. alignof(TfLiteAffineQuantization)));
  481. if (quantization == nullptr) {
  482. TF_LITE_REPORT_ERROR(error_reporter,
  483. "Unable to allocate TfLiteAffineQuantization.\n");
  484. return kTfLiteError;
  485. }
  486. // TODO(b/153688719): Reduce tail allocation by using a global zero-point
  487. // buffer. This value can not be reused from the flatbuffer since the
  488. // zero_point is stored as a int64_t.
  489. quantization->zero_point =
  490. allocate_temp
  491. ? reinterpret_cast<TfLiteIntArray*>(allocator->AllocateTemp(
  492. TfLiteIntArrayGetSizeInBytes(channels),
  493. alignof(TfLiteIntArray)))
  494. : reinterpret_cast<TfLiteIntArray*>(allocator->AllocateFromTail(
  495. TfLiteIntArrayGetSizeInBytes(channels),
  496. alignof(TfLiteIntArray)));
  497. if (quantization->zero_point == nullptr) {
  498. TF_LITE_REPORT_ERROR(error_reporter,
  499. "Unable to allocate quantization->zero_point.\n");
  500. return kTfLiteError;
  501. }
  502. TF_LITE_ENSURE_STATUS(FlatBufferVectorToTfLiteTypeArray(
  503. allocator, error_reporter, src_quantization->scale(),
  504. &quantization->scale));
  505. quantization->zero_point->size = channels;
  506. int* zero_point_data = quantization->zero_point->data;
  507. for (int i = 0; i < channels; i++) {
  508. zero_point_data[i] = src_quantization->zero_point()->Get(i);
  509. }
  510. // TODO(rocky): Need to add a micro_allocator test case that fails when
  511. // this is not copied:
  512. quantization->quantized_dimension = src_quantization->quantized_dimension();
  513. result->quantization = {kTfLiteAffineQuantization, quantization};
  514. }
  515. return kTfLiteOk;
  516. }
  517. TfLiteStatus InitializeTfLiteEvalTensorFromFlatbuffer(
  518. SimpleMemoryAllocator* allocator, const tflite::Tensor& flatbuffer_tensor,
  519. const flatbuffers::Vector<flatbuffers::Offset<Buffer>>* buffers,
  520. ErrorReporter* error_reporter, TfLiteEvalTensor* result) {
  521. *result = {};
  522. // Make sure the serialized type is one we know how to deal with, and convert
  523. // it from a flatbuffer enum into a constant used by the kernel C API.
  524. TF_LITE_ENSURE_STATUS(ConvertTensorType(flatbuffer_tensor.type(),
  525. &result->type, error_reporter));
  526. result->data.data = GetFlatbufferTensorBuffer(flatbuffer_tensor, buffers);
  527. if (flatbuffer_tensor.shape() == nullptr) {
  528. // flatbuffer_tensor.shape() can return a nullptr in the case of a scalar
  529. // tensor.
  530. result->dims = const_cast<TfLiteIntArray*>(&kZeroLengthIntArray);
  531. } else {
  532. TF_LITE_ENSURE_STATUS(FlatBufferVectorToTfLiteTypeArray(
  533. allocator, error_reporter, flatbuffer_tensor.shape(), &(result->dims)));
  534. }
  535. return kTfLiteOk;
  536. }
  537. } // namespace internal
  538. MicroAllocator::MicroAllocator(SimpleMemoryAllocator* memory_allocator,
  539. ErrorReporter* error_reporter)
  540. : memory_allocator_(memory_allocator),
  541. error_reporter_(error_reporter),
  542. model_is_allocating_(false) {}
  543. MicroAllocator::~MicroAllocator() {}
  544. MicroAllocator* MicroAllocator::Create(uint8_t* tensor_arena, size_t arena_size,
  545. ErrorReporter* error_reporter) {
  546. uint8_t* aligned_arena = AlignPointerUp(tensor_arena, kBufferAlignment);
  547. size_t aligned_arena_size = tensor_arena + arena_size - aligned_arena;
  548. return Create(SimpleMemoryAllocator::Create(error_reporter, aligned_arena,
  549. aligned_arena_size),
  550. error_reporter);
  551. }
  552. MicroAllocator* MicroAllocator::Create(SimpleMemoryAllocator* memory_allocator,
  553. ErrorReporter* error_reporter) {
  554. TFLITE_DCHECK(memory_allocator != nullptr);
  555. TFLITE_DCHECK(error_reporter != nullptr);
  556. uint8_t* allocator_buffer = memory_allocator->AllocateFromTail(
  557. sizeof(MicroAllocator), alignof(MicroAllocator));
  558. MicroAllocator* allocator =
  559. new (allocator_buffer) MicroAllocator(memory_allocator, error_reporter);
  560. return allocator;
  561. }
  562. TfLiteStatus MicroAllocator::StartModelAllocation(
  563. const Model* model, const MicroOpResolver& op_resolver,
  564. NodeAndRegistration** node_and_registrations,
  565. TfLiteEvalTensor** eval_tensors) {
  566. TFLITE_DCHECK(model != nullptr);
  567. if (model_is_allocating_) {
  568. TF_LITE_REPORT_ERROR(error_reporter_,
  569. "MicroAllocator: Model allocation started before "
  570. "finishing previously allocated model");
  571. return kTfLiteError;
  572. }
  573. model_is_allocating_ = true;
  574. TF_LITE_ENSURE_STATUS(InitScratchBufferData());
  575. TF_LITE_ENSURE_STATUS(AllocateTfLiteEvalTensors(model, eval_tensors));
  576. TF_LITE_ENSURE_STATUS(
  577. AllocateNodeAndRegistrations(model, node_and_registrations));
  578. TF_LITE_ENSURE_STATUS(PrepareNodeAndRegistrationDataFromFlatbuffer(
  579. model, op_resolver, *node_and_registrations));
  580. return kTfLiteOk;
  581. }
  582. TfLiteStatus MicroAllocator::FinishModelAllocation(
  583. const Model* model, TfLiteEvalTensor* eval_tensors,
  584. ScratchBufferHandle** scratch_buffer_handles) {
  585. if (!model_is_allocating_) {
  586. TF_LITE_REPORT_ERROR(error_reporter_,
  587. "MicroAllocator: Model allocation finished before "
  588. "starting allocating model");
  589. return kTfLiteError;
  590. }
  591. const SubGraph* subgraph = GetSubGraphFromModel(model);
  592. TFLITE_DCHECK(subgraph != nullptr);
  593. TF_LITE_ENSURE_STATUS(AllocateScratchBufferHandles(
  594. scratch_buffer_handles, scratch_buffer_request_count_));
  595. TF_LITE_ENSURE_STATUS(CommitStaticMemoryPlan(model, subgraph, eval_tensors,
  596. *scratch_buffer_handles));
  597. TF_LITE_ENSURE_STATUS(AllocateVariables(subgraph, eval_tensors));
  598. model_is_allocating_ = false;
  599. return kTfLiteOk;
  600. }
  601. void* MicroAllocator::AllocatePersistentBuffer(size_t bytes) {
  602. return memory_allocator_->AllocateFromTail(bytes, kBufferAlignment);
  603. }
  604. TfLiteStatus MicroAllocator::RequestScratchBufferInArena(size_t bytes,
  605. int* buffer_idx) {
  606. // All scratch buffer requests are stored in the head section of the arena
  607. // when a model is in the prepare phase. First align a scratch buffer request
  608. // pointer to the start of the head:
  609. internal::ScratchBufferRequest* requests = GetScratchBufferRequests();
  610. // Count the number of requested scratch buffers for the current node:
  611. size_t current_node_request_count = 0;
  612. for (size_t i = 0; i < scratch_buffer_request_count_; ++i) {
  613. if (requests[i].node_idx == kUnassignedScratchBufferRequestIndex) {
  614. ++current_node_request_count;
  615. }
  616. }
  617. // First, ensure that the per-kernel request has not exceeded the limit:
  618. if (current_node_request_count >= kMaxScratchBuffersPerOp) {
  619. TF_LITE_REPORT_ERROR(
  620. error_reporter_,
  621. "Scratch buffer request exeeds limit per operator (%d)",
  622. kMaxScratchBuffersPerOp);
  623. return kTfLiteError;
  624. }
  625. // Initialize and assign values for the request at the current index:
  626. internal::ScratchBufferRequest* current_request =
  627. &requests[scratch_buffer_request_count_];
  628. *current_request = {};
  629. // Assign -1 as a sentinel value that will be updated when the node finishes
  630. // allocating:
  631. current_request->bytes = bytes;
  632. current_request->node_idx = kUnassignedScratchBufferRequestIndex;
  633. // Assign the current request index to the out-param:
  634. *buffer_idx = scratch_buffer_request_count_;
  635. // Bump the request count to prepare for the next request:
  636. ++scratch_buffer_request_count_;
  637. return kTfLiteOk;
  638. }
  639. TfLiteStatus MicroAllocator::FinishPrepareNodeAllocations(int node_id) {
  640. // When a node has finished preparing, all temp allocations performed by the
  641. // kernel should be cleaned up:
  642. ResetTempAllocations();
  643. // Find and update any new scratch buffer requests for the current node:
  644. internal::ScratchBufferRequest* requests = GetScratchBufferRequests();
  645. for (size_t i = 0; i < scratch_buffer_request_count_; ++i) {
  646. // A request with a node_idx of -1 is a sentinel value used to indicate this
  647. // was a new request for the current node. The allocator finally knows the
  648. // node index at this point. Assign the value and update the list of new
  649. // requests so the head section can be adjusted to allow for the next kernel
  650. // to allocate at most kMaxScratchBuffersPerOp requests:
  651. if (requests[i].node_idx == kUnassignedScratchBufferRequestIndex) {
  652. requests[i].node_idx = node_id;
  653. }
  654. }
  655. // Ensure that the head is re-adjusted to allow for another at-most
  656. // kMaxScratchBuffersPerOp scratch buffer requests in the next operator:
  657. TF_LITE_ENSURE_STATUS(memory_allocator_->SetHeadBufferSize(
  658. sizeof(internal::ScratchBufferRequest) *
  659. (scratch_buffer_request_count_ + kMaxScratchBuffersPerOp),
  660. alignof(internal::ScratchBufferRequest)));
  661. return kTfLiteOk;
  662. }
  663. size_t MicroAllocator::used_bytes() const {
  664. return memory_allocator_->GetUsedBytes();
  665. }
  666. TfLiteStatus MicroAllocator::AllocateNodeAndRegistrations(
  667. const Model* model, NodeAndRegistration** node_and_registrations) {
  668. TFLITE_DCHECK(node_and_registrations);
  669. const SubGraph* subgraph = GetSubGraphFromModel(model);
  670. TFLITE_DCHECK(subgraph != nullptr);
  671. NodeAndRegistration* output = reinterpret_cast<NodeAndRegistration*>(
  672. memory_allocator_->AllocateFromTail(
  673. sizeof(NodeAndRegistration) * subgraph->operators()->size(),
  674. alignof(NodeAndRegistration)));
  675. if (output == nullptr) {
  676. TF_LITE_REPORT_ERROR(
  677. error_reporter_,
  678. "Failed to allocate memory for node_and_registrations.");
  679. return kTfLiteError;
  680. }
  681. *node_and_registrations = output;
  682. return kTfLiteOk;
  683. }
  684. TfLiteStatus MicroAllocator::PrepareNodeAndRegistrationDataFromFlatbuffer(
  685. const Model* model, const MicroOpResolver& op_resolver,
  686. NodeAndRegistration* node_and_registrations) {
  687. TFLITE_DCHECK(model != nullptr);
  688. TFLITE_DCHECK(node_and_registrations != nullptr);
  689. const SubGraph* subgraph = GetSubGraphFromModel(model);
  690. TFLITE_DCHECK(subgraph != nullptr);
  691. TfLiteStatus status = kTfLiteOk;
  692. auto* opcodes = model->operator_codes();
  693. MicroBuiltinDataAllocator builtin_data_allocator(memory_allocator_);
  694. for (size_t i = 0; i < subgraph->operators()->size(); ++i) {
  695. const auto* op = subgraph->operators()->Get(i);
  696. const size_t index = op->opcode_index();
  697. if (index >= opcodes->size()) {
  698. TF_LITE_REPORT_ERROR(error_reporter_,
  699. "Missing registration for opcode_index %d\n", index);
  700. return kTfLiteError;
  701. }
  702. auto* opcode = (*opcodes)[index];
  703. status =
  704. GetRegistrationFromOpCode(opcode, op_resolver, error_reporter_,
  705. &(node_and_registrations[i].registration));
  706. if (status != kTfLiteOk) {
  707. TF_LITE_REPORT_ERROR(error_reporter_,
  708. "Failed to get registration from op code %s\n ",
  709. EnumNameBuiltinOperator(GetBuiltinCode(opcode)));
  710. return status;
  711. }
  712. const auto* registration = node_and_registrations[i].registration;
  713. if (registration == nullptr) {
  714. TF_LITE_REPORT_ERROR(error_reporter_, "Skipping op for opcode_index %d\n",
  715. index);
  716. return kTfLiteError;
  717. }
  718. BuiltinOperator op_type =
  719. static_cast<BuiltinOperator>(registration->builtin_code);
  720. const char* custom_data = nullptr;
  721. size_t custom_data_size = 0;
  722. unsigned char* builtin_data = nullptr;
  723. if (op_type == BuiltinOperator_CUSTOM) {
  724. // Custom Ops may or may not have a non-null custom_options field.
  725. if (op->custom_options() != nullptr) {
  726. custom_data =
  727. reinterpret_cast<const char*>(op->custom_options()->data());
  728. custom_data_size = op->custom_options()->size();
  729. }
  730. } else {
  731. if (op->custom_options() != nullptr) {
  732. TF_LITE_REPORT_ERROR(
  733. error_reporter_,
  734. "Unsupported behavior: found builtin operator %s with custom "
  735. "options.\n",
  736. EnumNameBuiltinOperator(op_type));
  737. return kTfLiteError;
  738. }
  739. MicroOpResolver::BuiltinParseFunction parser =
  740. op_resolver.GetOpDataParser(op_type);
  741. if (parser == nullptr) {
  742. TF_LITE_REPORT_ERROR(error_reporter_, "Did not find a parser for %s",
  743. EnumNameBuiltinOperator(op_type));
  744. return kTfLiteError;
  745. }
  746. TF_LITE_ENSURE_STATUS(parser(op, error_reporter_, &builtin_data_allocator,
  747. (void**)(&builtin_data)));
  748. }
  749. TfLiteIntArray* inputs_array;
  750. TF_LITE_ENSURE_STATUS(internal::FlatBufferVectorToTfLiteTypeArray(
  751. memory_allocator_, error_reporter_, op->inputs(), &inputs_array));
  752. TfLiteIntArray* outputs_array;
  753. TF_LITE_ENSURE_STATUS(internal::FlatBufferVectorToTfLiteTypeArray(
  754. memory_allocator_, error_reporter_, op->outputs(), &outputs_array));
  755. TfLiteNode* node = &(node_and_registrations[i].node);
  756. *node = {};
  757. node->inputs = inputs_array;
  758. node->outputs = outputs_array;
  759. node->builtin_data = reinterpret_cast<void*>(builtin_data);
  760. node->custom_initial_data = custom_data;
  761. node->custom_initial_data_size = custom_data_size;
  762. }
  763. return kTfLiteOk;
  764. }
  765. TfLiteTensor* MicroAllocator::AllocatePersistentTfLiteTensor(
  766. const Model* model, TfLiteEvalTensor* eval_tensors, int tensor_index) {
  767. const SubGraph* subgraph = GetSubGraphFromModel(model);
  768. TFLITE_DCHECK(subgraph != nullptr);
  769. // This value is allocated from persistent arena space. It is guaranteed to be
  770. // around for the lifetime of the application.
  771. TfLiteTensor* tensor =
  772. AllocatePersistentTfLiteTensorInternal(model, eval_tensors, tensor_index);
  773. // Populate any fields from the flatbuffer, since this TfLiteTensor struct is
  774. // allocated in the persistent section of the arena, ensure that additional
  775. // allocations also take place in that section of the arena.
  776. if (PopulateTfLiteTensorFromFlatbuffer(model, subgraph, tensor, tensor_index,
  777. /*allocate_temp=*/false) !=
  778. kTfLiteOk) {
  779. TF_LITE_REPORT_ERROR(error_reporter_,
  780. "Failed to populate a persistent TfLiteTensor struct "
  781. "from flatbuffer data!");
  782. return nullptr;
  783. }
  784. if (eval_tensors != nullptr) {
  785. // Tensor buffers that are allocated at runtime (e.g. non-weight buffers)
  786. // and not located in the flatbuffer are stored on the pre-allocated list of
  787. // TfLiteEvalTensors structs. These structs are the source of truth, simply
  788. // point the corresponding buffer to the new TfLiteTensor data value.
  789. tensor->data.data = eval_tensors[tensor_index].data.data;
  790. }
  791. return tensor;
  792. }
  793. TfLiteTensor* MicroAllocator::AllocateTempTfLiteTensor(
  794. const Model* model, TfLiteEvalTensor* eval_tensors, int tensor_index) {
  795. const SubGraph* subgraph = GetSubGraphFromModel(model);
  796. TFLITE_DCHECK(subgraph != nullptr);
  797. // This value is allocated from temporary arena space. It is guaranteed to be
  798. // around for at least the scope of the calling function. Since this struct
  799. // allocation takes place in temp space, no need to own or cleanup.
  800. TfLiteTensor* tensor =
  801. reinterpret_cast<TfLiteTensor*>(memory_allocator_->AllocateTemp(
  802. sizeof(TfLiteTensor), alignof(TfLiteTensor)));
  803. // Populate any fields from the flatbuffer, since this TfLiteTensor struct is
  804. // allocated in the temp section of the arena, ensure that additional
  805. // allocations also take place in that section of the arena.
  806. if (PopulateTfLiteTensorFromFlatbuffer(model, subgraph, tensor, tensor_index,
  807. /*allocate_temp=*/true) != kTfLiteOk) {
  808. TF_LITE_REPORT_ERROR(
  809. error_reporter_,
  810. "Failed to populate a temp TfLiteTensor struct from flatbuffer data!");
  811. return nullptr;
  812. }
  813. if (eval_tensors != nullptr) {
  814. // Tensor buffers that are allocated at runtime (e.g. non-weight buffers)
  815. // and not located in the flatbuffer are stored on the pre-allocated list of
  816. // TfLiteEvalTensors structs. These structs are the source of truth, simply
  817. // point the corresponding buffer to the new TfLiteTensor data value.
  818. tensor->data.data = eval_tensors[tensor_index].data.data;
  819. }
  820. return tensor;
  821. }
  822. void MicroAllocator::ResetTempAllocations() {
  823. memory_allocator_->ResetTempAllocations();
  824. }
  825. TfLiteStatus MicroAllocator::AllocateTfLiteEvalTensors(
  826. const Model* model, TfLiteEvalTensor** eval_tensors) {
  827. TFLITE_DCHECK(eval_tensors != nullptr);
  828. const SubGraph* subgraph = GetSubGraphFromModel(model);
  829. TFLITE_DCHECK(subgraph != nullptr);
  830. size_t alloc_count = subgraph->tensors()->size();
  831. TfLiteEvalTensor* tensors =
  832. reinterpret_cast<TfLiteEvalTensor*>(memory_allocator_->AllocateFromTail(
  833. sizeof(TfLiteEvalTensor) * alloc_count, alignof(TfLiteEvalTensor)));
  834. if (tensors == nullptr) {
  835. TF_LITE_REPORT_ERROR(error_reporter_,
  836. "Failed to allocate memory for context->eval_tensors, "
  837. "%d bytes required",
  838. sizeof(TfLiteEvalTensor) * alloc_count);
  839. return kTfLiteError;
  840. }
  841. for (size_t i = 0; i < alloc_count; ++i) {
  842. TfLiteStatus status = internal::InitializeTfLiteEvalTensorFromFlatbuffer(
  843. memory_allocator_, *subgraph->tensors()->Get(i), model->buffers(),
  844. error_reporter_, &tensors[i]);
  845. if (status != kTfLiteOk) {
  846. TF_LITE_REPORT_ERROR(error_reporter_, "Failed to initialize tensor %d",
  847. i);
  848. return kTfLiteError;
  849. }
  850. }
  851. *eval_tensors = tensors;
  852. return kTfLiteOk;
  853. }
  854. TfLiteStatus MicroAllocator::AllocateVariables(const SubGraph* subgraph,
  855. TfLiteEvalTensor* eval_tensors) {
  856. for (size_t i = 0; i < subgraph->tensors()->size(); ++i) {
  857. auto* tensor = subgraph->tensors()->Get(i);
  858. if (tensor->is_variable()) {
  859. size_t buffer_size;
  860. TF_LITE_ENSURE_STATUS(
  861. TfLiteEvalTensorByteLength(&eval_tensors[i], &buffer_size));
  862. eval_tensors[i].data.data =
  863. memory_allocator_->AllocateFromTail(buffer_size, kBufferAlignment);
  864. if (eval_tensors[i].data.data == nullptr) {
  865. TF_LITE_REPORT_ERROR(error_reporter_,
  866. "Failed to allocate variable tensor of size %d",
  867. buffer_size);
  868. return kTfLiteError;
  869. }
  870. }
  871. }
  872. return kTfLiteOk;
  873. }
  874. TfLiteTensor* MicroAllocator::AllocatePersistentTfLiteTensorInternal(
  875. const Model* model, TfLiteEvalTensor* eval_tensors, int tensor_index) {
  876. return reinterpret_cast<TfLiteTensor*>(memory_allocator_->AllocateFromTail(
  877. sizeof(TfLiteTensor), alignof(TfLiteTensor)));
  878. }
  879. TfLiteStatus MicroAllocator::PopulateTfLiteTensorFromFlatbuffer(
  880. const Model* model, const SubGraph* subgraph, TfLiteTensor* tensor,
  881. int tensor_index, bool allocate_temp) {
  882. // TODO(b/162311891): This method serves as a stub to ensure quantized
  883. // allocations in the tail can be recorded. Once the interpreter has APIs for
  884. // accessing buffers on TfLiteEvalTensor this method can be dropped.
  885. return internal::InitializeTfLiteTensorFromFlatbuffer(
  886. memory_allocator_, allocate_temp, *subgraph->tensors()->Get(tensor_index),
  887. model->buffers(), error_reporter_, tensor);
  888. }
  889. ErrorReporter* MicroAllocator::error_reporter() const {
  890. return error_reporter_;
  891. }
  892. const SubGraph* MicroAllocator::GetSubGraphFromModel(const Model* model) {
  893. auto* subgraphs = model->subgraphs();
  894. if (subgraphs->size() != 1) {
  895. TF_LITE_REPORT_ERROR(error_reporter_,
  896. "Only 1 subgraph is currently supported.\n");
  897. return nullptr;
  898. }
  899. return (*subgraphs)[0];
  900. }
  901. TfLiteStatus MicroAllocator::CommitStaticMemoryPlan(
  902. const Model* model, const SubGraph* subgraph,
  903. TfLiteEvalTensor* eval_tensors,
  904. ScratchBufferHandle* scratch_buffer_handles) {
  905. size_t head_usage = 0;
  906. // Create static memory plan
  907. // 1. Calculate AllocationInfo to know the lifetime of each tensor/buffer.
  908. // 2. Add them into the planner (such as the GreedyMemoryPlanner).
  909. // 3. Static memory planning using the planner.
  910. // 4. Set tensor/buffer pointers based on the offsets from the previous step.
  911. //
  912. // Note that AllocationInfo is only needed for creating the plan. It will be
  913. // allocated from the temp section and cleaned up at the bottom of this
  914. // function.
  915. size_t allocation_info_count =
  916. subgraph->tensors()->size() + scratch_buffer_request_count_;
  917. size_t bytes = sizeof(AllocationInfo) * allocation_info_count;
  918. // Allocate an array of AllocationInfo structs from the temp section. This
  919. // struct will be used by AllocationInfoBuilder to find buffer usage.
  920. AllocationInfo* allocation_info = reinterpret_cast<AllocationInfo*>(
  921. memory_allocator_->AllocateTemp(bytes, alignof(AllocationInfo)));
  922. if (allocation_info == nullptr) {
  923. TF_LITE_REPORT_ERROR(
  924. error_reporter_,
  925. "Failed to allocate memory for allocation_info, %d bytes required",
  926. bytes);
  927. return kTfLiteError;
  928. }
  929. // Use the AllocationInfoBuilder class to help determine where buffers are
  930. // used in the subgraph.
  931. AllocationInfoBuilder builder(allocation_info, subgraph->tensors()->size(),
  932. scratch_buffer_request_count_, error_reporter_);
  933. const int32_t* offline_planner_offsets = nullptr;
  934. TF_LITE_ENSURE_STATUS(
  935. builder.GetOfflinePlannedOffsets(model, &offline_planner_offsets));
  936. TF_LITE_ENSURE_STATUS(
  937. builder.AddTensors(subgraph, offline_planner_offsets, eval_tensors));
  938. internal::ScratchBufferRequest* scratch_buffer_requests =
  939. GetScratchBufferRequests();
  940. TF_LITE_ENSURE_STATUS(builder.AddScratchBuffers(scratch_buffer_requests,
  941. scratch_buffer_handles));
  942. // Remaining arena size that memory planner can use for calculating offsets.
  943. size_t remaining_arena_size =
  944. memory_allocator_->GetAvailableMemory(kBufferAlignment);
  945. uint8_t* planner_arena =
  946. memory_allocator_->AllocateTemp(remaining_arena_size, kBufferAlignment);
  947. TF_LITE_ENSURE(error_reporter_, planner_arena != nullptr);
  948. GreedyMemoryPlanner planner(planner_arena, remaining_arena_size);
  949. TF_LITE_ENSURE_STATUS(CreatePlan(error_reporter_, &planner, allocation_info,
  950. allocation_info_count));
  951. // Reset all temp allocations used above:
  952. memory_allocator_->ResetTempAllocations();
  953. size_t actual_available_arena_size =
  954. memory_allocator_->GetAvailableMemory(kBufferAlignment);
  955. // Make sure we have enough arena size.
  956. if (planner.GetMaximumMemorySize() > actual_available_arena_size) {
  957. TF_LITE_REPORT_ERROR(
  958. error_reporter_,
  959. "Arena size is too small for all buffers. Needed %u but only "
  960. "%u was available.",
  961. planner.GetMaximumMemorySize(), actual_available_arena_size);
  962. return kTfLiteError;
  963. }
  964. // Commit the plan.
  965. TF_LITE_ENSURE_STATUS(CommitPlan(error_reporter_, &planner,
  966. memory_allocator_->GetHeadBuffer(),
  967. allocation_info, allocation_info_count));
  968. head_usage = planner.GetMaximumMemorySize();
  969. // The head is used to store memory plans for one model at a time during the
  970. // model preparation stage, and is re-purposed to store scratch buffer handles
  971. // during model invocation. The head must be as large as the greater of the
  972. // largest model memory plan's size and the total space required for all
  973. // scratch buffer handles.
  974. if (max_head_buffer_usage_ < head_usage) {
  975. max_head_buffer_usage_ = head_usage;
  976. }
  977. // The head is used for storing scratch buffer allocations before finalizing a
  978. // memory plan in this function. Ensure that the head is set to the largest
  979. // memory plan sent through the allocator:
  980. TF_LITE_ENSURE_STATUS(memory_allocator_->SetHeadBufferSize(
  981. max_head_buffer_usage_, kBufferAlignment));
  982. return kTfLiteOk;
  983. }
  984. TfLiteStatus MicroAllocator::AllocateScratchBufferHandles(
  985. ScratchBufferHandle** scratch_buffer_handles, size_t handle_count) {
  986. TFLITE_DCHECK(scratch_buffer_handles != nullptr);
  987. if (scratch_buffer_request_count_ == 0) {
  988. // No scratch buffer requests were requested during model allocation.
  989. return kTfLiteOk;
  990. }
  991. // Allocate a consecutive block of memory store the scratch buffer handles.
  992. // This alignment ensures quick lookup during inference time for the model:
  993. *scratch_buffer_handles = reinterpret_cast<ScratchBufferHandle*>(
  994. memory_allocator_->AllocateFromTail(
  995. sizeof(ScratchBufferHandle) * handle_count,
  996. alignof(ScratchBufferHandle)));
  997. return kTfLiteOk;
  998. }
  999. TfLiteStatus MicroAllocator::InitScratchBufferData() {
  1000. // A model is preparing to allocate resources, ensure that scratch buffer
  1001. // request counter is cleared:
  1002. scratch_buffer_request_count_ = 0;
  1003. // All requests will be stored in the head section. Each kernel is allowed at
  1004. // most kMaxScratchBuffersPerOp requests. Adjust the head to reserve at most
  1005. // that many requests to begin:
  1006. TF_LITE_ENSURE_STATUS(memory_allocator_->SetHeadBufferSize(
  1007. sizeof(internal::ScratchBufferRequest) * kMaxScratchBuffersPerOp,
  1008. alignof(internal::ScratchBufferRequest)));
  1009. return kTfLiteOk;
  1010. }
  1011. internal::ScratchBufferRequest* MicroAllocator::GetScratchBufferRequests() {
  1012. return reinterpret_cast<internal::ScratchBufferRequest*>(
  1013. AlignPointerUp(memory_allocator_->GetHeadBuffer(),
  1014. alignof(internal::ScratchBufferRequest)));
  1015. }
  1016. } // namespace tflite