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

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