You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

graph_caching_allocator.cc 10 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. /**
  2. * Copyright 2019-2020 Huawei Technologies Co., Ltd
  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. #include "graph/manager/graph_caching_allocator.h"
  17. #include <set>
  18. #include <string>
  19. #include <utility>
  20. #include "framework/common/debug/ge_log.h"
  21. #include "graph/manager/graph_mem_allocator.h"
  22. namespace ge {
  23. const size_t bin_ranges[kNumBins] = {kRoundBlockSize * kKByteSize,
  24. kBinSizeUnit8 * kMByteSize,
  25. kBinSizeUnit32 * kMByteSize,
  26. kBinSizeUnit128 * kMByteSize,
  27. kBinSizeUnit256 * kMByteSize,
  28. kBinSizeUnit512 * kMByteSize,
  29. kGByteSize};
  30. static bool BlockComparator(const Block *left, const Block *right) {
  31. if (left->size != right->size) {
  32. return left->size < right->size;
  33. }
  34. return reinterpret_cast<uintptr_t>(left->ptr) < reinterpret_cast<uintptr_t>(right->ptr);
  35. }
  36. bool CanMerge(Block *block) {
  37. if (block == nullptr || block->allocated || !block->IsSplit()) {
  38. return false;
  39. }
  40. return true;
  41. }
  42. size_t GetBinIndex(size_t size) {
  43. size_t index = 0;
  44. for (auto range : bin_ranges) {
  45. if (size <= range) {
  46. break;
  47. }
  48. ++index;
  49. }
  50. if (index > kNumBins - 1) {
  51. index = kNumBins - 1;
  52. }
  53. return index;
  54. }
  55. size_t GetAllocationSize(size_t size) {
  56. size_t index = GetBinIndex(size);
  57. if (bin_ranges[index] >= size) {
  58. return bin_ranges[index];
  59. }
  60. return kGByteSize * ((size + kGByteSize - 1) / kGByteSize);
  61. }
  62. ///
  63. /// @ingroup ge_graph
  64. /// @brief block size based on alignment
  65. /// @param [in] original malloc size
  66. /// @return allocation size
  67. ///
  68. size_t GetBlockSize(size_t size) {
  69. if (size == 0) {
  70. return kRoundBlockSize;
  71. }
  72. return kRoundBlockSize * ((size + kRoundBlockSize - 1) / kRoundBlockSize);
  73. }
  74. bool ShouldSplit(const Block *block, size_t size) {
  75. return static_cast<double>(size) <= (static_cast<double>(block->size) * kSplitThreshold);
  76. }
  77. CachingAllocator::CachingAllocator(rtMemType_t memory_type) : memory_type_(memory_type), memory_allocator_(nullptr) {
  78. for (uint32_t i = 0; i < kNumBins; ++i) {
  79. free_block_bins_[i] = nullptr;
  80. }
  81. }
  82. Status CachingAllocator::Initialize(uint32_t device_id) {
  83. GELOGI("Device id %u", device_id);
  84. // when redo Initialize free old memory
  85. FreeBlocks();
  86. std::lock_guard<std::recursive_mutex> lock(mutex_);
  87. for (uint32_t i = 0; i < kNumBins; ++i) {
  88. if (free_block_bins_[i] != nullptr) {
  89. continue;
  90. }
  91. auto bin_ptr = new (std::nothrow) BlockBin(BlockComparator);
  92. if (bin_ptr == nullptr) {
  93. GELOGE(ACL_ERROR_GE_MEMORY_ALLOCATION, "Alloc BlockBin failed.");
  94. return ACL_ERROR_GE_MEMORY_ALLOCATION;
  95. }
  96. free_block_bins_[i] = bin_ptr;
  97. }
  98. memory_allocator_ = MemManager::Instance(memory_type_);
  99. if (memory_allocator_ == nullptr) {
  100. return ACL_ERROR_GE_INTERNAL_ERROR;
  101. }
  102. return ge::SUCCESS;
  103. }
  104. void CachingAllocator::Finalize(uint32_t device_id) {
  105. GELOGI("Device id %u", device_id);
  106. FreeBlocks();
  107. FreeBlockBins();
  108. }
  109. uint8_t *CachingAllocator::Malloc(size_t size, uint8_t *org_ptr, uint32_t device_id) {
  110. uint8_t *ptr = nullptr;
  111. size = GetBlockSize(size);
  112. Block *block = FindFreeBlock(size, org_ptr, device_id);
  113. if (block != nullptr) {
  114. ptr = block->ptr;
  115. } else {
  116. if (ge::SUCCESS == TryExtendCache(size, device_id)) {
  117. block = FindFreeBlock(size, org_ptr, device_id);
  118. if (block != nullptr) {
  119. ptr = block->ptr;
  120. }
  121. }
  122. }
  123. if (ptr == nullptr) {
  124. GELOGE(FAILED, "Malloc failed device id = %u, size= %zu", device_id, size);
  125. }
  126. return ptr;
  127. }
  128. Status CachingAllocator::Free(uint8_t *ptr, uint32_t device_id) {
  129. GELOGI("Free device id = %u", device_id);
  130. if (ptr == nullptr) {
  131. GELOGE(PARAM_INVALID, "Invalid memory pointer");
  132. return ge::PARAM_INVALID;
  133. }
  134. std::lock_guard<std::recursive_mutex> lock(mutex_);
  135. auto it = allocated_blocks_.find(ptr);
  136. if (it == allocated_blocks_.end()) {
  137. GELOGE(PARAM_INVALID, "Invalid memory pointer");
  138. return ge::PARAM_INVALID;
  139. }
  140. Block *block = it->second;
  141. allocated_blocks_.erase(it);
  142. FreeBlock(block);
  143. return ge::SUCCESS;
  144. }
  145. void CachingAllocator::FreeBlock(Block *block) {
  146. if (block == nullptr || !block->allocated) {
  147. return;
  148. }
  149. GELOGI("Free block size = %zu", block->size);
  150. std::lock_guard<std::recursive_mutex> lock(mutex_);
  151. block->allocated = false;
  152. auto &bin = *block->bin;
  153. Block *merge_blocks[] = {block->prev, block->next};
  154. for (Block *merge_block : merge_blocks) {
  155. MergeBlocks(block, merge_block, bin);
  156. }
  157. bin.insert(block);
  158. }
  159. void CachingAllocator::MergeBlocks(Block *dst, Block *src, BlockBin &bin) {
  160. if (!CanMerge(dst) || !CanMerge(src)) {
  161. return;
  162. }
  163. if (dst->prev == src) {
  164. dst->ptr = src->ptr;
  165. dst->prev = src->prev;
  166. if (dst->prev != nullptr) {
  167. dst->prev->next = dst;
  168. }
  169. } else {
  170. dst->next = src->next;
  171. if (dst->next != nullptr) {
  172. dst->next->prev = dst;
  173. }
  174. }
  175. dst->size += src->size;
  176. bin.erase(src);
  177. delete src;
  178. }
  179. BlockBin *CachingAllocator::GetBlockBin(size_t size) {
  180. size_t index = GetBinIndex(size);
  181. return free_block_bins_[index];
  182. }
  183. Block *CachingAllocator::FindFreeBlock(size_t size, uint8_t *org_ptr, uint32_t device_id) {
  184. // org_ptr - 1, try to find ptr same as org_ptr
  185. Block key(device_id, size, (org_ptr == nullptr ? nullptr : org_ptr - 1));
  186. BlockBin *bin = GetBlockBin(size);
  187. if (bin == nullptr) {
  188. GELOGE(ge::FAILED, "Get block bin failed size = %zu", size);
  189. return nullptr;
  190. }
  191. std::lock_guard<std::recursive_mutex> lock(mutex_);
  192. auto it = bin->lower_bound(&key);
  193. if (it != bin->end()) {
  194. Block *block = *it;
  195. bin->erase(it);
  196. if (block != nullptr) {
  197. GELOGI("Find block size = %zu", block->size);
  198. if (ShouldSplit(block, size)) {
  199. block = SplitBlock(block, size, *bin, device_id);
  200. }
  201. if (block->ptr != nullptr) {
  202. block->allocated = true;
  203. allocated_blocks_[block->ptr] = block;
  204. GELOGI("Malloc device id = %u, size= %zu", device_id, size);
  205. }
  206. }
  207. return block;
  208. }
  209. return nullptr;
  210. }
  211. Block *CachingAllocator::SplitBlock(Block *block, size_t size, BlockBin &bin, uint32_t device_id) {
  212. // block has been checked, should not be nullptr
  213. Block *remaining = block;
  214. Block *new_block = new (std::nothrow) Block(device_id, size, &bin, block->ptr);
  215. if (new_block == nullptr) {
  216. GELOGE(ge::FAILED, "Alloc block failed size = %zu", size);
  217. return block;
  218. }
  219. new_block->prev = remaining->prev;
  220. if (new_block->prev != nullptr) {
  221. new_block->prev->next = new_block;
  222. }
  223. new_block->next = remaining;
  224. remaining->prev = new_block;
  225. remaining->ptr = remaining->ptr + size;
  226. remaining->size -= size;
  227. bin.insert(remaining);
  228. return new_block;
  229. }
  230. Status CachingAllocator::TryExtendCache(size_t size, uint32_t device_id) {
  231. auto memory_size = GetAllocationSize(size);
  232. const std::string purpose = "Memory for caching.";
  233. auto memory_addr = memory_allocator_->MallocMemory(purpose, memory_size, device_id);
  234. // try to free caches and malloc again when malloc memory failed
  235. if (memory_addr == nullptr) {
  236. FreeCachedBlocks();
  237. memory_addr = memory_allocator_->MallocMemory(purpose, memory_size, device_id);
  238. if (memory_addr == nullptr) {
  239. GELOGE(ge::FAILED, "TryExtendCache failed, no enough memory for size = %zu, device_id = %u", memory_size,
  240. device_id);
  241. return ge::FAILED;
  242. }
  243. }
  244. if (AddToBlockBin(memory_addr, memory_size, device_id) != ge::SUCCESS) {
  245. (void)memory_allocator_->FreeMemory(memory_addr);
  246. return ge::FAILED;
  247. }
  248. return ge::SUCCESS;
  249. }
  250. Status CachingAllocator::AddToBlockBin(uint8_t *ptr, size_t size, uint32_t device_id) {
  251. BlockBin *bin = GetBlockBin(size);
  252. if (bin == nullptr) {
  253. GELOGE(ge::FAILED, "Get block bin failed size = %zu", size);
  254. return ge::FAILED;
  255. }
  256. Block *block = new (std::nothrow) Block(device_id, size, bin, nullptr);
  257. if (block == nullptr) {
  258. GELOGE(ge::FAILED, "Alloc block failed size = %zu", size);
  259. return ge::FAILED;
  260. }
  261. GELOGI("Block size = %zu", size);
  262. block->ptr = ptr;
  263. block->size = size;
  264. std::lock_guard<std::recursive_mutex> lock(mutex_);
  265. bin->insert(block);
  266. return ge::SUCCESS;
  267. }
  268. void CachingAllocator::FreeCachedBlocks() {
  269. GELOGI("Free cached blocks");
  270. std::lock_guard<std::recursive_mutex> lock(mutex_);
  271. for (uint32_t i = 0; i < kNumBins; ++i) {
  272. auto pool = free_block_bins_[i];
  273. if (pool == nullptr) {
  274. continue;
  275. }
  276. for (auto it = pool->begin(); it != pool->end();) {
  277. Block *block = *it;
  278. // free block memory that has not been split
  279. if ((block != nullptr) && (block->ptr != nullptr) && (block->prev == nullptr) && (block->next == nullptr) &&
  280. (memory_allocator_->FreeMemory(block->ptr) == ge::SUCCESS)) {
  281. pool->erase(it++);
  282. delete block;
  283. continue;
  284. }
  285. ++it;
  286. }
  287. }
  288. }
  289. void CachingAllocator::FreeBlocks() {
  290. GELOGI("Free blocks");
  291. std::lock_guard<std::recursive_mutex> lock(mutex_);
  292. // free allocated blocks and put to cache
  293. for (auto &it : allocated_blocks_) {
  294. FreeBlock(it.second);
  295. }
  296. allocated_blocks_.clear();
  297. FreeCachedBlocks();
  298. }
  299. void CachingAllocator::FreeBlockBins() {
  300. GELOGI("Free block bins");
  301. std::lock_guard<std::recursive_mutex> lock(mutex_);
  302. for (uint32_t i = 0; i < kNumBins; ++i) {
  303. if (free_block_bins_[i] != nullptr) {
  304. delete free_block_bins_[i];
  305. free_block_bins_[i] = nullptr;
  306. }
  307. }
  308. }
  309. } // namespace ge

图引擎模块(GE)是MindSpore的一个子模块,其代码由C++实现,位于前端模块ME和底层硬件之间,起到承接作用。图引擎模块以ME下发的图作为输入,然后进行一系列的深度图优化操作,最后输出一张可以在底层硬件上高效运行的图。GE针对昇腾AI处理器的硬件结构特点,做了特定的优化工作,以此来充分发挥出昇腾AI处理器的强大算力。在进行模型训练/推理时,GE会被自动调用而用户并不感知.