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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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 "graph/manager/graph_mem_manager.h"
  21. namespace ge {
  22. const size_t bin_ranges[kNumBins] = {kRoundBlockSize * kKByteSize,
  23. kBinSizeUnit8 * kMByteSize,
  24. kBinSizeUnit32 * kMByteSize,
  25. kBinSizeUnit128 * kMByteSize,
  26. kBinSizeUnit256 * kMByteSize,
  27. kBinSizeUnit512 * kMByteSize,
  28. kGByteSize};
  29. static bool BlockComparator(const Block *left, const Block *right) {
  30. if (left->size != right->size) {
  31. return left->size < right->size;
  32. }
  33. return reinterpret_cast<uintptr_t>(left->ptr) < reinterpret_cast<uintptr_t>(right->ptr);
  34. }
  35. bool CanMerge(Block *block) {
  36. if ((block == nullptr) || block->allocated || !block->IsSplit()) {
  37. return false;
  38. }
  39. return true;
  40. }
  41. size_t GetBinIndex(size_t size) {
  42. size_t index = 0;
  43. for (auto range : bin_ranges) {
  44. if (size <= range) {
  45. break;
  46. }
  47. index++;
  48. }
  49. if (index > kNumBins - 1) {
  50. index = kNumBins - 1;
  51. }
  52. return index;
  53. }
  54. size_t GetAllocationSize(size_t size) {
  55. size_t index = GetBinIndex(size);
  56. if (bin_ranges[index] >= size) {
  57. return bin_ranges[index];
  58. }
  59. return kGByteSize * ((size + kGByteSize - 1) / kGByteSize);
  60. }
  61. ///
  62. /// @ingroup ge_graph
  63. /// @brief block size based on alignment
  64. /// @param [in] original malloc size
  65. /// @return allocation size
  66. ///
  67. size_t GetBlockSize(size_t size) {
  68. if (size == 0) {
  69. return kRoundBlockSize;
  70. }
  71. return kRoundBlockSize * ((size + kRoundBlockSize - 1) / kRoundBlockSize);
  72. }
  73. bool ShouldSplit(const Block *block, size_t size) {
  74. return static_cast<double>(size) <= (static_cast<double>(block->size) * kSplitThreshold);
  75. }
  76. void IncreaseCount(std::map<size_t, size_t> &count, size_t size) {
  77. auto it = count.find(size);
  78. if (it == count.end()) {
  79. count.emplace(size, 1);
  80. } else {
  81. it->second++;
  82. }
  83. }
  84. CachingAllocator::CachingAllocator(rtMemType_t memory_type)
  85. : memory_type_(memory_type), memory_allocator_(nullptr), called_malloc_counts_(0), called_free_counts_(0) {
  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. called_malloc_counts_ = 0;
  112. called_free_counts_ = 0;
  113. return ge::SUCCESS;
  114. }
  115. void CachingAllocator::Finalize(uint32_t device_id) {
  116. GELOGI("Device id %u", device_id);
  117. PrintStatics();
  118. FreeBlocks();
  119. FreeBlockBins();
  120. }
  121. uint8_t *CachingAllocator::Malloc(size_t size, uint8_t *org_ptr, uint32_t device_id) {
  122. GELOGI("Start malloc pool memory, size = %zu, device id = %u", size, device_id);
  123. called_malloc_counts_++;
  124. size = GetBlockSize(size);
  125. uint8_t *ptr = nullptr;
  126. Block *block = FindFreeBlock(size, org_ptr, device_id);
  127. if (block == nullptr) {
  128. std::lock_guard<std::recursive_mutex> lock(mutex_);
  129. if (ge::SUCCESS == TryExtendCache(size, device_id)) {
  130. block = FindFreeBlock(size, org_ptr, device_id);
  131. if (block != nullptr) {
  132. ptr = block->ptr;
  133. }
  134. }
  135. } else {
  136. ptr = block->ptr;
  137. }
  138. if (ptr == nullptr) {
  139. REPORT_INNER_ERROR("E19999", "FindFreeBlock fail, size:%zu, device_id:%u", size, device_id);
  140. GELOGE(FAILED, "[Check][Param] FindFreeBlock failed device id = %u, size= %zu", device_id, size);
  141. }
  142. return ptr;
  143. }
  144. Status CachingAllocator::Free(uint8_t *ptr, uint32_t device_id) {
  145. GELOGI("Free device id = %u", device_id);
  146. called_free_counts_++;
  147. if (ptr == nullptr) {
  148. REPORT_INNER_ERROR("E19999", "Param ptr is nullptr, device_id:%u, check invalid", device_id);
  149. GELOGE(PARAM_INVALID, "[Check][Param] Invalid memory pointer, device_id:%u", device_id);
  150. return ge::PARAM_INVALID;
  151. }
  152. std::lock_guard<std::recursive_mutex> lock(mutex_);
  153. auto it = allocated_blocks_.find(ptr);
  154. if (it == allocated_blocks_.end()) {
  155. REPORT_INNER_ERROR("E19999", "Param ptr not allocated before, device_id:%u, check invalid", device_id);
  156. GELOGE(PARAM_INVALID, "[Check][Param] Param ptr not allocated before, device_id:%u", device_id);
  157. return ge::PARAM_INVALID;
  158. }
  159. Block *block = it->second;
  160. allocated_blocks_.erase(it);
  161. FreeBlock(block);
  162. return ge::SUCCESS;
  163. }
  164. void CachingAllocator::FreeBlock(Block *block) {
  165. if ((block == nullptr) || !block->allocated) {
  166. return;
  167. }
  168. GELOGI("Free block size = %zu", block->size);
  169. std::lock_guard<std::recursive_mutex> lock(mutex_);
  170. block->allocated = false;
  171. auto &bin = *block->bin;
  172. Block *merge_blocks[] = {block->prev, block->next};
  173. for (Block *merge_block : merge_blocks) {
  174. MergeBlocks(block, merge_block, bin);
  175. }
  176. bin.insert(block);
  177. }
  178. void CachingAllocator::MergeBlocks(Block *dst, Block *src, BlockBin &bin) {
  179. if (!CanMerge(src) || !CanMerge(dst)) {
  180. return;
  181. }
  182. if (dst->prev == src) {
  183. dst->ptr = src->ptr;
  184. dst->prev = src->prev;
  185. if (dst->prev != nullptr) {
  186. dst->prev->next = dst;
  187. }
  188. } else {
  189. dst->next = src->next;
  190. if (dst->next != nullptr) {
  191. dst->next->prev = dst;
  192. }
  193. }
  194. dst->size += src->size;
  195. bin.erase(src);
  196. delete src;
  197. }
  198. BlockBin *CachingAllocator::GetBlockBin(size_t size) {
  199. size_t index = GetBinIndex(size);
  200. return free_block_bins_[index];
  201. }
  202. Block *CachingAllocator::FindFreeBlock(size_t size, uint8_t *org_ptr, uint32_t device_id) {
  203. Block key(device_id, size, org_ptr);
  204. BlockBin *bin = GetBlockBin(size);
  205. if (bin == nullptr) {
  206. REPORT_INNER_ERROR("E19999", "GetBlockBin fail, size:%zu, device_id:%u", size, device_id);
  207. GELOGE(ge::FAILED, "[Get][BlockBin] failed, size:%zu, device_id:%u", size, device_id);
  208. return nullptr;
  209. }
  210. std::lock_guard<std::recursive_mutex> lock(mutex_);
  211. auto it = bin->lower_bound(&key);
  212. if (it != bin->end()) {
  213. Block *block = *it;
  214. bin->erase(it);
  215. if (block != nullptr) {
  216. GELOGI("Find block size = %zu", block->size);
  217. if (ShouldSplit(block, size)) {
  218. block = SplitBlock(block, size, *bin, device_id);
  219. }
  220. if (block->ptr != nullptr) {
  221. block->allocated = true;
  222. allocated_blocks_[block->ptr] = block;
  223. GELOGI("Malloc device id = %u, size= %zu", device_id, size);
  224. }
  225. }
  226. return block;
  227. }
  228. return nullptr;
  229. }
  230. Block *CachingAllocator::SplitBlock(Block *block, size_t size, BlockBin &bin, uint32_t device_id) {
  231. // block has been checked, should not be nullptr
  232. Block *remaining = block;
  233. Block *new_block = new (std::nothrow) Block(device_id, size, &bin, block->ptr);
  234. if (new_block == nullptr) {
  235. REPORT_CALL_ERROR("E19999", "New Block fail, size:%zu, device_id:%u", size, device_id);
  236. GELOGE(ge::FAILED, "[Alloc][Block] failed, size:%zu, device_id:%u", size, device_id);
  237. return block;
  238. }
  239. new_block->prev = remaining->prev;
  240. if (new_block->prev != nullptr) {
  241. new_block->prev->next = new_block;
  242. }
  243. new_block->next = remaining;
  244. remaining->prev = new_block;
  245. remaining->ptr = remaining->ptr + size;
  246. remaining->size -= size;
  247. bin.insert(remaining);
  248. return new_block;
  249. }
  250. Status CachingAllocator::TryExtendCache(size_t size, uint32_t device_id) {
  251. GELOGI("Try to extend cache. size = %zu, device id = %u", size, device_id);
  252. auto memory_size = GetAllocationSize(size);
  253. const std::string purpose = "Memory for caching.";
  254. auto memory_addr = memory_allocator_->MallocMemory(purpose, memory_size, device_id);
  255. // try to free caches and malloc again when malloc memory failed
  256. if (memory_addr == nullptr) {
  257. size_t free_cached_memory_size = FreeCachedBlocks();
  258. memory_addr = memory_allocator_->MallocMemory(purpose, memory_size, device_id);
  259. if (memory_addr == nullptr) {
  260. GELOGE(ge::FAILED, "[Malloc][Memory] failed, no enough memory for size = %zu, device_id = %u", memory_size,
  261. device_id);
  262. PrintStatics(DLOG_ERROR);
  263. return ge::FAILED;
  264. }
  265. GELOGT(TRACE_RUNNING, "Try to free cached memory size:%zu and malloc memory size:%zu success.",
  266. free_cached_memory_size, memory_size);
  267. }
  268. if (AddToBlockBin(memory_addr, memory_size, device_id) != ge::SUCCESS) {
  269. (void)memory_allocator_->FreeMemory(memory_addr);
  270. return ge::FAILED;
  271. }
  272. PrintStatics();
  273. return ge::SUCCESS;
  274. }
  275. Status CachingAllocator::AddToBlockBin(uint8_t *ptr, size_t size, uint32_t device_id) {
  276. BlockBin *bin = GetBlockBin(size);
  277. if (bin == nullptr) {
  278. REPORT_INNER_ERROR("E19999", "GetBlockBin fail, size:%zu, device_id:%u", size, device_id);
  279. GELOGE(ge::FAILED, "[Get][BlockBin] failed, size:%zu, device_id:%u", size, device_id);
  280. return ge::FAILED;
  281. }
  282. Block *block = new (std::nothrow) Block(device_id, size, bin, nullptr);
  283. if (block == nullptr) {
  284. REPORT_CALL_ERROR("E19999", "New Block fail, size:%zu, device_id:%u", size, device_id);
  285. GELOGE(ge::FAILED, "[Alloc][Block] failed, size:%zu, device_id:%u", size, device_id);
  286. return ge::FAILED;
  287. }
  288. GELOGI("Block size = %zu", size);
  289. block->ptr = ptr;
  290. block->size = size;
  291. std::lock_guard<std::recursive_mutex> lock(mutex_);
  292. IncreaseCount(malloced_memory_, block->size);
  293. bin->insert(block);
  294. return ge::SUCCESS;
  295. }
  296. size_t CachingAllocator::FreeCachedBlocks() {
  297. GELOGI("Free cached blocks");
  298. std::lock_guard<std::recursive_mutex> lock(mutex_);
  299. size_t free_cached_memory_size = 0;
  300. for (uint32_t i = 0; i < kNumBins; i++) {
  301. auto pool = free_block_bins_[i];
  302. if (pool == nullptr) {
  303. continue;
  304. }
  305. for (auto it = pool->begin(); it != pool->end();) {
  306. Block *block = *it;
  307. // free block memory that has not been split
  308. if ((block != nullptr) && (block->ptr != nullptr) &&
  309. (block->prev == nullptr) && (block->next == nullptr) &&
  310. (memory_allocator_->FreeMemory(block->ptr) == ge::SUCCESS)) {
  311. auto itcount = malloced_memory_.find(block->size);
  312. free_cached_memory_size += block->size;
  313. if (itcount != malloced_memory_.end()) {
  314. itcount->second--;
  315. if (itcount->second == 0) {
  316. malloced_memory_.erase(itcount);
  317. }
  318. }
  319. pool->erase(it++);
  320. delete block;
  321. continue;
  322. }
  323. ++it;
  324. }
  325. }
  326. return free_cached_memory_size;
  327. }
  328. void CachingAllocator::FreeBlocks() {
  329. GELOGI("Free blocks.");
  330. std::lock_guard<std::recursive_mutex> lock(mutex_);
  331. // free allocated blocks and put to cache
  332. for (auto &it : allocated_blocks_) {
  333. FreeBlock(it.second);
  334. }
  335. allocated_blocks_.clear();
  336. (void) FreeCachedBlocks();
  337. }
  338. void CachingAllocator::TryFreeBlocks() {
  339. GELOGI("Try free blocks.");
  340. std::lock_guard<std::recursive_mutex> lock(mutex_);
  341. if (allocated_blocks_.empty()) {
  342. (void) FreeCachedBlocks();
  343. }
  344. }
  345. void CachingAllocator::FreeBlockBins() {
  346. GELOGI("Free block bins.");
  347. std::lock_guard<std::recursive_mutex> lock(mutex_);
  348. for (uint32_t i = 0; i < kNumBins; i++) {
  349. if (free_block_bins_[i] != nullptr) {
  350. delete free_block_bins_[i];
  351. free_block_bins_[i] = nullptr;
  352. }
  353. }
  354. }
  355. void PrintCount(std::map<size_t, size_t> &count, const std::string &name, size_t total_size, size_t total_count) {
  356. GEEVENT("%6s total[size:%11zu count:%11zu].", name.c_str(), total_size, total_count);
  357. for (auto &it : count) {
  358. GEEVENT(" |- block[size:%11zu count:%11zu].", it.first, it.second);
  359. }
  360. }
  361. void CachingAllocator::PrintStatics(int32_t level) {
  362. if (!IsLogEnable(GE_MODULE_NAME, level)) {
  363. return;
  364. }
  365. size_t total_using_size = 0;
  366. size_t total_using_count = 0;
  367. size_t total_free_size = 0;
  368. size_t total_free_count = 0;
  369. size_t total_malloc_size = 0;
  370. size_t total_malloc_count = 0;
  371. std::map<size_t, size_t> using_block_stat;
  372. std::map<size_t, size_t> free_block_stat;
  373. std::map<size_t, size_t> malloc_block_stat;
  374. do {
  375. std::lock_guard<std::recursive_mutex> lock(mutex_);
  376. for (uint32_t i = 0; i < kNumBins; i++) {
  377. auto pool = free_block_bins_[i];
  378. if (pool == nullptr) {
  379. continue;
  380. }
  381. for (auto it = pool->begin(); it != pool->end(); it++) {
  382. if ((*it) != nullptr) {
  383. total_free_size += (*it)->size;
  384. IncreaseCount(free_block_stat, (*it)->size);
  385. total_free_count++;
  386. }
  387. }
  388. }
  389. for (auto &it : allocated_blocks_) {
  390. if (it.second != nullptr) {
  391. total_using_size += it.second->size;
  392. IncreaseCount(using_block_stat, it.second->size);
  393. total_using_count++;
  394. }
  395. }
  396. for (auto &it : malloced_memory_) {
  397. total_malloc_size += it.first * it.second;
  398. total_malloc_count += it.second;
  399. malloc_block_stat[it.first] = it.second;
  400. }
  401. } while (0);
  402. GEEVENT("Called counts[malloc:%11zu free:%11zu].", called_malloc_counts_.load(), called_free_counts_.load());
  403. PrintCount(malloc_block_stat, "Malloc", total_malloc_size, total_malloc_count);
  404. PrintCount(using_block_stat, "Using", total_using_size, total_using_count);
  405. PrintCount(free_block_stat, "Free", total_free_size, total_free_count);
  406. }
  407. } // namespace ge

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