micro_allocation_info.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. /* Copyright 2022 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_allocation_info.h"
  13. #include "tensorflow/lite/c/c_api_types.h"
  14. #include "tensorflow/lite/kernels/internal/compatibility.h"
  15. #include "tensorflow/lite/micro/memory_helpers.h"
  16. #include "tensorflow/lite/micro/memory_planner/greedy_memory_planner.h"
  17. namespace tflite {
  18. namespace {
  19. constexpr char kOfflineMemAllocMetadata[] = "OfflineMemoryAllocation";
  20. constexpr int kUninitializedLifetime = -1;
  21. } // namespace
  22. // Mark the given Allocation info as first created at the specified allocation
  23. // scope count. Only the first creation must be recorded since the allocation
  24. // scope count monotonically increases throughout the lifetime marking process.
  25. void AllocationInfoBuilder::UpdateFirstCreated(AllocationInfo* current,
  26. int allocation_scope_count) {
  27. TFLITE_DCHECK(current->first_created <= allocation_scope_count);
  28. if (current->first_created == kUninitializedLifetime) {
  29. current->first_created = allocation_scope_count;
  30. }
  31. }
  32. // Mark the given AllocationInfo as last used at the specified allocation scope
  33. // count. Update the last used marker every time, since the allocation scope
  34. // count monotonically increases through the lifetime marking process.
  35. void AllocationInfoBuilder::UpdateLastUsed(AllocationInfo* current,
  36. int allocation_scope_count) {
  37. TFLITE_DCHECK(current->last_used <= allocation_scope_count);
  38. current->last_used = allocation_scope_count;
  39. }
  40. TfLiteStatus AllocationInfoBuilder::MarkSubgraphLifetimesIfNecessary(
  41. const Operator* op, internal::ScratchBufferRequest* scratch_buffer_requests,
  42. ScratchBufferHandle* scratch_buffer_handles,
  43. SubgraphAllocations* allocations) {
  44. int first_subgraph_index = -1;
  45. int second_subgraph_index = -1;
  46. const OperatorCode* opcode =
  47. model_->operator_codes()->Get(op->opcode_index());
  48. switch (opcode->builtin_code()) {
  49. case BuiltinOperator_IF: {
  50. first_subgraph_index =
  51. op->builtin_options_as_IfOptions()->then_subgraph_index();
  52. second_subgraph_index =
  53. op->builtin_options_as_IfOptions()->else_subgraph_index();
  54. break;
  55. }
  56. case BuiltinOperator_CALL_ONCE: {
  57. first_subgraph_index =
  58. op->builtin_options_as_CallOnceOptions()->init_subgraph_index();
  59. break;
  60. }
  61. case BuiltinOperator_WHILE: {
  62. first_subgraph_index =
  63. op->builtin_options_as_WhileOptions()->cond_subgraph_index();
  64. second_subgraph_index =
  65. op->builtin_options_as_WhileOptions()->body_subgraph_index();
  66. break;
  67. }
  68. default: {
  69. break;
  70. }
  71. }
  72. if (first_subgraph_index != -1) {
  73. // Enter a new allocation scope for each subgraph.
  74. allocation_scope_count_++;
  75. TF_LITE_ENSURE_STATUS(
  76. MarkAllocationLifetimes(first_subgraph_index, scratch_buffer_requests,
  77. scratch_buffer_handles, allocations));
  78. }
  79. if (second_subgraph_index != -1) {
  80. // Enter a new allocation scope for each subgraph.
  81. allocation_scope_count_++;
  82. TF_LITE_ENSURE_STATUS(
  83. MarkAllocationLifetimes(second_subgraph_index, scratch_buffer_requests,
  84. scratch_buffer_handles, allocations));
  85. }
  86. return kTfLiteOk;
  87. }
  88. TfLiteStatus AllocationInfoBuilder::CreateAllocationInfo(
  89. int scratch_buffer_request_count) {
  90. size_t subgraph_offsets_length = model_->subgraphs()->size() * sizeof(size_t);
  91. info_.subgraph_offsets =
  92. reinterpret_cast<size_t*>(non_persistent_allocator_->AllocateTemp(
  93. subgraph_offsets_length, alignof(size_t)));
  94. if (info_.subgraph_offsets == nullptr) {
  95. TF_LITE_REPORT_ERROR(
  96. reporter_,
  97. "Failed to allocate memory for memory planning, %d bytes required",
  98. subgraph_offsets_length);
  99. return kTfLiteError;
  100. }
  101. size_t tensor_count = 0;
  102. for (size_t subgraph_idx = 0; subgraph_idx < model_->subgraphs()->size();
  103. subgraph_idx++) {
  104. // Add all tensors in each subgraph to the AllocationInfo array. Even weight
  105. // tensors are added but marked with needs_allocating = false. Including all
  106. // tensors in the graph here simplifies logic.
  107. info_.subgraph_offsets[subgraph_idx] = tensor_count;
  108. tensor_count += model_->subgraphs()->Get(subgraph_idx)->tensors()->size();
  109. }
  110. info_.tensor_count = tensor_count;
  111. // Scratch buffer allocations follow tensor allocations, so the scratch offset
  112. // is equal to the number of tensor allocations.
  113. info_.scratch_offset = tensor_count;
  114. info_.allocation_info_count = tensor_count + scratch_buffer_request_count;
  115. info_.scratch_buffer_count = scratch_buffer_request_count;
  116. size_t bytes = sizeof(AllocationInfo) * info_.allocation_info_count;
  117. // Allocate an array of AllocationInfo structs from the temp section. This
  118. // struct will be used by AllocationInfoBuilder to find buffer usage.
  119. info_.allocation_info = reinterpret_cast<AllocationInfo*>(
  120. non_persistent_allocator_->AllocateTemp(bytes, alignof(AllocationInfo)));
  121. if (info_.allocation_info == nullptr) {
  122. TF_LITE_REPORT_ERROR(
  123. reporter_,
  124. "Failed to allocate memory for memory planning, %d bytes required",
  125. bytes);
  126. return kTfLiteError;
  127. }
  128. return kTfLiteOk;
  129. }
  130. TfLiteStatus AllocationInfoBuilder::FreeAllocationInfo() {
  131. non_persistent_allocator_->DeallocateTemp(
  132. reinterpret_cast<uint8_t*>(info_.allocation_info));
  133. non_persistent_allocator_->DeallocateTemp(
  134. reinterpret_cast<uint8_t*>(info_.subgraph_offsets));
  135. return kTfLiteOk;
  136. }
  137. TfLiteStatus AllocationInfoBuilder::InitializeAllocationInfo(
  138. const int32_t* offline_offsets, SubgraphAllocations* allocations) {
  139. AllocationInfo* allocation_info = info_.allocation_info;
  140. // Initialize allocation info for every tensor in every subgraph.
  141. for (size_t subgraph_idx = 0; subgraph_idx < model_->subgraphs()->size();
  142. subgraph_idx++) {
  143. const SubGraph* subgraph = model_->subgraphs()->Get(subgraph_idx);
  144. TfLiteEvalTensor* eval_tensors = allocations[subgraph_idx].tensors;
  145. AllocationInfo* subgraph_allocation_info =
  146. &allocation_info[info_.subgraph_offsets[subgraph_idx]];
  147. for (size_t i = 0; i < subgraph->tensors()->size(); ++i) {
  148. AllocationInfo* current = &subgraph_allocation_info[i];
  149. current->output_ptr = &(eval_tensors[i].data.data);
  150. TF_LITE_ENSURE_STATUS(
  151. TfLiteEvalTensorByteLength(&eval_tensors[i], &current->bytes));
  152. current->first_created = kUninitializedLifetime;
  153. current->last_used = kUninitializedLifetime;
  154. current->needs_allocating = (eval_tensors[i].data.data == nullptr) &&
  155. (!subgraph->tensors()->Get(i)->is_variable());
  156. if (offline_offsets) {
  157. current->offline_offset = offline_offsets[i];
  158. } else {
  159. current->offline_offset = kOnlinePlannedBuffer;
  160. }
  161. }
  162. }
  163. // Initialize allocation info for every scratch buffer.
  164. AllocationInfo* scratch_allocation_info =
  165. &allocation_info[info_.scratch_offset];
  166. for (size_t i = 0; i < info_.scratch_buffer_count; i++) {
  167. AllocationInfo* current = &scratch_allocation_info[i];
  168. current->first_created = -1;
  169. current->last_used = -1;
  170. current->needs_allocating = true;
  171. current->offline_offset = kOnlinePlannedBuffer;
  172. }
  173. return kTfLiteOk;
  174. }
  175. TfLiteStatus AllocationInfoBuilder::MarkAllocationLifetimes(
  176. int subgraph_idx, internal::ScratchBufferRequest* scratch_buffer_requests,
  177. ScratchBufferHandle* scratch_buffer_handles,
  178. SubgraphAllocations* allocations) {
  179. const SubGraph* subgraph = model_->subgraphs()->Get(subgraph_idx);
  180. AllocationInfo* allocation_info = info_.allocation_info;
  181. // Each subgraph's tensor allocations are in a contiguous block starting at
  182. // subgraph_offsets_[subgraph index] with one entry per tensor.
  183. AllocationInfo* subgraph_allocation_info =
  184. &allocation_info[info_.subgraph_offsets[subgraph_idx]];
  185. uint32_t operators_size = NumSubgraphOperators(subgraph);
  186. // Mark all inputs as created at the start of the subgraph invocation.
  187. for (size_t i = 0;
  188. subgraph->inputs() != nullptr && i < subgraph->inputs()->size(); ++i) {
  189. const int tensor_index = subgraph->inputs()->Get(i);
  190. AllocationInfo* current = &subgraph_allocation_info[tensor_index];
  191. UpdateFirstCreated(current, allocation_scope_count_);
  192. }
  193. for (uint32_t i = 0; i < operators_size; i++) {
  194. // Each operator has a new allocation scope.
  195. allocation_scope_count_++;
  196. const auto* op = subgraph->operators()->Get(i);
  197. // Figure out when the first creation and use of each tensor is.
  198. for (size_t n = 0; op->outputs() != nullptr && n < op->outputs()->size();
  199. ++n) {
  200. const int tensor_index = op->outputs()->Get(n);
  201. AllocationInfo* current = &subgraph_allocation_info[tensor_index];
  202. UpdateFirstCreated(current, allocation_scope_count_);
  203. }
  204. // Keep track of scope count before any subgraphs, so that scratch buffers'
  205. // lifetime within a control flow op properly overlaps with all subgraphs.
  206. int start_allocation_scope_count = allocation_scope_count_;
  207. // Control flow operators can invoke subgraphs. Plan these subgraphs
  208. // before continuing on to the rest of the graph.
  209. MarkSubgraphLifetimesIfNecessary(op, scratch_buffer_requests,
  210. scratch_buffer_handles, allocations);
  211. // Figure out when the last use of each tensor is.
  212. for (size_t n = 0; op->inputs() != nullptr && n < op->inputs()->size();
  213. ++n) {
  214. const int tensor_index = op->inputs()->Get(n);
  215. // Optional bias tensors can have an index of -1 when they are omitted.
  216. if (tensor_index >= 0) {
  217. AllocationInfo* current = &subgraph_allocation_info[tensor_index];
  218. // No need to update creation since it is either marked by the subgraph
  219. // or producer op, or it is not part of the memory plan (weight, bias
  220. // tensor).
  221. UpdateLastUsed(current, allocation_scope_count_);
  222. }
  223. }
  224. for (size_t n = 0; op->outputs() != nullptr && n < op->outputs()->size();
  225. ++n) {
  226. const int tensor_index = op->outputs()->Get(n);
  227. AllocationInfo* current = &subgraph_allocation_info[tensor_index];
  228. UpdateLastUsed(current, allocation_scope_count_);
  229. }
  230. // Mark thse lifetime of scratch buffers belonging to the current node. This
  231. // operation is O(N * M) where N is the total number of visited nodes and M
  232. // is the total number of scratch buffers.
  233. // TODO(b/217794030): Optimize this memory planning code.
  234. AllocationInfo* scratch_allocation_info =
  235. &allocation_info[info_.scratch_offset];
  236. for (size_t scratch_idx = 0; scratch_idx < info_.scratch_buffer_count;
  237. scratch_idx++) {
  238. internal::ScratchBufferRequest request =
  239. scratch_buffer_requests[scratch_idx];
  240. AllocationInfo* current = &scratch_allocation_info[scratch_idx];
  241. if (request.node_idx == static_cast<int>(i) &&
  242. request.subgraph_idx == static_cast<int>(subgraph_idx)) {
  243. ScratchBufferHandle* current_handle =
  244. &(scratch_buffer_handles[scratch_idx]);
  245. current->output_ptr = reinterpret_cast<void**>(&current_handle->data);
  246. current->bytes = request.bytes;
  247. UpdateFirstCreated(current, start_allocation_scope_count);
  248. UpdateLastUsed(current, allocation_scope_count_);
  249. }
  250. }
  251. }
  252. // Mark all outputs as persistent to the end of the subgraph invocation.
  253. for (size_t i = 0;
  254. subgraph->outputs() != nullptr && i < subgraph->outputs()->size(); ++i) {
  255. const int tensor_index = subgraph->outputs()->Get(i);
  256. AllocationInfo* current = &subgraph_allocation_info[tensor_index];
  257. UpdateLastUsed(current, allocation_scope_count_);
  258. }
  259. return kTfLiteOk;
  260. }
  261. // Get offline tensors allocation plan. See
  262. // micro/docs/memory_management.md for more info.
  263. TfLiteStatus AllocationInfoBuilder::GetOfflinePlannedOffsets(
  264. const int32_t** offline_planner_offsets) {
  265. if (model_->metadata()) {
  266. for (size_t i = 0; i < model_->metadata()->size(); ++i) {
  267. auto metadata = model_->metadata()->Get(i);
  268. if (strncmp(metadata->name()->c_str(), kOfflineMemAllocMetadata,
  269. strlen(kOfflineMemAllocMetadata)) == 0) {
  270. const flatbuffers::Vector<flatbuffers::Offset<Buffer>>* buffers =
  271. model_->buffers();
  272. auto* buffer = (*buffers)[metadata->buffer()];
  273. auto* array = buffer->data();
  274. const uint32_t* metadata_buffer =
  275. reinterpret_cast<const uint32_t*>(array->data());
  276. const size_t nbr_tensors = static_cast<size_t>(metadata_buffer[2]);
  277. *offline_planner_offsets =
  278. reinterpret_cast<const int32_t*>(&metadata_buffer[3]);
  279. if (info_.tensor_count != nbr_tensors) {
  280. TF_LITE_REPORT_ERROR(reporter_,
  281. "Nbr of offline buffer offsets (%d) in metadata "
  282. "not equal nbr tensors (%d)\n",
  283. nbr_tensors, info_.tensor_count);
  284. return kTfLiteError;
  285. }
  286. }
  287. }
  288. }
  289. return kTfLiteOk;
  290. }
  291. } // namespace tflite