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