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

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