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.

block_mem_assigner.cc 71 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781
  1. /**
  2. * Copyright 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/build/memory/block_mem_assigner.h"
  17. #include <algorithm>
  18. #include <sstream>
  19. #include "external/ge/ge_api_types.h"
  20. #include "framework/common/debug/ge_log.h"
  21. #include "graph/anchor.h"
  22. #include "graph/buffer.h"
  23. #include "graph/ge_attr_value.h"
  24. #include "graph/ge_context.h"
  25. #include "graph/node.h"
  26. #include "graph/utils/graph_utils.h"
  27. #include "graph/utils/node_utils.h"
  28. #include "graph/utils/op_desc_utils.h"
  29. #include "graph/utils/tensor_utils.h"
  30. #include "graph/debug/ge_attr_define.h"
  31. #include "graph/common/local_context.h"
  32. #include "graph/optimize/common/params.h"
  33. #include "omg/omg_inner_types.h"
  34. #include "runtime/mem.h"
  35. using std::map;
  36. using std::set;
  37. using std::list;
  38. using std::pair;
  39. using std::string;
  40. using std::stringstream;
  41. using std::unordered_map;
  42. using std::unordered_set;
  43. using std::vector;
  44. namespace {
  45. const char *const kAttrNameWorkspaceReuseFlag = "workspace_reuse_flag";
  46. const char *const kL2FusionDynamicConvergeOp = "l2fusion_dynamic_converge_op";
  47. const char *const kOpNoReuseMem = "no_reuse_mem_flag";
  48. const char *const OP_NO_REUSE_MEM = "OP_NO_REUSE_MEM";
  49. const int kReuseMaxCount = 10;
  50. const int kReuseMaxOpNum = 10;
  51. const int kReuseMaxCharNum = 2000;
  52. } // namespace
  53. namespace ge {
  54. void AlignMemOffset(size_t &mem_align_size) {
  55. if (mem_align_size <= 0) {
  56. return;
  57. }
  58. mem_align_size = (mem_align_size + MEM_ALIGN_SIZE - 1) / MEM_ALIGN_SIZE * MEM_ALIGN_SIZE;
  59. }
  60. void MemoryBlock::SetHeadOffset(size_t offset) {
  61. head_offset_ = offset;
  62. size_t child_offset = head_offset_;
  63. for (auto block : child_blocks_) {
  64. if (block != nullptr) {
  65. block->SetHeadOffset(child_offset);
  66. child_offset += block->Size();
  67. }
  68. }
  69. }
  70. void MemoryBlock::SetTailOffset(size_t offset) {
  71. tail_offset_ = offset;
  72. size_t child_offset = head_offset_;
  73. for (auto block : child_blocks_) {
  74. if (block != nullptr) {
  75. child_offset += block->Size();
  76. block->SetTailOffset(child_offset - 1);
  77. }
  78. }
  79. }
  80. void MemoryBlock::Resize() {
  81. size_t child_block_size = 0;
  82. for (auto block : child_blocks_) {
  83. if (block != nullptr) {
  84. block->Resize();
  85. child_block_size += block->Size();
  86. }
  87. }
  88. auto iter = std::max_element(real_size_list_.begin(), real_size_list_.end());
  89. if (iter == real_size_list_.end()) {
  90. GELOGW("real_size_list_ is empty");
  91. return;
  92. } else {
  93. size_t block_size = (child_block_size > *iter) ? child_block_size : *iter;
  94. if ((block_size > 0) && (block_size % MEM_ALIGN_SIZE != 0)) {
  95. AlignMemOffset(block_size);
  96. }
  97. block_size_ = block_size;
  98. if (last_continuous_block_) {
  99. block_size_ += MEM_ALIGN_SIZE;
  100. }
  101. }
  102. }
  103. size_t MemoryBlock::AlignSize() const {
  104. size_t align_block_size = 0;
  105. auto iter = std::max_element(real_size_list_.begin(), real_size_list_.end());
  106. if (iter == real_size_list_.end()) {
  107. GELOGW("real_size_list_ is empty");
  108. } else {
  109. align_block_size = *iter;
  110. if ((align_block_size > 0) && (align_block_size % MEM_ALIGN_SIZE != 0)) {
  111. AlignMemOffset(align_block_size);
  112. }
  113. }
  114. return align_block_size;
  115. }
  116. bool MemoryBlock::IsSameLabel(std::string &first_batch_label) {
  117. if (node_type_index_list_.empty()) {
  118. return false;
  119. }
  120. auto node_op_desc = node_type_index_list_[0].node->GetOpDesc();
  121. if (node_op_desc == nullptr) {
  122. return false;
  123. }
  124. // not all op has ATTR_NAME_BATCH_LABEL, no need check return value, only check out parameter
  125. (void)ge::AttrUtils::GetStr(node_op_desc, ATTR_NAME_BATCH_LABEL, first_batch_label);
  126. if (first_batch_label.empty()) {
  127. return false;
  128. }
  129. bool all_same_label = true;
  130. for (size_t index = 1; index < node_type_index_list_.size(); ++index) {
  131. if (node_type_index_list_[index].node == nullptr) {
  132. continue;
  133. }
  134. std::string batch_label;
  135. auto index_op_desc = node_type_index_list_[index].node->GetOpDesc();
  136. GE_IF_BOOL_EXEC(index_op_desc == nullptr, continue);
  137. (void)ge::AttrUtils::GetStr(index_op_desc, ATTR_NAME_BATCH_LABEL, batch_label);
  138. if (first_batch_label != batch_label) {
  139. all_same_label = false;
  140. break;
  141. }
  142. }
  143. return all_same_label;
  144. }
  145. bool CanNotLifeReuse(MemoryBlock *block) {
  146. if ((block == nullptr) || !block->reuse_mem_ || block->deleted_block_) {
  147. return true;
  148. }
  149. return false;
  150. }
  151. void MemoryBlock::AddContinuousLifeReuseBlock(MemoryBlock *block, DependStreamLife &total_node_depend_stream_life) {
  152. // continuous memory case:only real_size is maximum can be reused and only one continuous memory in one block
  153. auto it_block = std::max_element(std::begin(block->NoAlignSizeList()), std::end(block->NoAlignSizeList()));
  154. auto it_this = std::max_element(std::begin(NoAlignSizeList()), std::end(NoAlignSizeList()));
  155. if (it_block != std::end(block->NoAlignSizeList()) && it_this != std::end(NoAlignSizeList())) {
  156. if ((continuous_block_ && block->continuous_block_) ||
  157. (continuous_block_ && (*it_this < *it_block)) || (block->continuous_block_ && (*it_this > *it_block))) {
  158. GELOGD("Conflict current block size:%zu continuous:%d, reuse block max size:%zu continuous:%d",
  159. *it_this, continuous_block_, *it_block, block->continuous_block_);
  160. return;
  161. }
  162. }
  163. MemoryBlock *parent = nullptr;
  164. MemoryBlock *child = nullptr;
  165. // merge small block to large block
  166. if (block->GetDependLifeBegin(stream_id_, total_node_depend_stream_life) > GetLifeEnd()) {
  167. if ((block->child_offset_ + AlignSize()) <= *it_block) {
  168. parent = block;
  169. child = this;
  170. }
  171. }
  172. if ((parent != nullptr) && (child != nullptr) && child->child_blocks_.empty()) {
  173. parent->child_blocks_.emplace_back(child);
  174. parent->child_offset_ += child->AlignSize();
  175. child->deleted_block_ = true;
  176. GELOGI("Add continuous block[%p size:%zu, stream id:%ld life time[begin:%zu, end:%zu]] to"
  177. " block[%p size:%zu, stream id:%ld, life time[begin:%zu, end:%zu]]", child, child->block_size_,
  178. child->stream_id_, child->GetLifeBegin(), child->GetLifeEnd(), parent, parent->block_size_,
  179. parent->stream_id_, parent->GetLifeBegin(), parent->GetLifeEnd());
  180. }
  181. }
  182. void MemoryBlock::AddLifeReuseBlock(MemoryBlock *block, DependStreamLife &total_node_depend_stream_life) {
  183. if (CanNotLifeReuse(this) || CanNotLifeReuse(block)) {
  184. return;
  185. }
  186. if (block->continuous_block_) {
  187. AddContinuousLifeReuseBlock(block, total_node_depend_stream_life);
  188. return;
  189. }
  190. MemoryBlock *parent = nullptr;
  191. MemoryBlock *child = nullptr;
  192. // merge small block to large block
  193. if (block->GetDependLifeBegin(stream_id_, total_node_depend_stream_life) > GetLifeEnd()) {
  194. if ((child_offset_ + block->AlignSize()) <= AlignSize()) {
  195. parent = this;
  196. child = block;
  197. } else if ((block->child_offset_ + AlignSize()) <= block->AlignSize()) {
  198. parent = block;
  199. child = this;
  200. }
  201. }
  202. if ((parent != nullptr) && (child != nullptr) && child->child_blocks_.empty()) {
  203. parent->child_blocks_.emplace_back(child);
  204. parent->child_offset_ += child->AlignSize();
  205. child->deleted_block_ = true;
  206. GELOGI("Add block[%p size:%zu, stream id:%ld life time[begin:%zu, end:%zu]] to"
  207. " block[%p size:%zu, stream id:%ld, life time[begin:%zu, end:%zu]]", child, child->block_size_,
  208. child->stream_id_, child->GetLifeBegin(), child->GetLifeEnd(), parent, parent->block_size_,
  209. parent->stream_id_, parent->GetLifeBegin(), parent->GetLifeEnd());
  210. }
  211. }
  212. size_t MemoryBlock::GetLifeBegin() {
  213. size_t life_time = 0;
  214. if (!node_type_index_list_.empty()) {
  215. if (node_type_index_list_.front().node != nullptr) {
  216. auto node_op_desc = node_type_index_list_.front().node->GetOpDesc();
  217. if (node_op_desc != nullptr) {
  218. life_time = node_op_desc->GetId();
  219. }
  220. }
  221. }
  222. return life_time;
  223. }
  224. /// |-stream 1-| |-stream 2-|
  225. /// |--block1--| |--block---|
  226. /// |--block2--| |--block---|
  227. /// |--block3--|\ |--block---|
  228. /// |--block---| \ |--block---|
  229. /// |--block---| \|--block---|
  230. /// |--block---| |--block7--|
  231. /// |--block---| |--block---|
  232. /// block7's first node's input node's life begin > block2's life end, block7 can reuse block1~block2
  233. size_t MemoryBlock::GetDependLifeBegin(int64_t stream_id, DependStreamLife &total_node_depend_stream_life) {
  234. AddDependLifeBegin(total_node_depend_stream_life);
  235. auto it = depend_stream_life_.find(stream_id);
  236. if (it == depend_stream_life_.end()) {
  237. return 0;
  238. }
  239. return it->second;
  240. }
  241. void AddDependLife(const ge::NodePtr &org_node, const ge::NodePtr &node, int64_t stream_id,
  242. std::map<int64_t, size_t> &depend_stream_life, DependStreamLife &total_node_depend_stream_life) {
  243. GE_CHECK_NOTNULL_EXEC(node, return);
  244. auto node_desc = node->GetOpDesc();
  245. GE_CHECK_NOTNULL_EXEC(node_desc, return);
  246. auto node_id = node_desc->GetId();
  247. auto stream_life = total_node_depend_stream_life.find(node_id);
  248. if (stream_life != total_node_depend_stream_life.end()) {
  249. for (auto &it : stream_life->second) {
  250. if (depend_stream_life.find(it.first) == depend_stream_life.end()) {
  251. depend_stream_life[it.first] = it.second;
  252. }
  253. }
  254. return;
  255. }
  256. for (const auto &in_anchor : node->GetAllInAnchors()) {
  257. GE_CHECK_NOTNULL_EXEC(in_anchor, continue);
  258. for (auto peer_out_anchor : in_anchor->GetPeerAnchors()) {
  259. GE_CHECK_NOTNULL_EXEC(peer_out_anchor, continue);
  260. auto peer_node = peer_out_anchor->GetOwnerNode();
  261. GE_CHECK_NOTNULL_EXEC(peer_node, continue);
  262. auto peer_node_desc = peer_node->GetOpDesc();
  263. GE_CHECK_NOTNULL_EXEC(peer_node_desc, continue);
  264. auto peer_node_stream_id = peer_node_desc->GetStreamId();
  265. if (peer_node_stream_id < 0) {
  266. continue;
  267. }
  268. size_t peer_node_life_time = peer_node_desc->GetId();
  269. auto it = depend_stream_life.find(peer_node_stream_id);
  270. if (it == depend_stream_life.end() || peer_node_life_time > it->second) {
  271. depend_stream_life[peer_node_stream_id] = peer_node_life_time;
  272. if (peer_node_stream_id != stream_id) {
  273. GELOGI("Node:%s stream id:%ld depend node:%s stream id:%ld index[%d] life time[%zu].",
  274. org_node->GetName().c_str(), stream_id, peer_node_desc->GetName().c_str(),
  275. peer_node_stream_id, peer_out_anchor->GetIdx(), peer_node_life_time);
  276. }
  277. AddDependLife(org_node, peer_node, stream_id, depend_stream_life, total_node_depend_stream_life);
  278. }
  279. }
  280. }
  281. // save on node to save next calculation
  282. for (auto &it : depend_stream_life) {
  283. if (total_node_depend_stream_life[node_id].find(it.first) == total_node_depend_stream_life[node_id].end()) {
  284. total_node_depend_stream_life[node_id][it.first] = it.second;
  285. }
  286. }
  287. }
  288. void MemoryBlock::AddDependLifeBegin(DependStreamLife &total_node_depend_stream_life) {
  289. if (!depend_stream_life_.empty()) {
  290. return;
  291. }
  292. if (!node_type_index_list_.empty()) {
  293. auto node = node_type_index_list_.front().node;
  294. if (node != nullptr) {
  295. AddDependLife(node, node, stream_id_, depend_stream_life_, total_node_depend_stream_life);
  296. }
  297. }
  298. depend_stream_life_[stream_id_] = GetLifeBegin();
  299. }
  300. size_t MemoryBlock::GetLifeEnd() {
  301. if (!node_type_index_list_.empty()) {
  302. return node_type_index_list_.back().life_time_end;
  303. }
  304. return kMaxLifeTime;
  305. }
  306. void MemoryBlock::SetLifeTimeEnd(size_t time) {
  307. if (!node_type_index_list_.empty()) {
  308. node_type_index_list_.back().life_time_end = time;
  309. }
  310. }
  311. void SetLastUsedInputMemAttr(NodePtr &node, int input_index) {
  312. if (node == nullptr) {
  313. return;
  314. }
  315. auto node_op_desc = node->GetOpDesc();
  316. if (node_op_desc != nullptr) {
  317. auto input_desc = node_op_desc->GetInputDesc(input_index);
  318. if (!ge::AttrUtils::SetInt(input_desc, ATTR_NAME_IS_END_OF_INPUTMEM_LIFECYCLE, true)) {
  319. GELOGW("Set %s input[%d] ATTR_NAME_IS_END_OF_INPUTMEM_LIFECYCLE to true failed.", node_op_desc->GetName().c_str(),
  320. input_index);
  321. return;
  322. }
  323. GELOGD("Set %s input[%d] ATTR_NAME_IS_END_OF_INPUTMEM_LIFECYCLE to true success.", node_op_desc->GetName().c_str(),
  324. input_index);
  325. if (node_op_desc->UpdateInputDesc(input_index, input_desc) != GRAPH_SUCCESS) {
  326. GELOGW("Update %s input[%d] desc failed.", node_op_desc->GetName().c_str(), input_index);
  327. }
  328. }
  329. }
  330. Status GetNoAlignSize(const ge::OpDesc &desc, uint32_t index, size_t &size) {
  331. // calculate tensor real size
  332. auto output_op_desc = desc.GetOutputDescPtr(index);
  333. if (output_op_desc == nullptr) {
  334. GELOGI("GetNoAlignSize failed. OpName: %s, OpType: %s, index: %d",
  335. desc.GetName().c_str(), desc.GetType().c_str(), index);
  336. return FAILED;
  337. }
  338. int64_t tensor_size = 0;
  339. GeShape shape = output_op_desc->GetShape();
  340. Format format = output_op_desc->GetFormat();
  341. DataType data_type = output_op_desc->GetDataType();
  342. graphStatus graph_status = TensorUtils::CalcTensorMemSize(shape, format, data_type, tensor_size);
  343. if (graph_status != GRAPH_SUCCESS) {
  344. GELOGE(graph_status, "CalcTensorMemSize failed!");
  345. return FAILED;
  346. }
  347. size = static_cast<size_t>(tensor_size);
  348. return SUCCESS;
  349. }
  350. string ToString(ge::NodeTypeIndex &x) {
  351. stringstream ss;
  352. ss << "[" << x.node->GetName() << "(" << x.node->GetType() << "), ";
  353. if (x.mem_type == kOutput) {
  354. ss << "Output, ";
  355. } else {
  356. ss << "Workspace, ";
  357. }
  358. ss << x.index << "]";
  359. return ss.str();
  360. }
  361. string MemoryBlock::String() {
  362. stringstream ss;
  363. ss << "Block size: " << Size() << " from " << HeadOffset() << " to " << TailOffset() << " ";
  364. ss << "real_size_list: " << ToString(real_size_list_) << " ";
  365. ss << "ref_count: " << ref_count_ << " ";
  366. ss << "members: ";
  367. for (auto x : NodeTypeIndexList()) {
  368. ss << "__node: " << ToString(x) << " ";
  369. }
  370. for (const auto& symbol : SymbolList()) {
  371. ss << "__symbol: " << symbol << " ";
  372. }
  373. ss << "memory_type: " << memory_type_ << " ";
  374. return ss.str();
  375. }
  376. BlockMemAssigner::BlockMemAssigner(ComputeGraphPtr compute_graph, const map<string, string> &anchor_to_symbol,
  377. const map<string, list<NodeIndexIO>> &symbol_to_anchors)
  378. : mem_offset_(0), p2p_mem_offset_(0), compute_graph_(std::move(compute_graph)),
  379. symbol_to_anchors_(symbol_to_anchors), anchor_to_symbol_(anchor_to_symbol), life_time_(0) {}
  380. BlockMemAssigner::~BlockMemAssigner() {
  381. GELOGD("blocks_store_ size : %lu", blocks_store_.size());
  382. for (MemoryBlock *memory_block : blocks_store_) {
  383. GE_DELETE_NEW_SINGLE(memory_block);
  384. }
  385. }
  386. void BlockMemAssigner::GetOutAndWorkSpaceMem(vector<int64_t> &all_memory_size) {
  387. vector<int64_t> temp;
  388. for (const NodePtr &n : compute_graph_->GetAllNodes()) {
  389. auto node_op_desc = n->GetOpDesc();
  390. GE_IF_BOOL_EXEC(node_op_desc == nullptr, continue);
  391. if (node_op_desc->GetType() == ATOMICADDRCLEAN) {
  392. atomic_addr_clean_id_ = node_op_desc->GetId();
  393. }
  394. // if input size just one, no need to reassign continuous memory
  395. bool is_input_continuous = false;
  396. (void)ge::AttrUtils::GetBool(node_op_desc, ATTR_NAME_CONTINUOUS_INPUT, is_input_continuous);
  397. if (is_input_continuous && (node_op_desc->GetInputSize() <= 1)) {
  398. (void)ge::AttrUtils::SetBool(node_op_desc, ATTR_NAME_CONTINUOUS_INPUT_ALLOC, true);
  399. }
  400. for (auto &out_anchor : n->GetAllOutDataAnchors()) {
  401. GeTensorDesc output_desc = node_op_desc->GetOutputDesc(out_anchor->GetIdx());
  402. bool reuse_input = false;
  403. GE_IF_BOOL_EXEC(ge::TensorUtils::GetReuseInput(output_desc, reuse_input) != SUCCESS,
  404. GELOGI("Get reuse_input failed"));
  405. if (!reuse_input) {
  406. int64_t size = 0;
  407. GE_IF_BOOL_EXEC(ge::TensorUtils::GetSize(output_desc, size) != SUCCESS, GELOGI("Get size failed"));
  408. if (anchor_to_symbol_.empty()) {
  409. all_memory_size.emplace_back(size);
  410. } else {
  411. auto iter1 = anchor_to_symbol_.find(NodeIndexIO(n, out_anchor->GetIdx(), kOut).ToString());
  412. if (iter1 == anchor_to_symbol_.end()) {
  413. continue;
  414. }
  415. const std::string &symbol = iter1->second;
  416. auto iter2 = symbol_size_.find(symbol);
  417. if (iter2 == symbol_size_.end()) {
  418. symbol_size_[symbol] = size;
  419. } else if (size > static_cast<int64_t>(iter2->second)) {
  420. iter2->second = size;
  421. }
  422. }
  423. }
  424. }
  425. temp.clear();
  426. GetNodeWorkSpaceSize(n, temp);
  427. all_memory_size.insert(all_memory_size.end(), temp.begin(), temp.end());
  428. }
  429. GELOGI("The last atomic_addr_clean node id: %ld", atomic_addr_clean_id_);
  430. for (const auto &pair : symbol_size_) {
  431. all_memory_size.emplace_back(pair.second);
  432. }
  433. sort(all_memory_size.begin(), all_memory_size.end());
  434. GELOGI("All memory size: %s", ToString(all_memory_size).c_str());
  435. for (auto iter = all_memory_size.begin(); iter != all_memory_size.end();) {
  436. if (*iter == 0) {
  437. iter = all_memory_size.erase(iter);
  438. } else {
  439. ++iter;
  440. }
  441. }
  442. InitReuseFlag();
  443. PrintSymbolMap();
  444. }
  445. ///
  446. /// @ingroup domi
  447. /// @brief decide memory size based on actual input memory size
  448. /// @param [in] size actual memory size in need
  449. /// @param [in] ranges memory size provided
  450. /// @return size_t memory size to apply
  451. ///
  452. size_t GetBlockSize(size_t size, const vector<int64_t> &ranges) {
  453. for (int64_t x : ranges) {
  454. auto x_temp = static_cast<size_t>(x);
  455. if (size <= x_temp) {
  456. return x_temp;
  457. }
  458. }
  459. GELOGW("Memory needed size:%zu is beyond the biggest block in memory ranges.", size);
  460. return size;
  461. }
  462. bool IsDirectOutputNode(const NodePtr &node, int idx) {
  463. if ((node != nullptr) && (node->GetOpDesc() != nullptr) && (node->GetOpDesc()->GetType() == NETOUTPUT)) {
  464. GELOGI("This is netoutput node, the input node mem can not be reused");
  465. return true;
  466. }
  467. return false;
  468. }
  469. void AddReusableBlockCount(const MemoryBlock &mem_block, map<string, uint64_t> &reusable_block_counts) {
  470. string key = std::to_string(mem_block.Size());
  471. key += "_" + std::to_string(mem_block.stream_id_);
  472. key += "_" + std::to_string(mem_block.memory_type_);
  473. auto it = reusable_block_counts.find(key);
  474. if (it != reusable_block_counts.end()) {
  475. it->second++;
  476. } else {
  477. reusable_block_counts[key] = 1;
  478. }
  479. }
  480. void ReduceReusableBlockCount(const MemoryBlock &mem_block, map<string, uint64_t> &reusable_block_counts) {
  481. string key = std::to_string(mem_block.Size());
  482. key += "_" + std::to_string(mem_block.stream_id_);
  483. key += "_" + std::to_string(mem_block.memory_type_);
  484. auto it = reusable_block_counts.find(key);
  485. if (it != reusable_block_counts.end()) {
  486. if (it->second > 0) {
  487. it->second--;
  488. }
  489. }
  490. }
  491. bool CanReuseBySize(const map<string, uint64_t> &reusable_block_counts, const MemoryBlock &reusable_block,
  492. size_t block_size, size_t real_size, bool continuous) {
  493. bool can_reuse = false;
  494. if (reusable_block.Size() == block_size) {
  495. can_reuse = true;
  496. } else {
  497. string key = std::to_string(reusable_block.Size());
  498. key += "_" + std::to_string(reusable_block.stream_id_);
  499. key += "_" + std::to_string(reusable_block.memory_type_);
  500. auto it = reusable_block_counts.find(key);
  501. GE_IF_BOOL_EXEC((it != reusable_block_counts.end() && (it->second > kReuseMaxCount)) &&
  502. (reusable_block.Size() > block_size),
  503. can_reuse = true;
  504. GELOGD("Less size mem reuse, reuse block size:%zu, current block size:%zu",
  505. reusable_block.Size(), block_size););
  506. }
  507. return can_reuse;
  508. }
  509. bool BlockMemAssigner::IsOutNodeSetContinuousInput(const NodePtr &n, uint32_t out_index, std::string &peer_name,
  510. uint32_t &peer_input_index,
  511. bool &no_need_assign_memory, bool &reset_zero_copy_flag) {
  512. if (n == nullptr || n->GetAllOutDataAnchors().size() <= 0) {
  513. return false;
  514. }
  515. if (static_cast<size_t>(out_index) < n->GetAllOutDataAnchors().size()) {
  516. auto out_anchor = n->GetOutDataAnchor(out_index);
  517. GE_IF_BOOL_EXEC(out_anchor == nullptr,
  518. GELOGE(FAILED, "Node[%s] output[%u] anchor is null.", n->GetName().c_str(), out_index);
  519. return false;);
  520. for (auto const &peer_in_anchor : out_anchor->GetPeerInDataAnchors()) {
  521. GE_IF_BOOL_EXEC(peer_in_anchor == nullptr,
  522. GELOGE(FAILED, "Node[%s] output[%u] peer_in_anchor 0 is null.", n->GetName().c_str(), out_index);
  523. return false;);
  524. auto peer_node = peer_in_anchor->GetOwnerNode();
  525. GE_IF_BOOL_EXEC(peer_node == nullptr,
  526. GELOGE(FAILED, "Node[%s] output[%u] node is null.", n->GetName().c_str(), out_index);
  527. return false;);
  528. // Get the continuous input type of the node, default is false
  529. bool is_input_continuous = false;
  530. auto peer_in_node_desc = peer_node->GetOpDesc();
  531. GE_IF_BOOL_EXEC(peer_in_node_desc == nullptr,
  532. GELOGE(FAILED, "Node[%s] output[%u] nodedesc is null.", n->GetName().c_str(), out_index);
  533. return false;);
  534. // If GetBool fail, is_input_continuous is false.
  535. bool is_input_continuous_no_padding = false;
  536. (void)ge::AttrUtils::GetBool(peer_in_node_desc, ATTR_NAME_NOPADDING_CONTINUOUS_INPUT,
  537. is_input_continuous_no_padding);
  538. if (is_input_continuous_no_padding) {
  539. reset_zero_copy_flag = true;
  540. return false;
  541. }
  542. (void)ge::AttrUtils::GetBool(peer_in_node_desc, ATTR_NAME_CONTINUOUS_INPUT, is_input_continuous);
  543. GE_IF_BOOL_EXEC(is_input_continuous && CheckIsZeroMemNodeType(peer_node->GetType()),
  544. GELOGI("Node[%s] output[%u] no_need_assign_memory.", n->GetName().c_str(), out_index);
  545. no_need_assign_memory = true;
  546. return false;);
  547. if (is_input_continuous) {
  548. if (n->GetOwnerComputeGraph() != nullptr) {
  549. string graph_name = n->GetOwnerComputeGraph()->GetName();
  550. GELOGI("%s name[%s] output[%u] node[%s] set input[%d] continuous, input size[%u].", graph_name.c_str(),
  551. n->GetName().c_str(), out_index, peer_in_node_desc->GetName().c_str(), peer_in_anchor->GetIdx(),
  552. peer_node->GetAllInDataAnchorsSize());
  553. // Only set attr one times.
  554. if (node_continuous_input_blocks_[peer_in_node_desc->GetName()].size() == 0) {
  555. (void)ge::AttrUtils::SetBool(peer_in_node_desc, ATTR_NAME_CONTINUOUS_INPUT_ALLOC, true);
  556. node_continuous_input_counts_[peer_in_node_desc->GetName()] = peer_node->GetAllInDataAnchorsSize();
  557. }
  558. peer_input_index = peer_in_anchor->GetIdx();
  559. peer_name = peer_in_node_desc->GetName();
  560. return true;
  561. }
  562. }
  563. }
  564. }
  565. return false;
  566. }
  567. ///
  568. /// @ingroup GE
  569. /// @brief Check pre_reuse flag & post_reuse glag for each symbol
  570. /// @return void
  571. ///
  572. void BlockMemAssigner::InitReuseFlag() {
  573. static const std::set<std::string> kPreReuseTypes = { ge::DATA_TYPE, ge::AIPP_DATA_TYPE, ge::ANN_DATA_TYPE,
  574. ge::NETOUTPUT, ge::PROPOSAL, ge::ZEROSLIKE,
  575. ge::CONSTANT, ge::CONSTANTOP };
  576. static const std::set<std::string> kPostReuseTypes = { ge::DATA_TYPE, ge::AIPP_DATA_TYPE, ge::ENTER, ge::REFENTER,
  577. ge::NEXTITERATION, ge::REFNEXTITERATION };
  578. for (const auto &pair : symbol_to_anchors_) {
  579. std::string symbol = pair.first;
  580. bool pre_reuse_flag = true;
  581. bool post_reuse_flag = true;
  582. // default memory type
  583. int64_t mem_type = RT_MEMORY_HBM;
  584. GetSymbolMemType(pair.second, mem_type);
  585. GELOGD("The memory type of symbol[%s] is [%ld]].", symbol.c_str(), mem_type);
  586. if (mem_type == RT_MEMORY_P2P_DDR) {
  587. UpdateOpTensorMemType(pair.second, mem_type);
  588. }
  589. // Only the memory with special requirements is processed. The HBM uses the default processing mode.
  590. if (mem_type == RT_MEMORY_P2P_DDR) {
  591. symbol_to_mem_type_[symbol] = mem_type;
  592. }
  593. for (const auto &node_index_io : pair.second) {
  594. if (node_index_io.io_type_ == kIn) {
  595. continue;
  596. }
  597. OutDataAnchorPtr out_anchor = node_index_io.node_->GetOutDataAnchor(node_index_io.index_);
  598. if (out_anchor == nullptr) {
  599. continue;
  600. }
  601. bool out_flg = false;
  602. if (node_index_io.node_->GetOutDataNodes().empty()) {
  603. out_flg = true;
  604. }
  605. for (const auto &in_anchor : out_anchor->GetPeerInDataAnchors()) {
  606. if (IsDirectOutputNode(in_anchor->GetOwnerNode(), in_anchor->GetIdx())) {
  607. out_flg = true;
  608. break;
  609. }
  610. }
  611. const std::string &type = out_anchor->GetOwnerNode()->GetType();
  612. pre_reuse_flag = pre_reuse_flag && !out_flg && (kPreReuseTypes.count(type) == 0);
  613. post_reuse_flag = post_reuse_flag && (kPostReuseTypes.count(type) == 0);
  614. if (!pre_reuse_flag && !post_reuse_flag) {
  615. break;
  616. }
  617. }
  618. pre_reuse_flag_[symbol] = pre_reuse_flag;
  619. post_reuse_flag_[symbol] = post_reuse_flag;
  620. }
  621. }
  622. ///
  623. /// @ingroup GE
  624. /// @brief get pre_reuse flag
  625. /// @param [in] node
  626. /// @param [in] out_index
  627. /// @return bool
  628. ///
  629. bool BlockMemAssigner::IsPreReuse(const NodePtr &node, uint32_t out_index) const {
  630. OutDataAnchorPtr out_data_anchor = nullptr;
  631. if (static_cast<size_t>(out_index) < node->GetAllOutDataAnchors().size()) {
  632. out_data_anchor = node->GetOutDataAnchor(out_index);
  633. }
  634. if (out_data_anchor == nullptr) {
  635. return false;
  636. }
  637. NodeIndexIO cur_node_index_io(out_data_anchor->GetOwnerNode(), out_data_anchor->GetIdx(), kOut);
  638. auto iter1 = anchor_to_symbol_.find(cur_node_index_io.ToString());
  639. if (iter1 == anchor_to_symbol_.end()) {
  640. return false;
  641. }
  642. const std::string &symbol = iter1->second;
  643. auto iter2 = pre_reuse_flag_.find(symbol);
  644. if (iter2 == pre_reuse_flag_.end()) {
  645. return false;
  646. }
  647. return iter2->second;
  648. }
  649. ///
  650. /// @ingroup GE
  651. /// @brief get post_reuse flag
  652. /// @param [in] mem_block
  653. /// @return bool
  654. ///
  655. bool BlockMemAssigner::IsPostReuse(const MemoryBlock *mem_block) const {
  656. if (mem_block == nullptr) {
  657. return false;
  658. }
  659. for (const auto &symbol : mem_block->SymbolList()) {
  660. auto iter = post_reuse_flag_.find(symbol);
  661. if (iter == post_reuse_flag_.end()) {
  662. continue;
  663. }
  664. if (!iter->second) {
  665. return false;
  666. }
  667. }
  668. return true;
  669. }
  670. ///
  671. /// @ingroup GE
  672. /// @brief check if symbol of cur node_index_io has block
  673. /// @param [in] node_index_io
  674. /// @param [out] symbol
  675. /// @return bool
  676. ///
  677. bool BlockMemAssigner::IsSymbolExist(const NodeIndexIO &node_index_io, string &symbol) {
  678. auto iter = anchor_to_symbol_.find(node_index_io.ToString());
  679. if (iter == anchor_to_symbol_.end()) {
  680. return false;
  681. }
  682. symbol = iter->second;
  683. return symbol_blocks_.find(iter->second) != symbol_blocks_.end();
  684. }
  685. ///
  686. /// @ingroup GE
  687. /// @brief Print symbol
  688. /// @return void
  689. ///
  690. void BlockMemAssigner::PrintSymbolMap() {
  691. for (const auto &pair : symbol_to_anchors_) {
  692. GELOGD("symbol=%s, max_size=%zu, pre_reuse=%s, post_reuse=%s", pair.first.c_str(), symbol_size_[pair.first],
  693. pre_reuse_flag_[pair.first] ? "true" : "false", post_reuse_flag_[pair.first] ? "true" : "false");
  694. for (const auto &node_index_io : pair.second) {
  695. GELOGD("anchor:%s", node_index_io.ToString().c_str());
  696. }
  697. }
  698. }
  699. void BlockMemAssigner::GetSymbolMemType(std::list<NodeIndexIO> node_index_io_list, int64_t &memory_type) {
  700. memory_type = RT_MEMORY_HBM;
  701. vector<int64_t> memory_types;
  702. for (auto &node_index_io : node_index_io_list) {
  703. auto op_desc = node_index_io.node_->GetOpDesc();
  704. if (op_desc == nullptr) {
  705. GELOGW("Node[%s] op desc is null.", node_index_io.node_->GetName().c_str());
  706. return;
  707. }
  708. if (node_index_io.io_type_ == kIn) {
  709. vector<int64_t> input_memory_types;
  710. (void) ge::AttrUtils::GetListInt(op_desc, ATTR_NAME_INPUT_MEM_TYPE_LIST, input_memory_types);
  711. if (!input_memory_types.empty() && node_index_io.index_ < input_memory_types.size()) {
  712. int64_t input_memory_type = input_memory_types[node_index_io.index_];
  713. GELOGD("Node[%s]: the memory type of input index [%u] is [%ld]].", op_desc->GetName().c_str(),
  714. node_index_io.index_, input_memory_type);
  715. memory_types.emplace_back(input_memory_type);
  716. }
  717. }
  718. if (node_index_io.io_type_ == kOut) {
  719. vector<int64_t> output_memory_types;
  720. (void) ge::AttrUtils::GetListInt(op_desc, ATTR_NAME_OUTPUT_MEM_TYPE_LIST, output_memory_types);
  721. if (!output_memory_types.empty() && node_index_io.index_ < output_memory_types.size()) {
  722. int64_t output_memory_type = output_memory_types[node_index_io.index_];
  723. GELOGD("Node[%s]: the memory type of output index [%u] is [%ld]].", op_desc->GetName().c_str(),
  724. node_index_io.index_, output_memory_type);
  725. memory_types.emplace_back(output_memory_type);
  726. }
  727. }
  728. }
  729. // memory priority
  730. for (auto node_memory_type : memory_types) {
  731. if (node_memory_type > memory_type) {
  732. memory_type = node_memory_type;
  733. }
  734. }
  735. }
  736. void BlockMemAssigner::UpdateOpTensorMemType(std::list<NodeIndexIO> node_index_io_list, int64_t memory_type) {
  737. for (auto &node_index_io : node_index_io_list) {
  738. auto op_desc = node_index_io.node_->GetOpDesc();
  739. if (op_desc == nullptr) {
  740. GELOGW("Node[%s] op desc is null.", node_index_io.node_->GetName().c_str());
  741. return;
  742. }
  743. if (node_index_io.io_type_ == kIn) {
  744. auto input_desc = op_desc->MutableInputDesc(node_index_io.index_);
  745. (void) AttrUtils::SetInt(input_desc, ATTR_NAME_TENSOR_MEM_TYPE, memory_type);
  746. }
  747. if (node_index_io.io_type_ == kOut) {
  748. auto output_desc = op_desc->MutableOutputDesc(node_index_io.index_);
  749. (void) AttrUtils::SetInt(output_desc, ATTR_NAME_TENSOR_MEM_TYPE, memory_type);
  750. }
  751. }
  752. }
  753. bool BlockMemAssigner::IsContinuousOutput(const NodePtr &n) {
  754. if (n == nullptr) {
  755. GELOGE(FAILED, "Node is null.");
  756. return false;
  757. }
  758. // Get the continuous output type of the node, default is false
  759. bool is_output_continuous = false;
  760. auto node_desc = n->GetOpDesc();
  761. if (node_desc == nullptr) {
  762. GELOGE(FAILED, "Node[%s] nodedesc is null.", n->GetName().c_str());
  763. return false;
  764. }
  765. // If GetBool fail, is_output_continuous is false.
  766. (void)ge::AttrUtils::GetBool(node_desc, ATTR_NAME_CONTINUOUS_OUTPUT, is_output_continuous);
  767. if (is_output_continuous) {
  768. if (n->GetOwnerComputeGraph() != nullptr) {
  769. string graph_name = n->GetOwnerComputeGraph()->GetName();
  770. GELOGI("%s name[%s] set continuous, output size[%u].", graph_name.c_str(),
  771. n->GetName().c_str(), n->GetAllOutDataAnchorsSize());
  772. return true;
  773. }
  774. }
  775. return false;
  776. }
  777. bool BlockMemAssigner::IsZeroCopyBlock(const NodePtr &node, bool continuous) {
  778. if (NodeUtils::IsDynamicShape(node)) {
  779. return ((node->GetType() == DATA_TYPE) && !continuous) || (node->GetType() == NETOUTPUT);
  780. }
  781. if ((node->GetType() == DATA_TYPE) && !continuous) {
  782. return !node->GetOpDesc()->HasAttr(ATTR_NAME_PARENT_NODE_INDEX);
  783. }
  784. if (node->GetType() == NETOUTPUT) {
  785. const auto &owner = node->GetOwnerComputeGraph();
  786. return owner->GetParentGraph() == nullptr;
  787. }
  788. return false;
  789. }
  790. MemoryBlock *BlockMemAssigner::ApplyMemory(size_t block_size, size_t real_size, size_t no_align_size,
  791. OpMemoryType mem_type, const NodePtr &n, uint32_t out_index,
  792. const vector<bool> &workspace_reuse_flag, const bool is_op_reuse_mem,
  793. const bool continuous, int64_t memory_type) {
  794. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(n == nullptr, return nullptr, "Input parameter n is null.");
  795. auto node_op_desc = n->GetOpDesc();
  796. GE_IF_BOOL_EXEC(node_op_desc == nullptr, return nullptr);
  797. bool is_reuse_memory = false;
  798. string ge_disable_reuse_mem_env = "0";
  799. (void)ge::GetContext().GetOption(OPTION_EXEC_DISABLE_REUSED_MEMORY, ge_disable_reuse_mem_env);
  800. if (ge_disable_reuse_mem_env != "1") {
  801. bool reuse_mem_flag = (mem_type == kOutput) ? IsPreReuse(n, out_index) :
  802. !((workspace_reuse_flag.size() > out_index) && !workspace_reuse_flag[out_index]);
  803. is_reuse_memory = !node_op_desc->HasAttr(kL2FusionDynamicConvergeOp) &&
  804. !node_op_desc->HasAttr(kOpNoReuseMem) && reuse_mem_flag && is_op_reuse_mem;
  805. auto stream_id = node_op_desc->GetStreamId();
  806. if (is_reuse_memory && !continuous && !reusable_blocks_[memory_type].empty()) {
  807. for (auto it = reusable_blocks_[memory_type][stream_id].begin();
  808. it != reusable_blocks_[memory_type][stream_id].end(); ++it) {
  809. MemoryBlock *reusable_block = *it;
  810. if (!IsPostReuse(reusable_block)) {
  811. reusable_block->reuse_mem_ = false;
  812. GELOGI("Unreusable block.");
  813. continue;
  814. }
  815. // A node can reuse blocks of the same stream and preorder streams
  816. if (CanReuseBySize(reusable_block_counts_, *reusable_block, block_size, real_size, continuous)) {
  817. reusable_block->AddNodeTypeIndex({n, mem_type, out_index, false}, real_size, no_align_size);
  818. if (mem_type == kOutput) {
  819. auto iter = anchor_to_symbol_.find(NodeIndexIO(n, out_index, kOut).ToString());
  820. if (iter != anchor_to_symbol_.end()) {
  821. reusable_block->AddSymbol(iter->second);
  822. }
  823. }
  824. reusable_block->continuous_block_ = continuous;
  825. reusable_block->ref_count_++;
  826. ReduceReusableBlockCount(*reusable_block, reusable_block_counts_);
  827. reusable_blocks_[memory_type][stream_id].erase(it);
  828. return reusable_block;
  829. }
  830. }
  831. }
  832. }
  833. auto block = new (std::nothrow) MemoryBlock(block_size, node_op_desc->GetStreamId(), is_reuse_memory, memory_type);
  834. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(block == nullptr, return nullptr, "new an object failed.");
  835. // Data and netoutput need zero copy block
  836. block->is_zero_copy_ = IsZeroCopyBlock(n, continuous);
  837. block->Init(real_size, mem_type, n, out_index, no_align_size);
  838. block->stream_id_ = node_op_desc->GetStreamId();
  839. block->ref_count_++;
  840. block->continuous_block_ = continuous;
  841. if (mem_type == kOutput) {
  842. auto iter = anchor_to_symbol_.find(NodeIndexIO(n, out_index, kOut).ToString());
  843. if (iter != anchor_to_symbol_.end()) {
  844. block->AddSymbol(iter->second);
  845. }
  846. }
  847. memory_blocks_.emplace_back(block);
  848. // cause memory_blocks_ may reduce when swap after,
  849. // create blocks_store_ to assure blocks deleted finally
  850. blocks_store_.emplace_back(block);
  851. return block;
  852. }
  853. MemoryBlock *BlockMemAssigner::ApplyContinuousMemory(const NodePtr &n, const vector<int64_t> &ranges,
  854. const bool is_op_reuse_mem) {
  855. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(n == nullptr, return nullptr, "input node is null.");
  856. auto node_op_desc = n->GetOpDesc();
  857. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(node_op_desc == nullptr, return nullptr, "node_op_desc is null.");
  858. // if output size just one, no need to reassign continuous memory
  859. if (node_op_desc->GetOutputsSize() == 1) {
  860. zero_memory_list_.emplace_back(n, kOutput, 0);
  861. return nullptr;
  862. }
  863. MemoryBlock *block = nullptr;
  864. int64_t total_size = 0;
  865. int64_t memory_type = RT_MEMORY_HBM;
  866. for (uint32_t index = 0; index < static_cast<uint32_t>(node_op_desc->GetOutputsSize()); index++) {
  867. auto output_op_desc = node_op_desc->GetOutputDescPtr(index);
  868. if (output_op_desc == nullptr) {
  869. return nullptr;
  870. }
  871. int64_t size = 0;
  872. if (ge::TensorUtils::GetSize(*output_op_desc, size) != SUCCESS) {
  873. GELOGI("Get size failed");
  874. return nullptr;
  875. }
  876. size_t align_size = static_cast<size_t>(size);
  877. AlignMemOffset(align_size);
  878. total_size += align_size;
  879. // only apply total size in first block
  880. if (index != 0) {
  881. zero_memory_list_.emplace_back(n, kOutput, index);
  882. }
  883. if (index == 0) {
  884. NodeIndexIO node_index_io(n, index, kOut);
  885. auto iter = anchor_to_symbol_.find(node_index_io.ToString());
  886. if (iter != anchor_to_symbol_.end()) {
  887. string symbol = iter->second;
  888. if (symbol_to_mem_type_.find(symbol) != symbol_to_mem_type_.end()) {
  889. memory_type = symbol_to_mem_type_[symbol];
  890. GELOGD("Continuous out memory symbol is [%s], memory type is [%ld]", symbol.c_str(), memory_type);
  891. }
  892. }
  893. }
  894. }
  895. auto block_size = GetBlockSize(total_size, ranges);
  896. GELOGI("Node[%s] continuous out memory size[%ld] block size[%zu]", node_op_desc->GetName().c_str(),
  897. total_size, block_size);
  898. vector<bool> workspace_reuse_flag;
  899. block = ApplyMemory(block_size, total_size, total_size, kOutput, n, 0, workspace_reuse_flag, is_op_reuse_mem, true,
  900. memory_type);
  901. if (block != nullptr) {
  902. // hccl task need align header and tail
  903. block->first_continuous_block_ = true;
  904. block->last_continuous_block_ = true;
  905. }
  906. return block;
  907. }
  908. MemoryBlock *BlockMemAssigner::ApplyOutMemory(const NodePtr &n, uint32_t index, const vector<int64_t> &ranges,
  909. const bool is_op_reuse_mem, const bool continuous) {
  910. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(n == nullptr, return nullptr, "input node is null.");
  911. auto node_op_desc = n->GetOpDesc();
  912. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(node_op_desc == nullptr, return nullptr, "node_op_desc is null.");
  913. MemoryBlock *block = nullptr;
  914. NodeIndexIO node_index_io(n, index, kOut);
  915. int64_t size = 0;
  916. auto output_op_desc = node_op_desc->GetOutputDescPtr(index);
  917. if (output_op_desc != nullptr) {
  918. GE_IF_BOOL_EXEC(ge::TensorUtils::GetSize(*output_op_desc, size) != SUCCESS, GELOGI("Get size failed"));
  919. }
  920. size_t no_align_size = 0;
  921. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(GetNoAlignSize(*node_op_desc, index, no_align_size) != SUCCESS,
  922. return nullptr, "Get no align size failed");
  923. std::string symbol;
  924. if (IsSymbolExist(node_index_io, symbol)) {
  925. block = symbol_blocks_[symbol];
  926. block->AddNodeTypeIndex({n, kOutput, index, true}, size, no_align_size);
  927. block->ref_count_++;
  928. } else {
  929. int64_t max_size = size;
  930. int64_t memory_type = RT_MEMORY_HBM;
  931. auto iter1 = anchor_to_symbol_.find(node_index_io.ToString());
  932. if (iter1 != anchor_to_symbol_.end()) {
  933. auto iter2 = symbol_size_.find(iter1->second);
  934. if (iter2 != symbol_size_.end()) {
  935. max_size = iter2->second;
  936. }
  937. auto iter3 = symbol_to_mem_type_.find(iter1->second);
  938. if (iter3 != symbol_to_mem_type_.end()) {
  939. memory_type = iter3->second;
  940. }
  941. }
  942. auto block_size = GetBlockSize(max_size, ranges);
  943. vector<bool> workspace_reuse_flag;
  944. block = ApplyMemory(block_size, size, no_align_size, kOutput, n, index,
  945. workspace_reuse_flag, is_op_reuse_mem, continuous, memory_type);
  946. }
  947. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(block == nullptr, return nullptr, "Block is nullptr.");
  948. int out_count_reuse_input = block->ref_count_;
  949. int out_count = 0;
  950. GE_IF_BOOL_EXEC(index >= n->GetAllOutDataAnchors().size(), GELOGE(FAILED, "index is out of range."); return nullptr);
  951. auto out_data_anchor = n->GetOutDataAnchor(index);
  952. GE_IF_BOOL_EXEC(out_data_anchor == nullptr, GELOGE(FAILED, "Out data anchor is nullptr."); return nullptr);
  953. for (const auto &in_anchor : out_data_anchor->GetPeerInDataAnchors()) {
  954. auto owner_node = in_anchor->GetOwnerNode();
  955. auto op_desc = owner_node->GetOpDesc();
  956. GE_IF_BOOL_EXEC(op_desc == nullptr, continue);
  957. Params *instance = Params::Instance();
  958. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(instance == nullptr, return nullptr, "Params instance is nullptr.");
  959. if (!((instance->GetTarget() == TARGET_TYPE_TINY) && (op_desc->GetType() == NETOUTPUT))) {
  960. out_count++;
  961. }
  962. }
  963. bool reuse_input = false;
  964. for (const auto &in_anchor : out_data_anchor->GetPeerInDataAnchors()) {
  965. auto owner_node = in_anchor->GetOwnerNode();
  966. GE_IF_BOOL_EXEC(owner_node == nullptr, continue);
  967. auto op_desc = owner_node->GetOpDesc();
  968. GE_IF_BOOL_EXEC(op_desc == nullptr, continue);
  969. for (uint32_t i = 0; i < static_cast<uint32_t>(op_desc->GetOutputsSize()); i++) {
  970. bool dst_reuse_input = false;
  971. uint32_t dst_reuse_input_index = 0;
  972. auto owner_node_op_desc = op_desc->GetOutputDescPtr(i);
  973. GE_IF_BOOL_EXEC(owner_node_op_desc == nullptr, continue);
  974. GE_IF_BOOL_EXEC(ge::TensorUtils::GetReuseInput(*owner_node_op_desc, dst_reuse_input) != SUCCESS,
  975. GELOGI("Get dst_reuse_input failed"));
  976. GE_IF_BOOL_EXEC(ge::TensorUtils::GetReuseInputIndex(*owner_node_op_desc, dst_reuse_input_index) != SUCCESS,
  977. GELOGI("Get dst_reuse_input_index failed"));
  978. if (dst_reuse_input && (dst_reuse_input_index == static_cast<uint32_t>(in_anchor->GetIdx()))) {
  979. block->AddNodeTypeIndex({owner_node, kOutput, i, true}, block->Size(), block->Size());
  980. out_count_reuse_input += 1;
  981. reuse_input = true;
  982. }
  983. }
  984. }
  985. block->ref_count_ = reuse_input ? out_count_reuse_input + out_count - 1 : out_count;
  986. return block;
  987. }
  988. bool IsOutputBlock(const ge::InDataAnchorPtr &in_data_anchor) {
  989. auto peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  990. GE_IF_BOOL_EXEC(peer_out_anchor == nullptr, GELOGE(FAILED, "Peer out anchor is nullptr."); return false);
  991. auto src = peer_out_anchor->GetOwnerNode();
  992. int32_t index = peer_out_anchor->GetIdx();
  993. auto iter = GetLocalOmgContext().out_nodes_map.find(src->GetName());
  994. if (iter != GetLocalOmgContext().out_nodes_map.end()) {
  995. for (auto id : iter->second) {
  996. if (index == id) {
  997. return true;
  998. }
  999. }
  1000. }
  1001. return false;
  1002. }
  1003. // atomic out memory will be reassigned
  1004. bool IsAtomicOutputMemory(const ge::NodePtr &node, uint32_t output_index, bool is_atomic,
  1005. bool out_node_set_continuous_input) {
  1006. auto op_desc = node->GetOpDesc();
  1007. if (op_desc == nullptr) {
  1008. return false;
  1009. }
  1010. vector<int64_t> atomic_output_index;
  1011. // If GetListInt fail, atomic_output_index is empty.
  1012. (void)ge::AttrUtils::GetListInt(op_desc, ATOMIC_ATTR_OUTPUT_INDEX, atomic_output_index);
  1013. if (!out_node_set_continuous_input && is_atomic) {
  1014. for (auto &index : atomic_output_index) {
  1015. if (static_cast<uint32_t>(index) == output_index) {
  1016. if (node->GetOwnerComputeGraph() != nullptr) {
  1017. string graph_name = node->GetOwnerComputeGraph()->GetName();
  1018. GELOGD("[IMAS]Atomic no assign %s name[%s] output[%d] streamid[%ld].", graph_name.c_str(),
  1019. op_desc->GetName().c_str(), index, op_desc->GetStreamId());
  1020. }
  1021. return true;
  1022. }
  1023. }
  1024. }
  1025. return false;
  1026. }
  1027. bool IsKnownSubgraphData(const NodePtr &node) {
  1028. if (NodeUtils::IsDynamicShape(node)) {
  1029. return false;
  1030. }
  1031. return node->GetOpDesc()->HasAttr(ATTR_NAME_PARENT_NODE_INDEX);
  1032. }
  1033. void BlockMemAssigner::ReleaseMemory(MemoryBlock *to_release, vector<MemoryBlock *> &reusable_memory) {
  1034. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(to_release == nullptr, return, "Input parameter to_release is null.");
  1035. GE_CHK_TRUE_EXEC_INFO(to_release->ref_count_ <= 0, return, "Release memory");
  1036. GE_CHK_TRUE_EXEC_INFO(!to_release->reuse_mem_, return, "doesn't reuse memory");
  1037. --to_release->ref_count_;
  1038. if (to_release->ref_count_ == 0) {
  1039. to_release->SetLifeTimeEnd(life_time_);
  1040. reusable_memory.emplace_back(to_release);
  1041. AddReusableBlockCount(*to_release, reusable_block_counts_);
  1042. }
  1043. }
  1044. void BlockMemAssigner::ReleaseMemorys(const vector<MemoryBlock *> &to_releases,
  1045. vector<MemoryBlock *> &reusable_memory) {
  1046. for (auto mem_block : to_releases) {
  1047. ReleaseMemory(mem_block, reusable_memory);
  1048. }
  1049. }
  1050. void BlockMemAssigner::ReleaseInputNodeOutMemory(const unordered_map<string, vector<MemoryBlock *>> &node_out_blocks,
  1051. vector<MemoryBlock *> &reusable_memory, NodePtr &node) {
  1052. for (const auto &in_anchor : node->GetAllInDataAnchors()) {
  1053. if ((in_anchor->GetPeerOutAnchor() == nullptr) ||
  1054. (in_anchor->GetPeerOutAnchor()->GetOwnerNode()->GetOpDesc() == nullptr) || (node->GetOpDesc() == nullptr)) {
  1055. return;
  1056. }
  1057. GE_IF_BOOL_EXEC(IsOutputBlock(in_anchor), continue);
  1058. auto node_name = in_anchor->GetPeerOutAnchor()->GetOwnerNode()->GetName();
  1059. GE_IF_BOOL_EXEC((in_anchor->GetPeerOutAnchor()->GetOwnerNode()->GetType() == CONSTANT) ||
  1060. (in_anchor->GetPeerOutAnchor()->GetOwnerNode()->GetType() == FASTRCNNPREDICTIONS) ||
  1061. (in_anchor->GetPeerOutAnchor()->GetOwnerNode()->GetType() == CONSTANTOP),
  1062. continue);
  1063. auto it = node_out_blocks.find(node_name);
  1064. if (it == node_out_blocks.end()) {
  1065. continue;
  1066. }
  1067. for (auto block : it->second) {
  1068. const vector<NodeTypeIndex> &node_type_indexs = block->NodeTypeIndexList();
  1069. if (node_type_indexs.empty()) {
  1070. continue;
  1071. }
  1072. GELOGD("node_type_indexs: %d, %s", node_type_indexs.back().index,
  1073. node_type_indexs.back().node->GetName().c_str());
  1074. if ((node_type_indexs.back().node == in_anchor->GetPeerOutAnchor()->GetOwnerNode()) &&
  1075. (node_type_indexs.back().index == static_cast<uint32_t>(in_anchor->GetPeerOutAnchor()->GetIdx())) &&
  1076. (node->GetOpDesc()->GetStreamId() == block->stream_id_)) {
  1077. ReleaseMemory(block, reusable_memory);
  1078. if (block->ref_count_ == 0) {
  1079. SetLastUsedInputMemAttr(node, in_anchor->GetIdx());
  1080. }
  1081. }
  1082. }
  1083. }
  1084. }
  1085. void SplitStringByComma(const string &str, vector<string> &sub_str_vec) {
  1086. std::string tmp_string = str + ",";
  1087. std::string::size_type start_pos = 0;
  1088. std::string::size_type cur_pos = tmp_string.find(',', 0);
  1089. while (cur_pos != std::string::npos) {
  1090. std::string sub_str = tmp_string.substr(start_pos, cur_pos - start_pos);
  1091. if (!sub_str.empty()) {
  1092. vector<string>::iterator ret = std::find(sub_str_vec.begin(), sub_str_vec.end(), sub_str);
  1093. if (ret == sub_str_vec.end()) {
  1094. sub_str_vec.push_back(sub_str);
  1095. }
  1096. }
  1097. start_pos = cur_pos + 1;
  1098. cur_pos = tmp_string.find(',', start_pos);
  1099. }
  1100. }
  1101. void CheckAndGetOpReuseEnv(const string &env, vector<string> &env_vec, bool &op_reuse_env_valid) {
  1102. string env_str;
  1103. env_str = string(env);
  1104. if (env_str.size() > kReuseMaxCharNum) {
  1105. GELOGE(FAILED, "The OP_NO_REUSE_MEM has more than %d characters.", kReuseMaxCharNum);
  1106. return;
  1107. }
  1108. SplitStringByComma(env_str, env_vec);
  1109. if (env_vec.size() > kReuseMaxOpNum) {
  1110. GELOGE(FAILED, "The OP_NO_REUSE_MEM has more than %d nodes.", kReuseMaxOpNum);
  1111. return;
  1112. }
  1113. op_reuse_env_valid = true;
  1114. return;
  1115. }
  1116. Status BlockMemAssigner::AssignOutputMemoryWithReuse(const NodePtr &node, vector<int64_t> &ranges) {
  1117. auto op_desc = node->GetOpDesc();
  1118. int64_t stream_id = op_desc->GetStreamId();
  1119. vector<int64_t> memorys_type;
  1120. bool has_mem_type_attr = ge::AttrUtils::GetListInt(op_desc, ATTR_NAME_OUTPUT_MEM_TYPE_LIST, memorys_type);
  1121. GELOGI("Assign memory node[%s], output size[%d], output memory type size[%d]", op_desc->GetName().c_str(),
  1122. op_desc->GetOutputsSize(), memorys_type.size());
  1123. if (has_mem_type_attr && (memorys_type.size() != op_desc->GetOutputsSize())) {
  1124. GELOGE(INTERNAL_ERROR, "fusion: node[%s], output memory size err[outputsize:%zu, memorysize:%zu]",
  1125. op_desc->GetName().c_str(), op_desc->GetOutputsSize(), memorys_type.size());
  1126. return INTERNAL_ERROR;
  1127. }
  1128. is_op_reuse_mem_ = true;
  1129. if (op_reuse_env_valid_ == true) {
  1130. vector<string>::iterator it_name =
  1131. std::find(op_no_reuse_mem_vec_.begin(), op_no_reuse_mem_vec_.end(), op_desc->GetName());
  1132. vector<string>::iterator it_type =
  1133. std::find(op_no_reuse_mem_vec_.begin(), op_no_reuse_mem_vec_.end(), op_desc->GetType());
  1134. GE_IF_BOOL_EXEC(it_name != op_no_reuse_mem_vec_.end() || it_type != op_no_reuse_mem_vec_.end(),
  1135. is_op_reuse_mem_ = false;);
  1136. }
  1137. bool is_atomic = false;
  1138. // If GetBool fail, is_atomic is false.
  1139. (void)ge::AttrUtils::GetBool(op_desc, ATOMIC_ATTR_IS_ATOMIC_NODE, is_atomic);
  1140. // Allocate memory for the current node and release node memory of the same size in the workspace
  1141. GE_IF_BOOL_EXEC(ge_disable_reuse_mem_env_ != "1",
  1142. for (auto iter = stream_workspace_blocks_.begin(); iter != stream_workspace_blocks_.end();
  1143. ++iter) { ReleaseMemorys(iter->second[stream_id], reusable_blocks_[iter->first][stream_id]); });
  1144. if (IsContinuousOutput(node)) {
  1145. (void)ApplyContinuousMemory(node, ranges, is_op_reuse_mem_);
  1146. return SUCCESS;
  1147. }
  1148. for (uint32_t i = 0; i < static_cast<uint32_t>(op_desc->GetOutputsSize()); i++) {
  1149. int64_t size = 0;
  1150. auto output_op_desc = op_desc->GetOutputDescPtr(i);
  1151. if (output_op_desc != nullptr) {
  1152. GE_IF_BOOL_EXEC(ge::TensorUtils::GetSize(*output_op_desc, size) != SUCCESS, GELOGI("Get size failed"));
  1153. }
  1154. // fusion: other type's size not means malloc HBM memory
  1155. bool l1_flag = has_mem_type_attr && memorys_type[i] == RT_MEMORY_L1;
  1156. if (l1_flag) {
  1157. GELOGI("fusion: node[%s], output[%s], output memory type [%d]",
  1158. op_desc->GetName().c_str(), op_desc->GetOutputNameByIndex(i).c_str(), memorys_type[i]);
  1159. size = 0;
  1160. }
  1161. std::string peer_name;
  1162. uint32_t peer_input_index = 0;
  1163. bool out_node_set_continuous_input = false;
  1164. bool reset_zero_copy_flag = false;
  1165. bool no_need_assign_memory = ((size == 0) || CheckIsZeroMemNodeType(node->GetType()));
  1166. if (!no_need_assign_memory) {
  1167. out_node_set_continuous_input =
  1168. IsOutNodeSetContinuousInput(node, i, peer_name, peer_input_index, no_need_assign_memory, reset_zero_copy_flag);
  1169. GE_IF_BOOL_EXEC(!no_need_assign_memory,
  1170. no_need_assign_memory = IsAtomicOutputMemory(node, i, is_atomic, out_node_set_continuous_input););
  1171. }
  1172. no_need_assign_memory = (no_need_assign_memory || IsKnownSubgraphData(node));
  1173. if (no_need_assign_memory) {
  1174. zero_memory_list_.emplace_back(node, kOutput, i, false);
  1175. continue;
  1176. }
  1177. // atomic can't be reused
  1178. bool need_change = is_op_reuse_mem_ && out_node_set_continuous_input && is_atomic;
  1179. if (need_change) {
  1180. is_op_reuse_mem_ = false;
  1181. }
  1182. MemoryBlock *mem_block = ApplyOutMemory(node, i, ranges, is_op_reuse_mem_, out_node_set_continuous_input);
  1183. if (mem_block != nullptr) {
  1184. GE_IF_BOOL_EXEC(reset_zero_copy_flag,
  1185. mem_block->is_zero_copy_ = false;
  1186. GELOGI("Node[%s] output[%u] need assign memory before reassign.", op_desc->GetName().c_str(), i););
  1187. node_out_blocks_[node->GetName()].emplace_back(mem_block);
  1188. if (out_node_set_continuous_input) {
  1189. node_continuous_input_blocks_[peer_name][peer_input_index] = mem_block;
  1190. }
  1191. NodeIndexIO node_index_io(node, i, kOut);
  1192. auto iter = anchor_to_symbol_.find(node_index_io.ToString());
  1193. if (iter == anchor_to_symbol_.end()) {
  1194. continue;
  1195. }
  1196. symbol_blocks_[iter->second] = mem_block;
  1197. }
  1198. }
  1199. return SUCCESS;
  1200. }
  1201. ///
  1202. /// @ingroup domi
  1203. /// @brief traverse all nodes outputs and workspace in need, apply memory block considering memory reuse
  1204. /// @param [in/out] ranges memory size provided
  1205. /// @return Status result
  1206. ///
  1207. void BlockMemAssigner::AssignMemoryWithReuse(vector<int64_t> &ranges) {
  1208. (void)ge::GetContext().GetOption(OPTION_EXEC_DISABLE_REUSED_MEMORY, ge_disable_reuse_mem_env_);
  1209. GEEVENT("Reuse memory %s", ge_disable_reuse_mem_env_ == "1" ? "close" : "open");
  1210. string op_no_reuse_mem_str;
  1211. const char *op_no_reuse_mem = std::getenv(OP_NO_REUSE_MEM);
  1212. GE_IF_BOOL_EXEC(op_no_reuse_mem != nullptr, op_no_reuse_mem_str = string(op_no_reuse_mem);
  1213. CheckAndGetOpReuseEnv(op_no_reuse_mem_str, op_no_reuse_mem_vec_, op_reuse_env_valid_););
  1214. for (NodePtr &n : compute_graph_->GetAllNodes()) {
  1215. auto node_op_desc = n->GetOpDesc();
  1216. GE_IF_BOOL_EXEC(node_op_desc == nullptr, continue);
  1217. life_time_ = node_op_desc->GetId();
  1218. int64_t stream_id = node_op_desc->GetStreamId();
  1219. if (AssignOutputMemoryWithReuse(n, ranges) != SUCCESS) {
  1220. return;
  1221. }
  1222. for (auto iter = stream_workspace_blocks_.begin(); iter != stream_workspace_blocks_.end(); ++iter) {
  1223. iter->second[stream_id].clear();
  1224. }
  1225. vector<int64_t> temp;
  1226. GetNodeWorkSpaceSize(n, temp);
  1227. vector<int64_t> workspace_bytes;
  1228. vector<int64_t> tvm_workspace_memory_type;
  1229. bool has_tvm_workspace_mem_type_attr =
  1230. ge::AttrUtils::GetListInt(node_op_desc, TVM_ATTR_NAME_WORKSPACE_TYPE, tvm_workspace_memory_type);
  1231. vector<bool> workspace_reuse_flag;
  1232. GE_IF_BOOL_EXEC(!ge::AttrUtils::GetListBool(node_op_desc, kAttrNameWorkspaceReuseFlag, workspace_reuse_flag),
  1233. GELOGD("OP %s get workspace_reuse_flag attr failed", node_op_desc->GetName().c_str()));
  1234. GELOGI("Assign memory node[%s], size [temp:%zu, memory type size:%zu]", node_op_desc->GetName().c_str(),
  1235. temp.size(), tvm_workspace_memory_type.size());
  1236. if (has_tvm_workspace_mem_type_attr && (temp.size() != tvm_workspace_memory_type.size())) {
  1237. GELOGE(INTERNAL_ERROR, "fusion: node[%s], tvm workspace memory size error![v_temp:%zu, workspace:%zu]",
  1238. n->GetName().c_str(), temp.size(), tvm_workspace_memory_type.size());
  1239. return;
  1240. }
  1241. for (size_t i = 0; i < temp.size(); i++) {
  1242. // fusion: other type's size not means malloc HBM memory
  1243. bool workspace_skip_flag = false;
  1244. if (has_tvm_workspace_mem_type_attr && tvm_workspace_memory_type[i] == RT_MEMORY_L1) {
  1245. GELOGI(
  1246. "fusion: node[%s]workspace index[%d] is not hbm type, add to zero_memory_list, workspace memory type [%ld]",
  1247. node_op_desc->GetName().c_str(), i, tvm_workspace_memory_type[i]);
  1248. workspace_skip_flag = true;
  1249. }
  1250. if (temp[i] == 0 || workspace_skip_flag) {
  1251. zero_memory_list_.emplace_back(n, kWorkspace, static_cast<uint32_t>(i), false);
  1252. continue;
  1253. }
  1254. int64_t memory_type = RT_MEMORY_HBM;
  1255. if (!GetWorkSpaceMemoryType(n, i, memory_type)) {
  1256. GELOGW("Get workspace memory type failed.");
  1257. return;
  1258. }
  1259. MemoryBlock *mem_block = ApplyMemory(GetBlockSize(static_cast<size_t>(temp[i]), ranges),
  1260. static_cast<size_t>(temp[i]), static_cast<size_t>(temp[i]),
  1261. kWorkspace, n, static_cast<uint32_t>(i), workspace_reuse_flag,
  1262. is_op_reuse_mem_, false, memory_type);
  1263. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(mem_block == nullptr, continue, "failed to apply memory block.");
  1264. CheckWorkspaceReuse(workspace_reuse_flag, i, stream_id, mem_block, memory_type);
  1265. }
  1266. for (auto it = reusable_blocks_.begin(); it != reusable_blocks_.end(); ++it) {
  1267. ReleaseInputNodeOutMemory(node_out_blocks_, it->second[stream_id], n);
  1268. }
  1269. }
  1270. GELOGD("Assigned memory blocks:");
  1271. for (auto mem_block : memory_blocks_) {
  1272. GELOGD("%s", mem_block->String().c_str());
  1273. (void)mem_block; // Fix warning
  1274. }
  1275. bool merge_dynamic_batch = false;
  1276. GE_IF_BOOL_EXEC(!(ge_disable_reuse_mem_env_ == "1"), merge_dynamic_batch = MergeDynamicBatchBlocks());
  1277. GE_IF_BOOL_EXEC((!(ge_disable_reuse_mem_env_ == "1") && !merge_dynamic_batch), ReuseBlocksByLifeTime(ranges.size()));
  1278. AssignContinuousBlocks();
  1279. ResizeMemoryBlocks();
  1280. GELOGD("Memory blocks after resize:");
  1281. for (auto mem_block : memory_blocks_) {
  1282. GELOGD("%s", mem_block->String().c_str());
  1283. (void)mem_block; // Fix warning
  1284. }
  1285. }
  1286. void BlockMemAssigner::CheckWorkspaceReuse(const vector<bool> &workspace_reuse_flag, uint32_t index, int64_t stream_id,
  1287. MemoryBlock *mem_block, int64_t memory_type) {
  1288. bool reuse_mem_flag =
  1289. ((workspace_reuse_flag.size() > index) && (workspace_reuse_flag[index] == false)) ? false : true;
  1290. if (reuse_mem_flag) {
  1291. stream_workspace_blocks_[memory_type][stream_id].emplace_back(mem_block);
  1292. }
  1293. }
  1294. void BlockMemAssigner::GetNodeWorkSpaceSize(const NodePtr &node, vector<int64_t> &workspace_memory) {
  1295. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(node->GetOpDesc() == nullptr, return, "Op desc is null.");
  1296. vector<int64_t> workspace_byte_nums = node->GetOpDesc()->GetWorkspaceBytes();
  1297. GELOGD("node[%s] size:%zu", node->GetOpDesc()->GetName().c_str(), workspace_byte_nums.size());
  1298. for (int64_t byte_size : workspace_byte_nums) {
  1299. workspace_memory.emplace_back(byte_size);
  1300. GELOGD("push back size:%ld", byte_size);
  1301. }
  1302. }
  1303. // descending order
  1304. static bool CompareBlockMaxSize(MemoryBlock *left, MemoryBlock *right) {
  1305. if (left == nullptr || right == nullptr) {
  1306. return false;
  1307. }
  1308. auto left_max_size = std::max_element(left->RealSizeList().begin(), left->RealSizeList().end());
  1309. if (left_max_size != left->RealSizeList().end()) {
  1310. auto right_max_size = std::max_element(right->RealSizeList().begin(), right->RealSizeList().end());
  1311. if (right_max_size == right->RealSizeList().end() || (*left_max_size > *right_max_size)) {
  1312. return true;
  1313. }
  1314. }
  1315. return false;
  1316. }
  1317. void MergeBlocks(std::vector<MemoryBlock *> &dest, std::vector<MemoryBlock *> &src) {
  1318. for (size_t i = 0; i < dest.size(); ++i) {
  1319. if (i >= src.size()) {
  1320. return;
  1321. }
  1322. if (dest[i] != nullptr && src[i] != nullptr) {
  1323. if (!dest[i]->reuse_mem_ || !src[i]->reuse_mem_) {
  1324. GELOGD("Diff batch's workspace can't be reused, i: %zu, dest[i]: %s, stream: %ld, src[i]: %s, stream: %ld.",
  1325. i, dest[i]->String().c_str(), dest[i]->stream_id_, src[i]->String().c_str(), src[i]->stream_id_);
  1326. continue;
  1327. }
  1328. for (auto &symbol : src[i]->SymbolList()) {
  1329. dest[i]->AddSymbol(symbol);
  1330. }
  1331. for (size_t j = 0; j < src[i]->NodeTypeIndexList().size(); ++j) {
  1332. dest[i]->AddNodeTypeIndex(src[i]->NodeTypeIndexList()[j],
  1333. src[i]->RealSizeList()[j],
  1334. src[i]->NoAlignSizeList()[j]);
  1335. src[i]->deleted_block_ = true;
  1336. }
  1337. }
  1338. }
  1339. }
  1340. bool BlockMemAssigner::MergeDynamicBatchBlocks() {
  1341. bool merged = false;
  1342. std::map<std::string, std::vector<MemoryBlock *>> dynamic_batch_blocks;
  1343. for (auto block : memory_blocks_) {
  1344. if (block == nullptr) {
  1345. continue;
  1346. }
  1347. std::string batch_label;
  1348. if (block->IsSameLabel(batch_label)) {
  1349. dynamic_batch_blocks[batch_label].emplace_back(block);
  1350. }
  1351. }
  1352. auto it = dynamic_batch_blocks.begin();
  1353. auto it_max = it;
  1354. // find max block counts
  1355. for (; it != dynamic_batch_blocks.end(); ++it) {
  1356. if (it->second.size() > it_max->second.size()) {
  1357. it_max = it;
  1358. }
  1359. std::sort(it->second.begin(), it->second.end(), CompareBlockMaxSize);
  1360. }
  1361. if (it_max != dynamic_batch_blocks.end()) {
  1362. GELOGD("MergeDynamicBatch %s block counts %zu", it_max->first.c_str(), it_max->second.size());
  1363. }
  1364. for (it = dynamic_batch_blocks.begin(); it != dynamic_batch_blocks.end(); ++it) {
  1365. if (it != it_max) {
  1366. GELOGD("MergeDynamicBatch from %s to %s", it->first.c_str(), it_max->first.c_str());
  1367. MergeBlocks(it_max->second, it->second);
  1368. merged = true;
  1369. }
  1370. }
  1371. return merged;
  1372. }
  1373. // asending order
  1374. static bool CompareBlockIndex(MemoryBlock *left, MemoryBlock *right) {
  1375. if (left == nullptr || right == nullptr) {
  1376. return false;
  1377. }
  1378. if (left->input_index_ < right->input_index_) {
  1379. return true;
  1380. }
  1381. return false;
  1382. }
  1383. ///
  1384. /// @ingroup domi
  1385. /// @brief order blocks by continuous input index
  1386. /// @param [in] blocks need be processed
  1387. /// @param [in] input blocks need continuous
  1388. /// @param [out] blocks after continuous order
  1389. /// @param [in/out] blocks ordered
  1390. /// @param [in] input or output
  1391. ///
  1392. void ReAssignContinuousBlocks(const std::vector<MemoryBlock *> &org_blocks,
  1393. const std::map<MemoryBlock *, uint32_t> block_map,
  1394. std::vector<MemoryBlock *> &dest_blocks, std::vector<MemoryBlock *> &continuous_blocks,
  1395. const std::string &type) {
  1396. for (auto &memory_block : org_blocks) {
  1397. if (memory_block == nullptr || memory_block->deleted_block_) {
  1398. continue;
  1399. }
  1400. if (block_map.find(memory_block) != block_map.end()) {
  1401. continue;
  1402. }
  1403. dest_blocks.emplace_back(memory_block);
  1404. }
  1405. // add continuous block
  1406. std::sort(continuous_blocks.begin(), continuous_blocks.end(), CompareBlockIndex);
  1407. size_t count = 0;
  1408. for (auto &memory_block : continuous_blocks) {
  1409. GE_IF_BOOL_EXEC(memory_block == nullptr, continue);
  1410. GELOGI("Block continuous %s index:%d", type.c_str(), memory_block->input_index_);
  1411. count++;
  1412. if (count == 1) {
  1413. memory_block->first_continuous_block_ = true;
  1414. }
  1415. if (count == continuous_blocks.size()) {
  1416. memory_block->last_continuous_block_ = true;
  1417. }
  1418. dest_blocks.emplace_back(memory_block);
  1419. }
  1420. }
  1421. void BlockMemAssigner::AssignContinuousBlocks() {
  1422. for (auto &block_map : node_continuous_input_blocks_) {
  1423. std::vector<MemoryBlock *> dest_memory_blocks;
  1424. std::map<MemoryBlock *, uint32_t> continuous_block_map;
  1425. std::vector<MemoryBlock *> continuous_blocks;
  1426. auto it = node_continuous_input_counts_.find(block_map.first);
  1427. GE_IF_BOOL_EXEC(it == node_continuous_input_counts_.end(), continue);
  1428. GELOGI("Node:%s continuous input block count:%zu input count:%u", block_map.first.c_str(), block_map.second.size(),
  1429. it->second);
  1430. GE_IF_BOOL_EXEC(it->second != block_map.second.size(), continue);
  1431. for (auto &it : block_map.second) {
  1432. if (it.second != nullptr) {
  1433. continuous_block_map[it.second] = it.first;
  1434. it.second->input_index_ = it.first;
  1435. continuous_blocks.emplace_back(it.second);
  1436. }
  1437. }
  1438. if (continuous_block_map.size() != continuous_blocks.size()) {
  1439. GELOGW("Node:%s continuous input map size:%zu vector size:%zu", block_map.first.c_str(),
  1440. continuous_block_map.size(), continuous_blocks.size());
  1441. continue;
  1442. }
  1443. ReAssignContinuousBlocks(memory_blocks_, continuous_block_map, dest_memory_blocks, continuous_blocks, "input");
  1444. memory_blocks_.swap(dest_memory_blocks);
  1445. }
  1446. }
  1447. void BlockMemAssigner::ReuseBlocksByLifeTime(size_t range_size) {
  1448. // 1 means block size is same so no need to do this
  1449. if (range_size <= 1) {
  1450. return;
  1451. }
  1452. for (size_t i = 0; i < memory_blocks_.size(); ++i) {
  1453. auto parent = memory_blocks_[i];
  1454. if (parent == nullptr || parent->deleted_block_ || parent->continuous_block_) {
  1455. continue;
  1456. }
  1457. if (parent->reuse_mem_ && !IsPostReuse(parent)) {
  1458. parent->reuse_mem_ = false;
  1459. }
  1460. for (size_t j = i + 1; j < memory_blocks_.size(); ++j) {
  1461. auto child = memory_blocks_[j];
  1462. if (child == nullptr) {
  1463. continue;
  1464. }
  1465. // If node is before atomic_addr_clean node, the continus memory can't be reused.
  1466. if (!parent->NodeTypeIndexList().empty() && child->continuous_block_) {
  1467. auto node = parent->NodeTypeIndexList()[0].node;
  1468. if (node == nullptr || node->GetOpDesc() == nullptr || (node->GetOpDesc()->GetId() < GetAtomicAddrCleanId())) {
  1469. continue;
  1470. }
  1471. }
  1472. parent->AddLifeReuseBlock(child, total_node_depend_stream_life_);
  1473. }
  1474. }
  1475. }
  1476. ///
  1477. /// @ingroup domi_omg
  1478. /// @brief traverse memory size, resize, calculate offset
  1479. /// @param [in&out] memory_blocks_ memory block, after calculating offset
  1480. ///
  1481. void BlockMemAssigner::ResizeMemoryBlocks() {
  1482. for (auto &memory_block : memory_blocks_) {
  1483. if (memory_block == nullptr || memory_block->deleted_block_ || memory_block->is_zero_copy_) {
  1484. continue;
  1485. }
  1486. if (memory_block->memory_type_ == RT_MEMORY_HBM) {
  1487. if (memory_block->first_continuous_block_) {
  1488. mem_offset_ += MEM_ALIGN_SIZE;
  1489. }
  1490. memory_block->Resize();
  1491. memory_block->SetHeadOffset(mem_offset_);
  1492. mem_offset_ += memory_block->Size();
  1493. memory_block->SetTailOffset(mem_offset_ - 1);
  1494. } else if (memory_block->memory_type_ == RT_MEMORY_P2P_DDR) {
  1495. if (memory_block->first_continuous_block_) {
  1496. p2p_mem_offset_ += MEM_ALIGN_SIZE;
  1497. }
  1498. memory_block->Resize();
  1499. memory_block->SetHeadOffset(p2p_mem_offset_);
  1500. p2p_mem_offset_ += memory_block->Size();
  1501. memory_block->SetTailOffset(p2p_mem_offset_ - 1);
  1502. }
  1503. }
  1504. GELOGI("mem_offset_ exclude zero_copy_memory is %zu, p2p_mem_offset_ exclude zero_copy_memory is %zu.",
  1505. mem_offset_, p2p_mem_offset_);
  1506. }
  1507. ///
  1508. /// @ingroup domi
  1509. /// @brief given NodeTypeIndex, set offset in Op's OpDef
  1510. /// @param [in&out] node_type_index <node, memory type, id>
  1511. /// @param [in] offset offset to be set
  1512. /// @param [in] size memory size
  1513. /// @param [in] real_size memory size in need
  1514. /// @return Status result
  1515. ///
  1516. void SetOffsetSize(const NodeTypeIndex &node_type, const MemoryBlock *block,
  1517. size_t real_size, size_t no_align_size, bool child_block) {
  1518. ge::OpDescPtr op_desc = node_type.node->GetOpDesc();
  1519. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(op_desc == nullptr, return, "op_desc is null.");
  1520. string graph_name = node_type.node->GetOwnerComputeGraph()->GetName();
  1521. vector<int64_t> memorys_type;
  1522. int64_t offset = block->HeadOffset();
  1523. size_t end = node_type.life_time_end;
  1524. bool has_mem_type_attr = ge::AttrUtils::GetListInt(op_desc, ATTR_NAME_OUTPUT_MEM_TYPE_LIST, memorys_type);
  1525. if (node_type.mem_type == kOutput) {
  1526. vector<int64_t> output_list = op_desc->GetOutputOffset();
  1527. for (auto i = static_cast<uint32_t>(output_list.size()); i < node_type.index + 1; i++) {
  1528. output_list.emplace_back(kInvalidOffset);
  1529. }
  1530. if (output_list.empty()) {
  1531. GELOGW("Empty output");
  1532. return;
  1533. }
  1534. static const set<string> kSetOffsetTypes = { DATA_TYPE, AIPP_DATA_TYPE, MULTISHAPE, NETOUTPUT };
  1535. if ((kSetOffsetTypes.count(op_desc->GetType()) > 0) && !IsKnownSubgraphData(node_type.node)) {
  1536. if ((output_list[node_type.index] == kInvalidOffset) || (output_list[node_type.index] < offset)) {
  1537. output_list.at(node_type.index) = offset;
  1538. }
  1539. } else {
  1540. // fusion: keep the original other type offset value from op_desc
  1541. bool set_out_offset = (!has_mem_type_attr) ||
  1542. (memorys_type.size() > node_type.index && memorys_type[node_type.index] != RT_MEMORY_L1);
  1543. if (set_out_offset) {
  1544. output_list.at(node_type.index) = offset;
  1545. }
  1546. }
  1547. op_desc->SetOutputOffset(output_list);
  1548. } else if (node_type.mem_type == kWorkspace) {
  1549. vector<int64_t> workspace_list;
  1550. workspace_list = op_desc->GetWorkspace();
  1551. for (auto i = static_cast<uint32_t>(workspace_list.size()); i < node_type.index + 1; i++) {
  1552. workspace_list.emplace_back(kInvalidOffset);
  1553. }
  1554. vector<int64_t> workspace_mem_type;
  1555. bool has_workspace_mem_type = ge::AttrUtils::GetListInt(op_desc, TVM_ATTR_NAME_WORKSPACE_TYPE, workspace_mem_type);
  1556. // fusion: keep the original other type offset value from op_desc
  1557. bool set_workspace_offset = (!has_workspace_mem_type) ||
  1558. (workspace_mem_type.size() > node_type.index && workspace_mem_type[node_type.index] != RT_MEMORY_L1);
  1559. if (set_workspace_offset) {
  1560. workspace_list.at(node_type.index) = offset;
  1561. }
  1562. op_desc->SetWorkspace(workspace_list);
  1563. }
  1564. GELOGI("[IMAS]Set %s name[%s] %s[%u] offset to [%ld] streamid[%ld] size[%zu] realsize[%zu]"
  1565. " noalignsize[%zu] life time begin[%zu] life time end[%zu] child[%d:%d:%d:%d] isref[%d].", graph_name.c_str(),
  1566. op_desc->GetName().c_str(), node_type.GetMemType().c_str(), node_type.index, offset, op_desc->GetStreamId(),
  1567. block->Size(), real_size, no_align_size, op_desc->GetId(), end, child_block, block->reuse_mem_,
  1568. block->continuous_block_, block->deleted_block_, node_type.ref_input);
  1569. }
  1570. void SetBlockOpMemOffset(MemoryBlock *block, bool child_block) {
  1571. if (block == nullptr) {
  1572. return;
  1573. }
  1574. size_t index = 0;
  1575. size_t real_size = 0;
  1576. size_t no_align_size = 0;
  1577. auto real_size_list_size = block->RealSizeList().size();
  1578. for (const NodeTypeIndex &node_type_index : block->NodeTypeIndexList()) {
  1579. if (index < real_size_list_size) {
  1580. real_size = block->RealSizeList()[index];
  1581. no_align_size = block->NoAlignSizeList()[index];
  1582. }
  1583. SetOffsetSize(node_type_index, block, real_size, no_align_size, child_block);
  1584. index++;
  1585. }
  1586. }
  1587. void BlockMemAssigner::SetOpMemOffset(bool is_zero_copy) {
  1588. for (MemoryBlock *memory_block : memory_blocks_) {
  1589. if (memory_block == nullptr || memory_block->deleted_block_) {
  1590. continue;
  1591. }
  1592. if ((is_zero_copy && !memory_block->is_zero_copy_) || (!is_zero_copy && memory_block->is_zero_copy_)) {
  1593. continue;
  1594. }
  1595. SetBlockOpMemOffset(memory_block, false);
  1596. for (MemoryBlock *child_block : memory_block->ChildBlockList()) {
  1597. SetBlockOpMemOffset(child_block, true);
  1598. }
  1599. }
  1600. if (!is_zero_copy) {
  1601. for (const NodeTypeIndex &node_type_index : zero_memory_list_) {
  1602. MemoryBlock block(0, 0);
  1603. SetOffsetSize(node_type_index, &block, 0, 0, false);
  1604. }
  1605. }
  1606. }
  1607. Status BlockMemAssigner::Assign() {
  1608. vector<int64_t> ranges;
  1609. if (GetMemoryRanges(ranges) != SUCCESS) {
  1610. GELOGE(FAILED, "GetMemoryRanges Fail!");
  1611. return FAILED;
  1612. }
  1613. GE_IF_BOOL_EXEC(ranges.empty(), return SUCCESS);
  1614. AssignMemoryWithReuse(ranges);
  1615. SetOpMemOffset(false);
  1616. return SUCCESS;
  1617. }
  1618. bool BlockMemAssigner::CheckIsZeroMemNodeType(const string &node_type) const {
  1619. return (node_type == VARIABLE) || (node_type == CONSTANT) || (node_type == MULTISHAPE) ||
  1620. (node_type == CONSTANTOP) || (node_type == ASSIGNADD) || (node_type == ASSIGNSUB) ||
  1621. (node_type == ASSIGN) || (node_type == HVDWAIT);
  1622. }
  1623. bool BlockMemAssigner::GetWorkSpaceMemoryType(const NodePtr &node, size_t index, int64_t &memory_type) {
  1624. memory_type = RT_MEMORY_HBM;
  1625. vector<int64_t> workspace_memory_type;
  1626. auto op_desc = node->GetOpDesc();
  1627. bool has_workspace_mem_type_attr =
  1628. ge::AttrUtils::GetListInt(op_desc, TVM_ATTR_NAME_WORKSPACE_TYPE, workspace_memory_type);
  1629. if (has_workspace_mem_type_attr && (workspace_memory_type.size() <= index)) {
  1630. GELOGE(INTERNAL_ERROR, "node[%s], workspace_memory size error![index:%zu, workspace:%zu]",
  1631. node->GetName().c_str(), index, workspace_memory_type.size());
  1632. return false;
  1633. }
  1634. memory_type = has_workspace_mem_type_attr ? workspace_memory_type[index] : RT_MEMORY_HBM;
  1635. return true;
  1636. }
  1637. } // namespace ge

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