ONE - On-device Neural Engine
Loading...
Searching...
No Matches
BuddyMemoryManager.cpp
Go to the documentation of this file.
1/*
2 * Copyright (c) 2021 Samsung Electronics Co., Ltd. All Rights Reserved
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
18
19namespace luci_interpreter
20{
21
22BuddyMemoryManager::BuddyMemoryManager(uint8_t *memory_start, int32_t memSize)
23{
24 int32_t p = lowerLog2(memSize);
25
26 // We assume that the requested size of memory does not exceed 4 GB
27 assert(p < 32);
28 memSize = 1 << p;
29
30 _start_block = reinterpret_cast<Block *>(memory_start);
31 _start_block->size = memSize - sizeof(Block);
32 _start_block->is_free = true;
33 _start_block->self = _start_block;
34 _num_blocks = 0;
35 _size = _start_block->size;
36
37 for (auto &_free_block : _free_blocks)
38 _free_block = nullptr;
39
40 addToBlocks(_start_block, p);
41}
42
44{
45 const size_t element_size = getDataTypeSize(tensor.element_type());
46 const int32_t num_elements = tensor.shape().num_elements();
47 auto size = num_elements * element_size;
48 auto footprint = size + sizeof(Block);
49 auto l = (footprint & (footprint - 1)) == 0
50 ? lowerLog2(footprint)
51 : lowerLog2(footprint) + 1; // check footprint is pow_of_2
52
53 while (l < 32 && !_free_blocks[l])
54 l++;
55
56 if (l >= 32)
57 {
58 throw std::runtime_error{"Memory limit exceeded"};
59 }
60
61 Block *tmp;
62 tmp = _free_blocks[l];
63 removeFromBlocks(tmp, l);
64
65 while ((tmp->size + sizeof(Block)) / 2 >= size + sizeof(Block))
66 {
67 divideBlock(tmp, l);
68 l--;
69 }
70
71 tmp->is_free = false;
72 tmp->self = tmp;
73 _num_blocks++;
74
75 auto *data = (uint8_t *)(tmp + 1);
76 tensor.set_data_buffer(data);
77}
78
80{
81 auto data = tensor.data<void>();
82 auto *tmp = (Block *)((uint8_t *)data - sizeof(Block));
83
84 assert(tmp->self == tmp);
85
86 tmp->is_free = true;
87 addToBlocks(tmp, lowerLog2(tmp->size + sizeof(Block)));
88
89 while (tmp)
90 if (tmp->size == _size)
91 break;
92 else
93 tmp = mergeBlock(tmp);
94
95 _num_blocks--;
96 tensor.set_data_buffer(nullptr);
97}
98
99} // namespace luci_interpreter
void allocate_memory(luci_interpreter::Tensor &tensor) final
void release_memory(luci_interpreter::Tensor &tensor) final
BuddyMemoryManager(uint8_t *memory_start, int32_t memSize)
const T * data(const std::vector< T, Alloc > &v)
size_t getDataTypeSize(DataType data_type)
Definition DataType.h:33
int32_t size[5]
Definition Slice.cpp:35