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 14 kB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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_manager.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. void IncreaseCount(std::map<size_t, size_t> &count, size_t size) {
  78. auto it = count.find(size);
  79. if (it == count.end()) {
  80. count.emplace(size, 1);
  81. } else {
  82. it->second++;
  83. }
  84. }
  85. CachingAllocator::CachingAllocator(rtMemType_t memory_type) : memory_type_(memory_type), memory_allocator_(nullptr) {
  86. for (uint32_t i = 0; i < kNumBins; i++) {
  87. free_block_bins_[i] = nullptr;
  88. }
  89. }
  90. Status CachingAllocator::Initialize(uint32_t device_id) {
  91. GELOGI("Device id %u", device_id);
  92. // when redo Initialize free old memory
  93. FreeBlocks();
  94. std::lock_guard<std::recursive_mutex> lock(mutex_);
  95. for (uint32_t i = 0; i < kNumBins; i++) {
  96. if (free_block_bins_[i] != nullptr) {
  97. continue;
  98. }
  99. auto bin_ptr = new (std::nothrow) BlockBin(BlockComparator);
  100. if (bin_ptr == nullptr) {
  101. REPORT_CALL_ERROR("E19999", "New BlockBin fail, device_id:%u", device_id);
  102. GELOGE(ACL_ERROR_GE_MEMORY_ALLOCATION, "[Alloc][BlockBin] failed, device_id:%u", device_id);
  103. return ACL_ERROR_GE_MEMORY_ALLOCATION;
  104. }
  105. free_block_bins_[i] = bin_ptr;
  106. }
  107. memory_allocator_ = &MemManager::Instance().MemInstance(memory_type_);
  108. if (memory_allocator_ == nullptr) {
  109. return ACL_ERROR_GE_INTERNAL_ERROR;
  110. }
  111. return ge::SUCCESS;
  112. }
  113. void CachingAllocator::Finalize(uint32_t device_id) {
  114. GELOGI("Device id %u", device_id);
  115. PrintStatics();
  116. FreeBlocks();
  117. FreeBlockBins();
  118. }
  119. uint8_t *CachingAllocator::Malloc(size_t size, uint8_t *org_ptr, uint32_t device_id) {
  120. GELOGI("Start malloc pool memory, size = %zu, device id = %u", size, device_id);
  121. size = GetBlockSize(size);
  122. uint8_t *ptr = nullptr;
  123. Block *block = FindFreeBlock(size, org_ptr, device_id);
  124. if (block == nullptr) {
  125. if (ge::SUCCESS == TryExtendCache(size, device_id)) {
  126. block = FindFreeBlock(size, org_ptr, device_id);
  127. if (block != nullptr) {
  128. ptr = block->ptr;
  129. }
  130. }
  131. } else {
  132. ptr = block->ptr;
  133. }
  134. if (ptr == nullptr) {
  135. REPORT_INNER_ERROR("E19999", "FindFreeBlock fail, size:%zu, device_id:%u", size, device_id);
  136. GELOGE(FAILED, "[Check][Param] FindFreeBlock failed device id = %u, size= %zu", device_id, size);
  137. }
  138. return ptr;
  139. }
  140. Status CachingAllocator::Free(uint8_t *ptr, uint32_t device_id) {
  141. GELOGI("Free device id = %u", device_id);
  142. if (ptr == nullptr) {
  143. REPORT_INNER_ERROR("E19999", "Param ptr is nullptr, device_id:%u, check invalid", device_id);
  144. GELOGE(PARAM_INVALID, "[Check][Param] Invalid memory pointer, device_id:%u", device_id);
  145. return ge::PARAM_INVALID;
  146. }
  147. std::lock_guard<std::recursive_mutex> lock(mutex_);
  148. auto it = allocated_blocks_.find(ptr);
  149. if (it == allocated_blocks_.end()) {
  150. REPORT_INNER_ERROR("E19999", "Param ptr not allocated before, device_id:%u, check invalid", device_id);
  151. GELOGE(PARAM_INVALID, "[Check][Param] Param ptr not allocated before, device_id:%u", device_id);
  152. return ge::PARAM_INVALID;
  153. }
  154. Block *block = it->second;
  155. allocated_blocks_.erase(it);
  156. FreeBlock(block);
  157. return ge::SUCCESS;
  158. }
  159. void CachingAllocator::FreeBlock(Block *block) {
  160. if ((block == nullptr) || !block->allocated) {
  161. return;
  162. }
  163. GELOGI("Free block size = %zu", block->size);
  164. std::lock_guard<std::recursive_mutex> lock(mutex_);
  165. block->allocated = false;
  166. auto &bin = *block->bin;
  167. Block *merge_blocks[] = {block->prev, block->next};
  168. for (Block *merge_block : merge_blocks) {
  169. MergeBlocks(block, merge_block, bin);
  170. }
  171. bin.insert(block);
  172. }
  173. void CachingAllocator::MergeBlocks(Block *dst, Block *src, BlockBin &bin) {
  174. if (!CanMerge(src) || !CanMerge(dst)) {
  175. return;
  176. }
  177. if (dst->prev == src) {
  178. dst->ptr = src->ptr;
  179. dst->prev = src->prev;
  180. if (dst->prev != nullptr) {
  181. dst->prev->next = dst;
  182. }
  183. } else {
  184. dst->next = src->next;
  185. if (dst->next != nullptr) {
  186. dst->next->prev = dst;
  187. }
  188. }
  189. dst->size += src->size;
  190. bin.erase(src);
  191. delete src;
  192. }
  193. BlockBin *CachingAllocator::GetBlockBin(size_t size) {
  194. size_t index = GetBinIndex(size);
  195. return free_block_bins_[index];
  196. }
  197. Block *CachingAllocator::FindFreeBlock(size_t size, uint8_t *org_ptr, uint32_t device_id) {
  198. Block key(device_id, size, org_ptr);
  199. BlockBin *bin = GetBlockBin(size);
  200. if (bin == nullptr) {
  201. REPORT_INNER_ERROR("E19999", "GetBlockBin fail, size:%zu, device_id:%u", size, device_id);
  202. GELOGE(ge::FAILED, "[Get][BlockBin] failed, size:%zu, device_id:%u", size, device_id);
  203. return nullptr;
  204. }
  205. std::lock_guard<std::recursive_mutex> lock(mutex_);
  206. auto it = bin->lower_bound(&key);
  207. if (it != bin->end()) {
  208. Block *block = *it;
  209. bin->erase(it);
  210. if (block != nullptr) {
  211. GELOGI("Find block size = %zu", block->size);
  212. if (ShouldSplit(block, size)) {
  213. block = SplitBlock(block, size, *bin, device_id);
  214. }
  215. if (block->ptr != nullptr) {
  216. block->allocated = true;
  217. allocated_blocks_[block->ptr] = block;
  218. GELOGI("Malloc device id = %u, size= %zu", device_id, size);
  219. }
  220. }
  221. return block;
  222. }
  223. return nullptr;
  224. }
  225. Block *CachingAllocator::SplitBlock(Block *block, size_t size, BlockBin &bin, uint32_t device_id) {
  226. // block has been checked, should not be nullptr
  227. Block *remaining = block;
  228. Block *new_block = new (std::nothrow) Block(device_id, size, &bin, block->ptr);
  229. if (new_block == nullptr) {
  230. REPORT_CALL_ERROR("E19999", "New Block fail, size:%zu, device_id:%u", size, device_id);
  231. GELOGE(ge::FAILED, "[Alloc][Block] failed, size:%zu, device_id:%u", size, device_id);
  232. return block;
  233. }
  234. new_block->prev = remaining->prev;
  235. if (new_block->prev != nullptr) {
  236. new_block->prev->next = new_block;
  237. }
  238. new_block->next = remaining;
  239. remaining->prev = new_block;
  240. remaining->ptr = remaining->ptr + size;
  241. remaining->size -= size;
  242. bin.insert(remaining);
  243. return new_block;
  244. }
  245. Status CachingAllocator::TryExtendCache(size_t size, uint32_t device_id) {
  246. GELOGI("Try to extend cache. size = %zu, device id = %u", size, device_id);
  247. auto memory_size = GetAllocationSize(size);
  248. const std::string purpose = "Memory for caching.";
  249. auto memory_addr = memory_allocator_->MallocMemory(purpose, memory_size, device_id);
  250. // try to free caches and malloc again when malloc memory failed
  251. if (memory_addr == nullptr) {
  252. size_t free_cached_memory_size = FreeCachedBlocks();
  253. memory_addr = memory_allocator_->MallocMemory(purpose, memory_size, device_id);
  254. if (memory_addr == nullptr) {
  255. GELOGE(ge::FAILED, "[Malloc][Memory] failed, no enough memory for size = %zu, device_id = %u", memory_size,
  256. device_id);
  257. return ge::FAILED;
  258. }
  259. GELOGT(TRACE_RUNNING, "Try to free cached memory size:%zu and malloc memory size:%zu success.",
  260. free_cached_memory_size, memory_size);
  261. }
  262. if (AddToBlockBin(memory_addr, memory_size, device_id) != ge::SUCCESS) {
  263. (void)memory_allocator_->FreeMemory(memory_addr);
  264. return ge::FAILED;
  265. }
  266. PrintStatics();
  267. return ge::SUCCESS;
  268. }
  269. Status CachingAllocator::AddToBlockBin(uint8_t *ptr, size_t size, uint32_t device_id) {
  270. BlockBin *bin = GetBlockBin(size);
  271. if (bin == nullptr) {
  272. REPORT_INNER_ERROR("E19999", "GetBlockBin fail, size:%zu, device_id:%u", size, device_id);
  273. GELOGE(ge::FAILED, "[Get][BlockBin] failed, size:%zu, device_id:%u", size, device_id);
  274. return ge::FAILED;
  275. }
  276. Block *block = new (std::nothrow) Block(device_id, size, bin, nullptr);
  277. if (block == nullptr) {
  278. REPORT_CALL_ERROR("E19999", "New Block fail, size:%zu, device_id:%u", size, device_id);
  279. GELOGE(ge::FAILED, "[Alloc][Block] failed, size:%zu, device_id:%u", size, device_id);
  280. return ge::FAILED;
  281. }
  282. GELOGI("Block size = %zu", size);
  283. block->ptr = ptr;
  284. block->size = size;
  285. std::lock_guard<std::recursive_mutex> lock(mutex_);
  286. IncreaseCount(malloced_memory_, block->size);
  287. bin->insert(block);
  288. return ge::SUCCESS;
  289. }
  290. size_t CachingAllocator::FreeCachedBlocks() {
  291. GELOGI("Free cached blocks");
  292. std::lock_guard<std::recursive_mutex> lock(mutex_);
  293. size_t free_cached_memory_size = 0;
  294. for (uint32_t i = 0; i < kNumBins; i++) {
  295. auto pool = free_block_bins_[i];
  296. if (pool == nullptr) {
  297. continue;
  298. }
  299. for (auto it = pool->begin(); it != pool->end();) {
  300. Block *block = *it;
  301. // free block memory that has not been split
  302. if ((block != nullptr) && (block->ptr != nullptr) &&
  303. (block->prev == nullptr) && (block->next == nullptr) &&
  304. (memory_allocator_->FreeMemory(block->ptr) == ge::SUCCESS)) {
  305. auto itcount = malloced_memory_.find(block->size);
  306. free_cached_memory_size += block->size;
  307. if (itcount != malloced_memory_.end()) {
  308. itcount->second--;
  309. if (itcount->second == 0) {
  310. malloced_memory_.erase(itcount);
  311. }
  312. }
  313. pool->erase(it++);
  314. delete block;
  315. continue;
  316. }
  317. ++it;
  318. }
  319. }
  320. return free_cached_memory_size;
  321. }
  322. void CachingAllocator::FreeBlocks() {
  323. GELOGI("Free blocks.");
  324. std::lock_guard<std::recursive_mutex> lock(mutex_);
  325. // free allocated blocks and put to cache
  326. for (auto &it : allocated_blocks_) {
  327. FreeBlock(it.second);
  328. }
  329. allocated_blocks_.clear();
  330. (void) FreeCachedBlocks();
  331. }
  332. void CachingAllocator::TryFreeBlocks() {
  333. GELOGI("Try free blocks.");
  334. std::lock_guard<std::recursive_mutex> lock(mutex_);
  335. if (allocated_blocks_.empty()) {
  336. (void) FreeCachedBlocks();
  337. }
  338. }
  339. void CachingAllocator::FreeBlockBins() {
  340. GELOGI("Free block bins.");
  341. std::lock_guard<std::recursive_mutex> lock(mutex_);
  342. for (uint32_t i = 0; i < kNumBins; i++) {
  343. if (free_block_bins_[i] != nullptr) {
  344. delete free_block_bins_[i];
  345. free_block_bins_[i] = nullptr;
  346. }
  347. }
  348. }
  349. void PrintCount(std::map<size_t, size_t> &count, const std::string &name, size_t total_size, size_t total_count) {
  350. GELOGI("%6s total[size:%10zu count:%10zu].", name.c_str(), total_size, total_count);
  351. for (auto &it : count) {
  352. GELOGI(" |- block[size:%10zu count:%10zu].", it.first, it.second);
  353. }
  354. }
  355. void CachingAllocator::PrintStatics() {
  356. if (!IsLogEnable(GE_MODULE_NAME, DLOG_INFO)) {
  357. return;
  358. }
  359. size_t total_using_size = 0;
  360. size_t total_using_count = 0;
  361. size_t total_free_size = 0;
  362. size_t total_free_count = 0;
  363. size_t total_malloc_size = 0;
  364. size_t total_malloc_count = 0;
  365. std::map<size_t, size_t> using_block_stat;
  366. std::map<size_t, size_t> free_block_stat;
  367. std::map<size_t, size_t> malloc_block_stat;
  368. do {
  369. std::lock_guard<std::recursive_mutex> lock(mutex_);
  370. for (uint32_t i = 0; i < kNumBins; i++) {
  371. auto pool = free_block_bins_[i];
  372. if (pool == nullptr) {
  373. continue;
  374. }
  375. for (auto it = pool->begin(); it != pool->end(); it++) {
  376. if ((*it) != nullptr) {
  377. total_free_size += (*it)->size;
  378. IncreaseCount(free_block_stat, (*it)->size);
  379. total_free_count++;
  380. }
  381. }
  382. }
  383. for (auto &it : allocated_blocks_) {
  384. if (it.second != nullptr) {
  385. total_using_size += it.second->size;
  386. IncreaseCount(using_block_stat, it.second->size);
  387. total_using_count++;
  388. }
  389. }
  390. for (auto &it : malloced_memory_) {
  391. total_malloc_size += it.first * it.second;
  392. total_malloc_count += it.second;
  393. malloc_block_stat[it.first] = it.second;
  394. }
  395. } while (0);
  396. PrintCount(malloc_block_stat, "Malloc", total_malloc_size, total_malloc_count);
  397. PrintCount(using_block_stat, "Using", total_using_size, total_using_count);
  398. PrintCount(free_block_stat, "Free", total_free_size, total_free_count);
  399. }
  400. } // namespace ge

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