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
4 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
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
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
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
4 years ago
5 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
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
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
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
4 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776
  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. for (auto &out_anchor : n->GetAllOutDataAnchors()) {
  395. GeTensorDesc output_desc = node_op_desc->GetOutputDesc(out_anchor->GetIdx());
  396. bool reuse_input = false;
  397. GE_IF_BOOL_EXEC(ge::TensorUtils::GetReuseInput(output_desc, reuse_input) != SUCCESS,
  398. GELOGI("Get reuse_input failed"));
  399. if (!reuse_input) {
  400. int64_t size = 0;
  401. GE_IF_BOOL_EXEC(ge::TensorUtils::GetSize(output_desc, size) != SUCCESS, GELOGI("Get size failed"));
  402. if (anchor_to_symbol_.empty()) {
  403. all_memory_size.emplace_back(size);
  404. } else {
  405. auto iter1 = anchor_to_symbol_.find(NodeIndexIO(n, out_anchor->GetIdx(), kOut).ToString());
  406. if (iter1 == anchor_to_symbol_.end()) {
  407. continue;
  408. }
  409. const std::string &symbol = iter1->second;
  410. auto iter2 = symbol_size_.find(symbol);
  411. if (iter2 == symbol_size_.end()) {
  412. symbol_size_[symbol] = size;
  413. } else if (size > static_cast<int64_t>(iter2->second)) {
  414. iter2->second = size;
  415. }
  416. }
  417. }
  418. }
  419. temp.clear();
  420. GetNodeWorkSpaceSize(n, temp);
  421. all_memory_size.insert(all_memory_size.end(), temp.begin(), temp.end());
  422. }
  423. for (const auto &pair : symbol_size_) {
  424. all_memory_size.emplace_back(pair.second);
  425. }
  426. sort(all_memory_size.begin(), all_memory_size.end());
  427. GELOGD("All memory size: %s", ToString(all_memory_size).c_str());
  428. for (auto iter = all_memory_size.begin(); iter != all_memory_size.end();) {
  429. if (*iter == 0) {
  430. iter = all_memory_size.erase(iter);
  431. } else {
  432. ++iter;
  433. }
  434. }
  435. InitReuseFlag();
  436. PrintSymbolMap();
  437. }
  438. ///
  439. /// @ingroup domi
  440. /// @brief decide memory size based on actual input memory size
  441. /// @param [in] size actual memory size in need
  442. /// @param [in] ranges memory size provided
  443. /// @return size_t memory size to apply
  444. ///
  445. size_t GetBlockSize(size_t size, const vector<int64_t> &ranges) {
  446. for (int64_t x : ranges) {
  447. auto x_temp = static_cast<size_t>(x);
  448. if (size <= x_temp) {
  449. return x_temp;
  450. }
  451. }
  452. GELOGW("Memory needed size:%zu is beyond the biggest block in memory ranges.", size);
  453. return size;
  454. }
  455. bool IsDirectOutputNode(const NodePtr &node, int idx) {
  456. if ((node != nullptr) && (node->GetOpDesc() != nullptr) && (node->GetOpDesc()->GetType() == NETOUTPUT)) {
  457. GELOGD("This is netoutput node, the input node mem can not be reused");
  458. return true;
  459. }
  460. return false;
  461. }
  462. void AddReusableBlockCount(const MemoryBlock &mem_block, map<string, uint64_t> &reusable_block_counts) {
  463. string key = std::to_string(mem_block.Size());
  464. key += "_" + std::to_string(mem_block.stream_id_);
  465. key += "_" + std::to_string(mem_block.memory_type_);
  466. auto it = reusable_block_counts.find(key);
  467. if (it != reusable_block_counts.end()) {
  468. it->second++;
  469. } else {
  470. reusable_block_counts[key] = 1;
  471. }
  472. }
  473. void ReduceReusableBlockCount(const MemoryBlock &mem_block, map<string, uint64_t> &reusable_block_counts) {
  474. string key = std::to_string(mem_block.Size());
  475. key += "_" + std::to_string(mem_block.stream_id_);
  476. key += "_" + std::to_string(mem_block.memory_type_);
  477. auto it = reusable_block_counts.find(key);
  478. if (it != reusable_block_counts.end()) {
  479. if (it->second > 0) {
  480. it->second--;
  481. }
  482. }
  483. }
  484. bool CanReuseBySize(const map<string, uint64_t> &reusable_block_counts, const MemoryBlock &reusable_block,
  485. size_t block_size, size_t real_size, bool continuous) {
  486. bool can_reuse = false;
  487. if (reusable_block.Size() == block_size) {
  488. can_reuse = true;
  489. } else {
  490. string key = std::to_string(reusable_block.Size());
  491. key += "_" + std::to_string(reusable_block.stream_id_);
  492. key += "_" + std::to_string(reusable_block.memory_type_);
  493. auto it = reusable_block_counts.find(key);
  494. GE_IF_BOOL_EXEC((it != reusable_block_counts.end() && (it->second > kReuseMaxCount)) &&
  495. (reusable_block.Size() > block_size),
  496. can_reuse = true;
  497. GELOGD("Less size mem reuse, reuse block size:%zu, current block size:%zu",
  498. reusable_block.Size(), block_size););
  499. }
  500. return can_reuse;
  501. }
  502. bool BlockMemAssigner::IsOutNodeSetContinuousInput(const NodePtr &n, uint32_t out_index, std::string &peer_name,
  503. uint32_t &peer_input_index,
  504. bool &no_need_assign_memory, bool &reset_zero_copy_flag) {
  505. if (n == nullptr || n->GetAllOutDataAnchors().size() <= 0) {
  506. return false;
  507. }
  508. if (static_cast<size_t>(out_index) < n->GetAllOutDataAnchors().size()) {
  509. auto out_anchor = n->GetOutDataAnchor(out_index);
  510. GE_IF_BOOL_EXEC(out_anchor == nullptr,
  511. GELOGE(FAILED, "Node[%s] output[%u] anchor is null.", n->GetName().c_str(), out_index);
  512. return false;);
  513. for (auto const &peer_in_anchor : out_anchor->GetPeerInDataAnchors()) {
  514. GE_IF_BOOL_EXEC(peer_in_anchor == nullptr,
  515. GELOGE(FAILED, "Node[%s] output[%u] peer_in_anchor 0 is null.", n->GetName().c_str(), out_index);
  516. return false;);
  517. auto peer_node = peer_in_anchor->GetOwnerNode();
  518. GE_IF_BOOL_EXEC(peer_node == nullptr,
  519. GELOGE(FAILED, "Node[%s] output[%u] node is null.", n->GetName().c_str(), out_index);
  520. return false;);
  521. // Get the continuous input type of the node, default is false
  522. bool is_input_continuous = false;
  523. auto peer_in_node_desc = peer_node->GetOpDesc();
  524. GE_IF_BOOL_EXEC(peer_in_node_desc == nullptr,
  525. GELOGE(FAILED, "Node[%s] output[%u] nodedesc is null.", n->GetName().c_str(), out_index);
  526. return false;);
  527. // If GetBool fail, is_input_continuous is false.
  528. bool is_input_continuous_no_padding = false;
  529. (void)ge::AttrUtils::GetBool(peer_in_node_desc, ATTR_NAME_NOPADDING_CONTINUOUS_INPUT,
  530. is_input_continuous_no_padding);
  531. if (is_input_continuous_no_padding) {
  532. reset_zero_copy_flag = true;
  533. return false;
  534. }
  535. (void)ge::AttrUtils::GetBool(peer_in_node_desc, ATTR_NAME_CONTINUOUS_INPUT, is_input_continuous);
  536. GE_IF_BOOL_EXEC(is_input_continuous && CheckIsZeroMemNodeType(peer_node->GetType()),
  537. GELOGI("Node[%s] output[%u] no_need_assign_memory.", n->GetName().c_str(), out_index);
  538. no_need_assign_memory = true;
  539. return false;);
  540. if (is_input_continuous) {
  541. if (n->GetOwnerComputeGraph() != nullptr) {
  542. string graph_name = n->GetOwnerComputeGraph()->GetName();
  543. GELOGI("%s name[%s] output[%u] node[%s] set input[%d] continuous, input size[%u].", graph_name.c_str(),
  544. n->GetName().c_str(), out_index, peer_in_node_desc->GetName().c_str(), peer_in_anchor->GetIdx(),
  545. peer_node->GetAllInDataAnchorsSize());
  546. // Only set attr one times.
  547. if (node_continuous_input_blocks_[peer_in_node_desc->GetName()].size() == 0) {
  548. (void)ge::AttrUtils::SetBool(peer_in_node_desc, ATTR_NAME_CONTINUOUS_INPUT_ALLOC, true);
  549. node_continuous_input_counts_[peer_in_node_desc->GetName()] = peer_node->GetAllInDataAnchorsSize();
  550. }
  551. peer_input_index = peer_in_anchor->GetIdx();
  552. peer_name = peer_in_node_desc->GetName();
  553. return true;
  554. }
  555. }
  556. }
  557. }
  558. return false;
  559. }
  560. ///
  561. /// @ingroup GE
  562. /// @brief Check pre_reuse flag & post_reuse glag for each symbol
  563. /// @return void
  564. ///
  565. void BlockMemAssigner::InitReuseFlag() {
  566. static const std::set<std::string> kPreReuseTypes = { ge::DATA_TYPE, ge::AIPP_DATA_TYPE, ge::ANN_DATA_TYPE,
  567. ge::NETOUTPUT, ge::PROPOSAL, ge::ZEROSLIKE,
  568. ge::CONSTANT, ge::CONSTANTOP };
  569. static const std::set<std::string> kPostReuseTypes = { ge::DATA_TYPE, ge::AIPP_DATA_TYPE, ge::ENTER, ge::REFENTER,
  570. ge::NEXTITERATION, ge::REFNEXTITERATION };
  571. for (const auto &pair : symbol_to_anchors_) {
  572. std::string symbol = pair.first;
  573. bool pre_reuse_flag = true;
  574. bool post_reuse_flag = true;
  575. // default memory type
  576. int64_t mem_type = RT_MEMORY_HBM;
  577. GetSymbolMemType(pair.second, mem_type);
  578. GELOGD("The memory type of symbol[%s] is [%ld]].", symbol.c_str(), mem_type);
  579. if (mem_type == RT_MEMORY_P2P_DDR) {
  580. UpdateOpTensorMemType(pair.second, mem_type);
  581. }
  582. // Only the memory with special requirements is processed. The HBM uses the default processing mode.
  583. if (mem_type == RT_MEMORY_P2P_DDR) {
  584. symbol_to_mem_type_[symbol] = mem_type;
  585. }
  586. for (const auto &node_index_io : pair.second) {
  587. if (node_index_io.io_type_ == kIn) {
  588. continue;
  589. }
  590. OutDataAnchorPtr out_anchor = node_index_io.node_->GetOutDataAnchor(node_index_io.index_);
  591. if (out_anchor == nullptr) {
  592. continue;
  593. }
  594. bool out_flg = false;
  595. if (node_index_io.node_->GetOutDataNodes().empty()) {
  596. out_flg = true;
  597. }
  598. for (const auto &in_anchor : out_anchor->GetPeerInDataAnchors()) {
  599. if (IsDirectOutputNode(in_anchor->GetOwnerNode(), in_anchor->GetIdx())) {
  600. out_flg = true;
  601. break;
  602. }
  603. }
  604. const std::string &type = out_anchor->GetOwnerNode()->GetType();
  605. pre_reuse_flag = pre_reuse_flag && !out_flg && (kPreReuseTypes.count(type) == 0);
  606. post_reuse_flag = post_reuse_flag && (kPostReuseTypes.count(type) == 0);
  607. if (!pre_reuse_flag && !post_reuse_flag) {
  608. break;
  609. }
  610. }
  611. pre_reuse_flag_[symbol] = pre_reuse_flag;
  612. post_reuse_flag_[symbol] = post_reuse_flag;
  613. }
  614. }
  615. ///
  616. /// @ingroup GE
  617. /// @brief get pre_reuse flag
  618. /// @param [in] node
  619. /// @param [in] out_index
  620. /// @return bool
  621. ///
  622. bool BlockMemAssigner::IsPreReuse(const NodePtr &node, uint32_t out_index) const {
  623. OutDataAnchorPtr out_data_anchor = nullptr;
  624. if (static_cast<size_t>(out_index) < node->GetAllOutDataAnchors().size()) {
  625. out_data_anchor = node->GetOutDataAnchor(out_index);
  626. }
  627. if (out_data_anchor == nullptr) {
  628. return false;
  629. }
  630. NodeIndexIO cur_node_index_io(out_data_anchor->GetOwnerNode(), out_data_anchor->GetIdx(), kOut);
  631. auto iter1 = anchor_to_symbol_.find(cur_node_index_io.ToString());
  632. if (iter1 == anchor_to_symbol_.end()) {
  633. return false;
  634. }
  635. const std::string &symbol = iter1->second;
  636. auto iter2 = pre_reuse_flag_.find(symbol);
  637. if (iter2 == pre_reuse_flag_.end()) {
  638. return false;
  639. }
  640. return iter2->second;
  641. }
  642. ///
  643. /// @ingroup GE
  644. /// @brief get post_reuse flag
  645. /// @param [in] mem_block
  646. /// @return bool
  647. ///
  648. bool BlockMemAssigner::IsPostReuse(const MemoryBlock *mem_block) const {
  649. if (mem_block == nullptr) {
  650. return false;
  651. }
  652. for (const auto &symbol : mem_block->SymbolList()) {
  653. auto iter = post_reuse_flag_.find(symbol);
  654. if (iter == post_reuse_flag_.end()) {
  655. continue;
  656. }
  657. if (!iter->second) {
  658. return false;
  659. }
  660. }
  661. return true;
  662. }
  663. ///
  664. /// @ingroup GE
  665. /// @brief check if symbol of cur node_index_io has block
  666. /// @param [in] node_index_io
  667. /// @param [out] symbol
  668. /// @return bool
  669. ///
  670. bool BlockMemAssigner::IsSymbolExist(const NodeIndexIO &node_index_io, string &symbol) {
  671. auto iter = anchor_to_symbol_.find(node_index_io.ToString());
  672. if (iter == anchor_to_symbol_.end()) {
  673. return false;
  674. }
  675. symbol = iter->second;
  676. return symbol_blocks_.find(iter->second) != symbol_blocks_.end();
  677. }
  678. ///
  679. /// @ingroup GE
  680. /// @brief Print symbol
  681. /// @return void
  682. ///
  683. void BlockMemAssigner::PrintSymbolMap() {
  684. for (const auto &pair : symbol_to_anchors_) {
  685. GELOGD("symbol=%s, max_size=%zu, pre_reuse=%s, post_reuse=%s", pair.first.c_str(), symbol_size_[pair.first],
  686. pre_reuse_flag_[pair.first] ? "true" : "false", post_reuse_flag_[pair.first] ? "true" : "false");
  687. for (const auto &node_index_io : pair.second) {
  688. GELOGD("anchor:%s", node_index_io.ToString().c_str());
  689. }
  690. }
  691. }
  692. void BlockMemAssigner::GetSymbolMemType(std::list<NodeIndexIO> node_index_io_list, int64_t &memory_type) {
  693. memory_type = RT_MEMORY_HBM;
  694. vector<int64_t> memory_types;
  695. for (auto &node_index_io : node_index_io_list) {
  696. auto op_desc = node_index_io.node_->GetOpDesc();
  697. if (op_desc == nullptr) {
  698. GELOGW("Node[%s] op desc is null.", node_index_io.node_->GetName().c_str());
  699. return;
  700. }
  701. if (node_index_io.io_type_ == kIn) {
  702. vector<int64_t> input_memory_types;
  703. (void) ge::AttrUtils::GetListInt(op_desc, ATTR_NAME_INPUT_MEM_TYPE_LIST, input_memory_types);
  704. if (!input_memory_types.empty() && node_index_io.index_ < input_memory_types.size()) {
  705. int64_t input_memory_type = input_memory_types[node_index_io.index_];
  706. GELOGD("Node[%s]: the memory type of input index [%u] is [%ld]].", op_desc->GetName().c_str(),
  707. node_index_io.index_, input_memory_type);
  708. memory_types.emplace_back(input_memory_type);
  709. }
  710. }
  711. if (node_index_io.io_type_ == kOut) {
  712. vector<int64_t> output_memory_types;
  713. (void) ge::AttrUtils::GetListInt(op_desc, ATTR_NAME_OUTPUT_MEM_TYPE_LIST, output_memory_types);
  714. if (!output_memory_types.empty() && node_index_io.index_ < output_memory_types.size()) {
  715. int64_t output_memory_type = output_memory_types[node_index_io.index_];
  716. GELOGD("Node[%s]: the memory type of output index [%u] is [%ld]].", op_desc->GetName().c_str(),
  717. node_index_io.index_, output_memory_type);
  718. memory_types.emplace_back(output_memory_type);
  719. }
  720. }
  721. }
  722. // memory priority
  723. for (auto node_memory_type : memory_types) {
  724. if (node_memory_type > memory_type) {
  725. memory_type = node_memory_type;
  726. }
  727. }
  728. }
  729. void BlockMemAssigner::UpdateOpTensorMemType(std::list<NodeIndexIO> node_index_io_list, int64_t memory_type) {
  730. for (auto &node_index_io : node_index_io_list) {
  731. auto op_desc = node_index_io.node_->GetOpDesc();
  732. if (op_desc == nullptr) {
  733. GELOGW("Node[%s] op desc is null.", node_index_io.node_->GetName().c_str());
  734. return;
  735. }
  736. if (node_index_io.io_type_ == kIn) {
  737. auto input_desc = op_desc->MutableInputDesc(node_index_io.index_);
  738. (void) AttrUtils::SetInt(input_desc, ATTR_NAME_TENSOR_MEM_TYPE, memory_type);
  739. }
  740. if (node_index_io.io_type_ == kOut) {
  741. auto output_desc = op_desc->MutableOutputDesc(node_index_io.index_);
  742. (void) AttrUtils::SetInt(output_desc, ATTR_NAME_TENSOR_MEM_TYPE, memory_type);
  743. }
  744. }
  745. }
  746. bool BlockMemAssigner::IsContinuousOutput(const NodePtr &n) {
  747. if (n == nullptr) {
  748. GELOGE(FAILED, "Node is null.");
  749. return false;
  750. }
  751. // Get the continuous output type of the node, default is false
  752. bool is_output_continuous = false;
  753. auto node_desc = n->GetOpDesc();
  754. if (node_desc == nullptr) {
  755. GELOGE(FAILED, "Node[%s] nodedesc is null.", n->GetName().c_str());
  756. return false;
  757. }
  758. // If GetBool fail, is_output_continuous is false.
  759. (void)ge::AttrUtils::GetBool(node_desc, ATTR_NAME_CONTINUOUS_OUTPUT, is_output_continuous);
  760. if (is_output_continuous) {
  761. if (n->GetOwnerComputeGraph() != nullptr) {
  762. string graph_name = n->GetOwnerComputeGraph()->GetName();
  763. GELOGI("%s name[%s] set continuous, output size[%u].", graph_name.c_str(),
  764. n->GetName().c_str(), n->GetAllOutDataAnchorsSize());
  765. return true;
  766. }
  767. }
  768. return false;
  769. }
  770. bool BlockMemAssigner::IsZeroCopyBlock(const NodePtr &node, bool continuous) {
  771. if (NodeUtils::IsDynamicShape(node)) {
  772. return ((node->GetType() == DATA_TYPE) && !continuous) || (node->GetType() == NETOUTPUT);
  773. }
  774. if ((node->GetType() == DATA_TYPE) && !continuous) {
  775. return !node->GetOpDesc()->HasAttr(ATTR_NAME_PARENT_NODE_INDEX);
  776. }
  777. if (node->GetType() == NETOUTPUT) {
  778. const auto &owner = node->GetOwnerComputeGraph();
  779. return owner->GetParentGraph() == nullptr;
  780. }
  781. return false;
  782. }
  783. MemoryBlock *BlockMemAssigner::ApplyMemory(size_t block_size, size_t real_size, size_t no_align_size,
  784. OpMemoryType mem_type, const NodePtr &n, uint32_t out_index,
  785. const vector<bool> &workspace_reuse_flag, const bool is_op_reuse_mem,
  786. const bool continuous, int64_t memory_type) {
  787. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(n == nullptr, return nullptr, "Input parameter n is null.");
  788. auto node_op_desc = n->GetOpDesc();
  789. GE_IF_BOOL_EXEC(node_op_desc == nullptr, return nullptr);
  790. bool is_reuse_memory = false;
  791. string ge_disable_reuse_mem_env = "0";
  792. (void)ge::GetContext().GetOption(OPTION_EXEC_DISABLE_REUSED_MEMORY, ge_disable_reuse_mem_env);
  793. if (ge_disable_reuse_mem_env != "1") {
  794. bool reuse_mem_flag = (mem_type == kOutput) ? IsPreReuse(n, out_index) :
  795. !((workspace_reuse_flag.size() > out_index) && !workspace_reuse_flag[out_index]);
  796. is_reuse_memory = !node_op_desc->HasAttr(kL2FusionDynamicConvergeOp) &&
  797. !node_op_desc->HasAttr(kOpNoReuseMem) && reuse_mem_flag && is_op_reuse_mem;
  798. auto stream_id = node_op_desc->GetStreamId();
  799. if (is_reuse_memory && !continuous && !reusable_blocks_[memory_type].empty()) {
  800. for (auto it = reusable_blocks_[memory_type][stream_id].begin();
  801. it != reusable_blocks_[memory_type][stream_id].end(); ++it) {
  802. MemoryBlock *reusable_block = *it;
  803. if (!IsPostReuse(reusable_block)) {
  804. reusable_block->reuse_mem_ = false;
  805. GELOGI("Unreusable block.");
  806. continue;
  807. }
  808. std::string batch_label;
  809. if (reusable_block->IsSameLabel(batch_label)) {
  810. std::string op_label;
  811. (void)ge::AttrUtils::GetStr(node_op_desc, ATTR_NAME_BATCH_LABEL, op_label);
  812. if (batch_label != op_label) {
  813. GELOGI("label diff, op name %s", node_op_desc->GetName().c_str());
  814. continue;
  815. }
  816. }
  817. // A node can reuse blocks of the same stream and preorder streams
  818. if (CanReuseBySize(reusable_block_counts_, *reusable_block, block_size, real_size, continuous)) {
  819. reusable_block->AddNodeTypeIndex({n, mem_type, out_index, false}, real_size, no_align_size);
  820. if (mem_type == kOutput) {
  821. auto iter = anchor_to_symbol_.find(NodeIndexIO(n, out_index, kOut).ToString());
  822. if (iter != anchor_to_symbol_.end()) {
  823. reusable_block->AddSymbol(iter->second);
  824. }
  825. }
  826. reusable_block->continuous_block_ = continuous;
  827. reusable_block->ref_count_++;
  828. ReduceReusableBlockCount(*reusable_block, reusable_block_counts_);
  829. reusable_blocks_[memory_type][stream_id].erase(it);
  830. return reusable_block;
  831. }
  832. }
  833. }
  834. }
  835. auto block = new (std::nothrow) MemoryBlock(block_size, node_op_desc->GetStreamId(), is_reuse_memory, memory_type);
  836. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(block == nullptr, return nullptr, "new an object failed.");
  837. // Data and netoutput need zero copy block
  838. block->is_zero_copy_ = IsZeroCopyBlock(n, continuous);
  839. block->Init(real_size, mem_type, n, out_index, no_align_size);
  840. block->stream_id_ = node_op_desc->GetStreamId();
  841. block->ref_count_++;
  842. block->continuous_block_ = continuous;
  843. if (mem_type == kOutput) {
  844. auto iter = anchor_to_symbol_.find(NodeIndexIO(n, out_index, kOut).ToString());
  845. if (iter != anchor_to_symbol_.end()) {
  846. block->AddSymbol(iter->second);
  847. }
  848. }
  849. memory_blocks_.emplace_back(block);
  850. // cause memory_blocks_ may reduce when swap after,
  851. // create blocks_store_ to assure blocks deleted finally
  852. blocks_store_.emplace_back(block);
  853. return block;
  854. }
  855. MemoryBlock *BlockMemAssigner::ApplyContinuousMemory(const NodePtr &n, const vector<int64_t> &ranges,
  856. const bool is_op_reuse_mem) {
  857. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(n == nullptr, return nullptr, "input node is null.");
  858. auto node_op_desc = n->GetOpDesc();
  859. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(node_op_desc == nullptr, return nullptr, "node_op_desc is null.");
  860. MemoryBlock *block = nullptr;
  861. int64_t total_size = 0;
  862. int64_t memory_type = RT_MEMORY_HBM;
  863. for (uint32_t index = 0; index < static_cast<uint32_t>(node_op_desc->GetOutputsSize()); index++) {
  864. auto output_op_desc = node_op_desc->GetOutputDescPtr(index);
  865. if (output_op_desc == nullptr) {
  866. return nullptr;
  867. }
  868. int64_t size = 0;
  869. if (ge::TensorUtils::GetSize(*output_op_desc, size) != SUCCESS) {
  870. GELOGI("Get size failed");
  871. return nullptr;
  872. }
  873. size_t align_size = static_cast<size_t>(size);
  874. AlignMemOffset(align_size);
  875. total_size += align_size;
  876. // only apply total size in first block
  877. if (index != 0) {
  878. zero_memory_list_.emplace_back(n, kOutput, index);
  879. }
  880. if (index == 0) {
  881. NodeIndexIO node_index_io(n, index, kOut);
  882. auto iter = anchor_to_symbol_.find(node_index_io.ToString());
  883. if (iter != anchor_to_symbol_.end()) {
  884. string symbol = iter->second;
  885. if (symbol_to_mem_type_.find(symbol) != symbol_to_mem_type_.end()) {
  886. memory_type = symbol_to_mem_type_[symbol];
  887. GELOGD("Continuous out memory symbol is [%s], memory type is [%ld]", symbol.c_str(), memory_type);
  888. }
  889. }
  890. }
  891. }
  892. auto block_size = GetBlockSize(total_size, ranges);
  893. GELOGI("Node[%s] continuous out memory size[%ld] block size[%zu]", node_op_desc->GetName().c_str(),
  894. total_size, block_size);
  895. vector<bool> workspace_reuse_flag;
  896. block = ApplyMemory(block_size, total_size, total_size, kOutput, n, 0, workspace_reuse_flag, is_op_reuse_mem, true,
  897. memory_type);
  898. if (block != nullptr) {
  899. // hccl task need align header and tail
  900. block->first_continuous_block_ = true;
  901. block->last_continuous_block_ = true;
  902. }
  903. return block;
  904. }
  905. MemoryBlock *BlockMemAssigner::ApplyOutMemory(const NodePtr &n, uint32_t index, const vector<int64_t> &ranges,
  906. const bool is_op_reuse_mem, const bool continuous) {
  907. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(n == nullptr, return nullptr, "input node is null.");
  908. auto node_op_desc = n->GetOpDesc();
  909. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(node_op_desc == nullptr, return nullptr, "node_op_desc is null.");
  910. MemoryBlock *block = nullptr;
  911. NodeIndexIO node_index_io(n, index, kOut);
  912. int64_t size = 0;
  913. auto output_op_desc = node_op_desc->GetOutputDescPtr(index);
  914. if (output_op_desc != nullptr) {
  915. GE_IF_BOOL_EXEC(ge::TensorUtils::GetSize(*output_op_desc, size) != SUCCESS, GELOGI("Get size failed"));
  916. }
  917. size_t no_align_size = 0;
  918. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(GetNoAlignSize(*node_op_desc, index, no_align_size) != SUCCESS,
  919. return nullptr, "Get no align size failed");
  920. std::string symbol;
  921. if (IsSymbolExist(node_index_io, symbol)) {
  922. block = symbol_blocks_[symbol];
  923. block->AddNodeTypeIndex({n, kOutput, index, true}, size, no_align_size);
  924. block->ref_count_++;
  925. } else {
  926. int64_t max_size = size;
  927. int64_t memory_type = RT_MEMORY_HBM;
  928. auto iter1 = anchor_to_symbol_.find(node_index_io.ToString());
  929. if (iter1 != anchor_to_symbol_.end()) {
  930. auto iter2 = symbol_size_.find(iter1->second);
  931. if (iter2 != symbol_size_.end()) {
  932. max_size = iter2->second;
  933. }
  934. auto iter3 = symbol_to_mem_type_.find(iter1->second);
  935. if (iter3 != symbol_to_mem_type_.end()) {
  936. memory_type = iter3->second;
  937. }
  938. }
  939. auto block_size = GetBlockSize(max_size, ranges);
  940. vector<bool> workspace_reuse_flag;
  941. block = ApplyMemory(block_size, size, no_align_size, kOutput, n, index,
  942. workspace_reuse_flag, is_op_reuse_mem, continuous, memory_type);
  943. }
  944. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(block == nullptr, return nullptr, "Block is nullptr.");
  945. int out_count_reuse_input = block->ref_count_;
  946. int out_count = 0;
  947. GE_IF_BOOL_EXEC(index >= n->GetAllOutDataAnchors().size(), GELOGE(FAILED, "index is out of range."); return nullptr);
  948. auto out_data_anchor = n->GetOutDataAnchor(index);
  949. GE_IF_BOOL_EXEC(out_data_anchor == nullptr, GELOGE(FAILED, "Out data anchor is nullptr."); return nullptr);
  950. for (const auto &in_anchor : out_data_anchor->GetPeerInDataAnchors()) {
  951. auto owner_node = in_anchor->GetOwnerNode();
  952. auto op_desc = owner_node->GetOpDesc();
  953. GE_IF_BOOL_EXEC(op_desc == nullptr, continue);
  954. Params *instance = Params::Instance();
  955. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(instance == nullptr, return nullptr, "Params instance is nullptr.");
  956. if (!((instance->GetTarget() == TARGET_TYPE_TINY) && (op_desc->GetType() == NETOUTPUT))) {
  957. out_count++;
  958. }
  959. }
  960. bool reuse_input = false;
  961. for (const auto &in_anchor : out_data_anchor->GetPeerInDataAnchors()) {
  962. auto owner_node = in_anchor->GetOwnerNode();
  963. GE_IF_BOOL_EXEC(owner_node == nullptr, continue);
  964. auto op_desc = owner_node->GetOpDesc();
  965. GE_IF_BOOL_EXEC(op_desc == nullptr, continue);
  966. for (uint32_t i = 0; i < static_cast<uint32_t>(op_desc->GetOutputsSize()); i++) {
  967. bool dst_reuse_input = false;
  968. uint32_t dst_reuse_input_index = 0;
  969. auto owner_node_op_desc = op_desc->GetOutputDescPtr(i);
  970. GE_IF_BOOL_EXEC(owner_node_op_desc == nullptr, continue);
  971. GE_IF_BOOL_EXEC(ge::TensorUtils::GetReuseInput(*owner_node_op_desc, dst_reuse_input) != SUCCESS,
  972. GELOGI("Get dst_reuse_input failed"));
  973. GE_IF_BOOL_EXEC(ge::TensorUtils::GetReuseInputIndex(*owner_node_op_desc, dst_reuse_input_index) != SUCCESS,
  974. GELOGI("Get dst_reuse_input_index failed"));
  975. if (dst_reuse_input && (dst_reuse_input_index == static_cast<uint32_t>(in_anchor->GetIdx()))) {
  976. block->AddNodeTypeIndex({owner_node, kOutput, i, true}, block->Size(), block->Size());
  977. out_count_reuse_input += 1;
  978. reuse_input = true;
  979. }
  980. }
  981. }
  982. block->ref_count_ = reuse_input ? out_count_reuse_input + out_count - 1 : out_count;
  983. return block;
  984. }
  985. bool IsOutputBlock(const ge::InDataAnchorPtr &in_data_anchor) {
  986. auto peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  987. GE_IF_BOOL_EXEC(peer_out_anchor == nullptr, GELOGE(FAILED, "Peer out anchor is nullptr."); return false);
  988. auto src = peer_out_anchor->GetOwnerNode();
  989. int32_t index = peer_out_anchor->GetIdx();
  990. auto iter = GetLocalOmgContext().out_nodes_map.find(src->GetName());
  991. if (iter != GetLocalOmgContext().out_nodes_map.end()) {
  992. for (auto id : iter->second) {
  993. if (index == id) {
  994. return true;
  995. }
  996. }
  997. }
  998. return false;
  999. }
  1000. // atomic out memory will be reassigned
  1001. bool IsAtomicOutputMemory(const ge::NodePtr &node, uint32_t output_index, bool is_atomic,
  1002. bool out_node_set_continuous_input) {
  1003. auto op_desc = node->GetOpDesc();
  1004. if (op_desc == nullptr) {
  1005. return false;
  1006. }
  1007. vector<int64_t> atomic_output_index;
  1008. // If GetListInt fail, atomic_output_index is empty.
  1009. (void)ge::AttrUtils::GetListInt(op_desc, ATOMIC_ATTR_OUTPUT_INDEX, atomic_output_index);
  1010. if (!out_node_set_continuous_input && is_atomic) {
  1011. for (auto &index : atomic_output_index) {
  1012. if (static_cast<uint32_t>(index) == output_index) {
  1013. if (node->GetOwnerComputeGraph() != nullptr) {
  1014. string graph_name = node->GetOwnerComputeGraph()->GetName();
  1015. GELOGD("[IMAS]Atomic no assign %s name[%s] output[%ld] streamid[%ld].", graph_name.c_str(),
  1016. op_desc->GetName().c_str(), index, op_desc->GetStreamId());
  1017. }
  1018. return true;
  1019. }
  1020. }
  1021. }
  1022. return false;
  1023. }
  1024. bool IsKnownSubgraphData(const NodePtr &node) {
  1025. if (NodeUtils::IsDynamicShape(node)) {
  1026. return false;
  1027. }
  1028. return node->GetOpDesc()->HasAttr(ATTR_NAME_PARENT_NODE_INDEX);
  1029. }
  1030. void BlockMemAssigner::ReleaseMemory(MemoryBlock *to_release, vector<MemoryBlock *> &reusable_memory) {
  1031. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(to_release == nullptr, return, "Input parameter to_release is null.");
  1032. GE_CHK_TRUE_EXEC_INFO(to_release->ref_count_ <= 0, return, "Release memory");
  1033. GE_CHK_TRUE_EXEC_INFO(!to_release->reuse_mem_, return, "doesn't reuse memory");
  1034. --to_release->ref_count_;
  1035. if (to_release->ref_count_ == 0) {
  1036. to_release->SetLifeTimeEnd(life_time_);
  1037. reusable_memory.emplace_back(to_release);
  1038. AddReusableBlockCount(*to_release, reusable_block_counts_);
  1039. }
  1040. }
  1041. void BlockMemAssigner::ReleaseMemorys(const vector<MemoryBlock *> &to_releases,
  1042. vector<MemoryBlock *> &reusable_memory) {
  1043. for (auto mem_block : to_releases) {
  1044. ReleaseMemory(mem_block, reusable_memory);
  1045. }
  1046. }
  1047. void BlockMemAssigner::ReleaseInputNodeOutMemory(const unordered_map<string, vector<MemoryBlock *>> &node_out_blocks,
  1048. vector<MemoryBlock *> &reusable_memory, NodePtr &node) {
  1049. for (const auto &in_anchor : node->GetAllInDataAnchors()) {
  1050. if ((in_anchor->GetPeerOutAnchor() == nullptr) ||
  1051. (in_anchor->GetPeerOutAnchor()->GetOwnerNode()->GetOpDesc() == nullptr) || (node->GetOpDesc() == nullptr)) {
  1052. return;
  1053. }
  1054. GE_IF_BOOL_EXEC(IsOutputBlock(in_anchor), continue);
  1055. auto node_name = in_anchor->GetPeerOutAnchor()->GetOwnerNode()->GetName();
  1056. GE_IF_BOOL_EXEC((in_anchor->GetPeerOutAnchor()->GetOwnerNode()->GetType() == CONSTANT) ||
  1057. (in_anchor->GetPeerOutAnchor()->GetOwnerNode()->GetType() == FASTRCNNPREDICTIONS) ||
  1058. (in_anchor->GetPeerOutAnchor()->GetOwnerNode()->GetType() == CONSTANTOP),
  1059. continue);
  1060. auto it = node_out_blocks.find(node_name);
  1061. if (it == node_out_blocks.end()) {
  1062. continue;
  1063. }
  1064. for (auto block : it->second) {
  1065. const vector<NodeTypeIndex> &node_type_indexs = block->NodeTypeIndexList();
  1066. if (node_type_indexs.empty()) {
  1067. continue;
  1068. }
  1069. GELOGD("node_type_indexs: %d, %s", node_type_indexs.back().index,
  1070. node_type_indexs.back().node->GetName().c_str());
  1071. if ((node_type_indexs.back().node == in_anchor->GetPeerOutAnchor()->GetOwnerNode()) &&
  1072. (node_type_indexs.back().index == static_cast<uint32_t>(in_anchor->GetPeerOutAnchor()->GetIdx())) &&
  1073. (node->GetOpDesc()->GetStreamId() == block->stream_id_)) {
  1074. ReleaseMemory(block, reusable_memory);
  1075. if (block->ref_count_ == 0) {
  1076. SetLastUsedInputMemAttr(node, in_anchor->GetIdx());
  1077. }
  1078. }
  1079. }
  1080. }
  1081. }
  1082. void SplitStringByComma(const string &str, vector<string> &sub_str_vec) {
  1083. std::string tmp_string = str + ",";
  1084. std::string::size_type start_pos = 0;
  1085. std::string::size_type cur_pos = tmp_string.find(',', 0);
  1086. while (cur_pos != std::string::npos) {
  1087. std::string sub_str = tmp_string.substr(start_pos, cur_pos - start_pos);
  1088. if (!sub_str.empty()) {
  1089. vector<string>::iterator ret = std::find(sub_str_vec.begin(), sub_str_vec.end(), sub_str);
  1090. if (ret == sub_str_vec.end()) {
  1091. sub_str_vec.push_back(sub_str);
  1092. }
  1093. }
  1094. start_pos = cur_pos + 1;
  1095. cur_pos = tmp_string.find(',', start_pos);
  1096. }
  1097. }
  1098. void CheckAndGetOpReuseEnv(const string &env, vector<string> &env_vec, bool &op_reuse_env_valid) {
  1099. string env_str;
  1100. env_str = string(env);
  1101. if (env_str.size() > kReuseMaxCharNum) {
  1102. GELOGE(FAILED, "The OP_NO_REUSE_MEM has more than %d characters.", kReuseMaxCharNum);
  1103. return;
  1104. }
  1105. SplitStringByComma(env_str, env_vec);
  1106. if (env_vec.size() > kReuseMaxOpNum) {
  1107. GELOGE(FAILED, "The OP_NO_REUSE_MEM has more than %d nodes.", kReuseMaxOpNum);
  1108. return;
  1109. }
  1110. op_reuse_env_valid = true;
  1111. return;
  1112. }
  1113. Status BlockMemAssigner::AssignOutputMemoryWithReuse(const NodePtr &node, vector<int64_t> &ranges) {
  1114. auto op_desc = node->GetOpDesc();
  1115. int64_t stream_id = op_desc->GetStreamId();
  1116. vector<int64_t> memorys_type;
  1117. bool has_mem_type_attr = ge::AttrUtils::GetListInt(op_desc, ATTR_NAME_OUTPUT_MEM_TYPE_LIST, memorys_type);
  1118. GELOGD("Assign memory node[%s], output size[%zu], output memory type size[%zu]", op_desc->GetName().c_str(),
  1119. op_desc->GetOutputsSize(), memorys_type.size());
  1120. if (has_mem_type_attr && (memorys_type.size() != op_desc->GetOutputsSize())) {
  1121. GELOGE(INTERNAL_ERROR, "fusion: node[%s], output memory size err[outputsize:%zu, memorysize:%zu]",
  1122. op_desc->GetName().c_str(), op_desc->GetOutputsSize(), memorys_type.size());
  1123. return INTERNAL_ERROR;
  1124. }
  1125. is_op_reuse_mem_ = true;
  1126. if (op_reuse_env_valid_ == true) {
  1127. vector<string>::iterator it_name =
  1128. std::find(op_no_reuse_mem_vec_.begin(), op_no_reuse_mem_vec_.end(), op_desc->GetName());
  1129. vector<string>::iterator it_type =
  1130. std::find(op_no_reuse_mem_vec_.begin(), op_no_reuse_mem_vec_.end(), op_desc->GetType());
  1131. GE_IF_BOOL_EXEC(it_name != op_no_reuse_mem_vec_.end() || it_type != op_no_reuse_mem_vec_.end(),
  1132. is_op_reuse_mem_ = false;);
  1133. }
  1134. bool is_atomic = false;
  1135. // If GetBool fail, is_atomic is false.
  1136. (void)ge::AttrUtils::GetBool(op_desc, ATOMIC_ATTR_IS_ATOMIC_NODE, is_atomic);
  1137. // Allocate memory for the current node and release node memory of the same size in the workspace
  1138. GE_IF_BOOL_EXEC(ge_disable_reuse_mem_env_ != "1",
  1139. for (auto iter = stream_workspace_blocks_.begin(); iter != stream_workspace_blocks_.end();
  1140. ++iter) { ReleaseMemorys(iter->second[stream_id], reusable_blocks_[iter->first][stream_id]); });
  1141. if (IsContinuousOutput(node)) {
  1142. (void)ApplyContinuousMemory(node, ranges, is_op_reuse_mem_);
  1143. return SUCCESS;
  1144. }
  1145. for (uint32_t i = 0; i < static_cast<uint32_t>(op_desc->GetOutputsSize()); i++) {
  1146. int64_t size = 0;
  1147. auto output_op_desc = op_desc->GetOutputDescPtr(i);
  1148. if (output_op_desc != nullptr) {
  1149. GE_IF_BOOL_EXEC(ge::TensorUtils::GetSize(*output_op_desc, size) != SUCCESS, GELOGI("Get size failed"));
  1150. }
  1151. // fusion: other type's size not means malloc HBM memory
  1152. bool l1_flag = has_mem_type_attr && memorys_type[i] == RT_MEMORY_L1;
  1153. if (l1_flag) {
  1154. GELOGI("fusion: node[%s], output[%s], output memory type [%ld]",
  1155. op_desc->GetName().c_str(), op_desc->GetOutputNameByIndex(i).c_str(), memorys_type[i]);
  1156. size = 0;
  1157. }
  1158. std::string peer_name;
  1159. uint32_t peer_input_index = 0;
  1160. bool out_node_set_continuous_input = false;
  1161. bool reset_zero_copy_flag = false;
  1162. bool no_need_assign_memory = ((size == 0) || CheckIsZeroMemNodeType(node->GetType()));
  1163. if (!no_need_assign_memory) {
  1164. out_node_set_continuous_input =
  1165. IsOutNodeSetContinuousInput(node, i, peer_name, peer_input_index, no_need_assign_memory, reset_zero_copy_flag);
  1166. GE_IF_BOOL_EXEC(!no_need_assign_memory,
  1167. no_need_assign_memory = IsAtomicOutputMemory(node, i, is_atomic, out_node_set_continuous_input););
  1168. }
  1169. no_need_assign_memory = (no_need_assign_memory || IsKnownSubgraphData(node));
  1170. if (no_need_assign_memory) {
  1171. zero_memory_list_.emplace_back(node, kOutput, i, false);
  1172. continue;
  1173. }
  1174. // atomic can't be reused
  1175. bool need_change = is_op_reuse_mem_ && out_node_set_continuous_input && is_atomic;
  1176. if (need_change) {
  1177. is_op_reuse_mem_ = false;
  1178. }
  1179. MemoryBlock *mem_block = ApplyOutMemory(node, i, ranges, is_op_reuse_mem_, out_node_set_continuous_input);
  1180. if (mem_block != nullptr) {
  1181. GE_IF_BOOL_EXEC(reset_zero_copy_flag,
  1182. mem_block->is_zero_copy_ = false;
  1183. GELOGI("Node[%s] output[%u] need assign memory before reassign.", op_desc->GetName().c_str(), i););
  1184. node_out_blocks_[node->GetName()].emplace_back(mem_block);
  1185. if (out_node_set_continuous_input) {
  1186. node_continuous_input_blocks_[peer_name][peer_input_index] = mem_block;
  1187. }
  1188. NodeIndexIO node_index_io(node, i, kOut);
  1189. auto iter = anchor_to_symbol_.find(node_index_io.ToString());
  1190. if (iter == anchor_to_symbol_.end()) {
  1191. continue;
  1192. }
  1193. symbol_blocks_[iter->second] = mem_block;
  1194. }
  1195. }
  1196. return SUCCESS;
  1197. }
  1198. ///
  1199. /// @ingroup domi
  1200. /// @brief traverse all nodes outputs and workspace in need, apply memory block considering memory reuse
  1201. /// @param [in/out] ranges memory size provided
  1202. /// @return Status result
  1203. ///
  1204. void BlockMemAssigner::AssignMemoryWithReuse(vector<int64_t> &ranges) {
  1205. (void)ge::GetContext().GetOption(OPTION_EXEC_DISABLE_REUSED_MEMORY, ge_disable_reuse_mem_env_);
  1206. GELOGD("Reuse memory %s", ge_disable_reuse_mem_env_ == "1" ? "close" : "open");
  1207. string op_no_reuse_mem_str;
  1208. const char *op_no_reuse_mem = std::getenv(OP_NO_REUSE_MEM);
  1209. GE_IF_BOOL_EXEC(op_no_reuse_mem != nullptr, op_no_reuse_mem_str = string(op_no_reuse_mem);
  1210. CheckAndGetOpReuseEnv(op_no_reuse_mem_str, op_no_reuse_mem_vec_, op_reuse_env_valid_););
  1211. for (NodePtr &n : compute_graph_->GetAllNodes()) {
  1212. auto node_op_desc = n->GetOpDesc();
  1213. GE_IF_BOOL_EXEC(node_op_desc == nullptr, continue);
  1214. life_time_ = node_op_desc->GetId();
  1215. int64_t stream_id = node_op_desc->GetStreamId();
  1216. if (AssignOutputMemoryWithReuse(n, ranges) != SUCCESS) {
  1217. return;
  1218. }
  1219. for (auto iter = stream_workspace_blocks_.begin(); iter != stream_workspace_blocks_.end(); ++iter) {
  1220. iter->second[stream_id].clear();
  1221. }
  1222. vector<int64_t> temp;
  1223. GetNodeWorkSpaceSize(n, temp);
  1224. vector<int64_t> workspace_bytes;
  1225. vector<int64_t> tvm_workspace_memory_type;
  1226. bool has_tvm_workspace_mem_type_attr =
  1227. ge::AttrUtils::GetListInt(node_op_desc, TVM_ATTR_NAME_WORKSPACE_TYPE, tvm_workspace_memory_type);
  1228. vector<bool> workspace_reuse_flag;
  1229. GE_IF_BOOL_EXEC(!ge::AttrUtils::GetListBool(node_op_desc, kAttrNameWorkspaceReuseFlag, workspace_reuse_flag),
  1230. GELOGD("OP %s get workspace_reuse_flag attr failed", node_op_desc->GetName().c_str()));
  1231. GELOGD("Assign memory node[%s], size [temp:%zu, memory type size:%zu]", node_op_desc->GetName().c_str(),
  1232. temp.size(), tvm_workspace_memory_type.size());
  1233. if (has_tvm_workspace_mem_type_attr && (temp.size() != tvm_workspace_memory_type.size())) {
  1234. GELOGE(INTERNAL_ERROR, "fusion: node[%s], tvm workspace memory size error![v_temp:%zu, workspace:%zu]",
  1235. n->GetName().c_str(), temp.size(), tvm_workspace_memory_type.size());
  1236. return;
  1237. }
  1238. for (size_t i = 0; i < temp.size(); i++) {
  1239. // fusion: other type's size not means malloc HBM memory
  1240. bool workspace_skip_flag = false;
  1241. if (has_tvm_workspace_mem_type_attr && tvm_workspace_memory_type[i] == RT_MEMORY_L1) {
  1242. GELOGI(
  1243. "fusion: node[%s]workspace index[%zu] is not hbm type, add to zero_memory_list, workspace memory type [%ld]",
  1244. node_op_desc->GetName().c_str(), i, tvm_workspace_memory_type[i]);
  1245. workspace_skip_flag = true;
  1246. }
  1247. if (temp[i] == 0 || workspace_skip_flag) {
  1248. zero_memory_list_.emplace_back(n, kWorkspace, static_cast<uint32_t>(i), false);
  1249. continue;
  1250. }
  1251. int64_t memory_type = RT_MEMORY_HBM;
  1252. if (!GetWorkSpaceMemoryType(n, i, memory_type)) {
  1253. GELOGW("Get workspace memory type failed.");
  1254. return;
  1255. }
  1256. MemoryBlock *mem_block = ApplyMemory(GetBlockSize(static_cast<size_t>(temp[i]), ranges),
  1257. static_cast<size_t>(temp[i]), static_cast<size_t>(temp[i]),
  1258. kWorkspace, n, static_cast<uint32_t>(i), workspace_reuse_flag,
  1259. is_op_reuse_mem_, false, memory_type);
  1260. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(mem_block == nullptr, continue, "failed to apply memory block.");
  1261. CheckWorkspaceReuse(workspace_reuse_flag, i, stream_id, mem_block, memory_type);
  1262. }
  1263. for (auto it = reusable_blocks_.begin(); it != reusable_blocks_.end(); ++it) {
  1264. ReleaseInputNodeOutMemory(node_out_blocks_, it->second[stream_id], n);
  1265. }
  1266. }
  1267. GELOGD("Assigned memory blocks:");
  1268. for (auto mem_block : memory_blocks_) {
  1269. GELOGD("%s", mem_block->String().c_str());
  1270. (void)mem_block; // Fix warning
  1271. }
  1272. bool merge_dynamic_batch = false;
  1273. GE_IF_BOOL_EXEC(!(ge_disable_reuse_mem_env_ == "1"), merge_dynamic_batch = MergeDynamicBatchBlocks());
  1274. GE_IF_BOOL_EXEC((!(ge_disable_reuse_mem_env_ == "1") && !merge_dynamic_batch), ReuseBlocksByLifeTime(ranges.size()));
  1275. AssignContinuousBlocks();
  1276. ResizeMemoryBlocks();
  1277. GELOGD("Memory blocks after resize:");
  1278. for (auto mem_block : memory_blocks_) {
  1279. GELOGD("%s", mem_block->String().c_str());
  1280. (void)mem_block; // Fix warning
  1281. }
  1282. }
  1283. void BlockMemAssigner::CheckWorkspaceReuse(const vector<bool> &workspace_reuse_flag, uint32_t index, int64_t stream_id,
  1284. MemoryBlock *mem_block, int64_t memory_type) {
  1285. bool reuse_mem_flag =
  1286. ((workspace_reuse_flag.size() > index) && (workspace_reuse_flag[index] == false)) ? false : true;
  1287. if (reuse_mem_flag) {
  1288. stream_workspace_blocks_[memory_type][stream_id].emplace_back(mem_block);
  1289. }
  1290. }
  1291. void BlockMemAssigner::GetNodeWorkSpaceSize(const NodePtr &node, vector<int64_t> &workspace_memory) {
  1292. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(node->GetOpDesc() == nullptr, return, "Op desc is null.");
  1293. vector<int64_t> workspace_byte_nums = node->GetOpDesc()->GetWorkspaceBytes();
  1294. GELOGD("node[%s] size:%zu", node->GetOpDesc()->GetName().c_str(), workspace_byte_nums.size());
  1295. for (int64_t byte_size : workspace_byte_nums) {
  1296. workspace_memory.emplace_back(byte_size);
  1297. GELOGD("push back size:%ld", byte_size);
  1298. }
  1299. }
  1300. // descending order
  1301. static bool CompareBlockMaxSize(MemoryBlock *left, MemoryBlock *right) {
  1302. if (left == nullptr || right == nullptr) {
  1303. return false;
  1304. }
  1305. auto left_max_size = std::max_element(left->RealSizeList().begin(), left->RealSizeList().end());
  1306. if (left_max_size != left->RealSizeList().end()) {
  1307. auto right_max_size = std::max_element(right->RealSizeList().begin(), right->RealSizeList().end());
  1308. if (right_max_size == right->RealSizeList().end() || (*left_max_size > *right_max_size)) {
  1309. return true;
  1310. }
  1311. }
  1312. return false;
  1313. }
  1314. void MergeBlocks(std::vector<MemoryBlock *> &dest, std::vector<MemoryBlock *> &src) {
  1315. for (size_t i = 0; i < dest.size(); ++i) {
  1316. if (i >= src.size()) {
  1317. return;
  1318. }
  1319. if (dest[i] != nullptr && src[i] != nullptr) {
  1320. if (!dest[i]->reuse_mem_ || !src[i]->reuse_mem_) {
  1321. GELOGD("Diff batch's workspace can't be reused, i: %zu, dest[i]: %s, stream: %ld, src[i]: %s, stream: %ld.",
  1322. i, dest[i]->String().c_str(), dest[i]->stream_id_, src[i]->String().c_str(), src[i]->stream_id_);
  1323. continue;
  1324. }
  1325. for (auto &symbol : src[i]->SymbolList()) {
  1326. dest[i]->AddSymbol(symbol);
  1327. }
  1328. for (size_t j = 0; j < src[i]->NodeTypeIndexList().size(); ++j) {
  1329. dest[i]->AddNodeTypeIndex(src[i]->NodeTypeIndexList()[j],
  1330. src[i]->RealSizeList()[j],
  1331. src[i]->NoAlignSizeList()[j]);
  1332. src[i]->deleted_block_ = true;
  1333. }
  1334. }
  1335. }
  1336. }
  1337. bool BlockMemAssigner::MergeDynamicBatchBlocks() {
  1338. bool merged = false;
  1339. std::map<std::string, std::vector<MemoryBlock *>> dynamic_batch_blocks;
  1340. for (auto block : memory_blocks_) {
  1341. if (block == nullptr) {
  1342. continue;
  1343. }
  1344. std::string batch_label;
  1345. if (block->IsSameLabel(batch_label)) {
  1346. dynamic_batch_blocks[batch_label].emplace_back(block);
  1347. }
  1348. }
  1349. auto it = dynamic_batch_blocks.begin();
  1350. auto it_max = it;
  1351. // find max block counts
  1352. for (; it != dynamic_batch_blocks.end(); ++it) {
  1353. if (it->second.size() > it_max->second.size()) {
  1354. it_max = it;
  1355. }
  1356. std::sort(it->second.begin(), it->second.end(), CompareBlockMaxSize);
  1357. }
  1358. if (it_max != dynamic_batch_blocks.end()) {
  1359. GELOGD("MergeDynamicBatch %s block counts %zu", it_max->first.c_str(), it_max->second.size());
  1360. }
  1361. for (it = dynamic_batch_blocks.begin(); it != dynamic_batch_blocks.end(); ++it) {
  1362. if (it != it_max) {
  1363. GELOGD("MergeDynamicBatch from %s to %s", it->first.c_str(), it_max->first.c_str());
  1364. MergeBlocks(it_max->second, it->second);
  1365. merged = true;
  1366. }
  1367. }
  1368. return merged;
  1369. }
  1370. // asending order
  1371. static bool CompareBlockIndex(MemoryBlock *left, MemoryBlock *right) {
  1372. if (left == nullptr || right == nullptr) {
  1373. return false;
  1374. }
  1375. if (left->input_index_ < right->input_index_) {
  1376. return true;
  1377. }
  1378. return false;
  1379. }
  1380. ///
  1381. /// @ingroup domi
  1382. /// @brief order blocks by continuous input index
  1383. /// @param [in] blocks need be processed
  1384. /// @param [in] input blocks need continuous
  1385. /// @param [out] blocks after continuous order
  1386. /// @param [in/out] blocks ordered
  1387. /// @param [in] input or output
  1388. ///
  1389. void ReAssignContinuousBlocks(const std::vector<MemoryBlock *> &org_blocks,
  1390. const std::map<MemoryBlock *, uint32_t> block_map,
  1391. std::vector<MemoryBlock *> &dest_blocks, std::vector<MemoryBlock *> &continuous_blocks,
  1392. const std::string &type) {
  1393. for (auto &memory_block : org_blocks) {
  1394. if (memory_block == nullptr || memory_block->deleted_block_) {
  1395. continue;
  1396. }
  1397. if (block_map.find(memory_block) != block_map.end()) {
  1398. continue;
  1399. }
  1400. dest_blocks.emplace_back(memory_block);
  1401. }
  1402. // add continuous block
  1403. std::sort(continuous_blocks.begin(), continuous_blocks.end(), CompareBlockIndex);
  1404. size_t count = 0;
  1405. for (auto &memory_block : continuous_blocks) {
  1406. GE_IF_BOOL_EXEC(memory_block == nullptr, continue);
  1407. GELOGI("Block continuous %s index:%d", type.c_str(), memory_block->input_index_);
  1408. count++;
  1409. if (count == 1) {
  1410. memory_block->first_continuous_block_ = true;
  1411. }
  1412. if (count == continuous_blocks.size()) {
  1413. memory_block->last_continuous_block_ = true;
  1414. }
  1415. dest_blocks.emplace_back(memory_block);
  1416. }
  1417. }
  1418. void BlockMemAssigner::AssignContinuousBlocks() {
  1419. for (auto &block_map : node_continuous_input_blocks_) {
  1420. std::vector<MemoryBlock *> dest_memory_blocks;
  1421. std::map<MemoryBlock *, uint32_t> continuous_block_map;
  1422. std::vector<MemoryBlock *> continuous_blocks;
  1423. auto it = node_continuous_input_counts_.find(block_map.first);
  1424. GE_IF_BOOL_EXEC(it == node_continuous_input_counts_.end(), continue);
  1425. GELOGI("Node:%s continuous input block count:%zu input count:%u", block_map.first.c_str(), block_map.second.size(),
  1426. it->second);
  1427. GE_IF_BOOL_EXEC(it->second != block_map.second.size(), continue);
  1428. for (auto &it : block_map.second) {
  1429. if (it.second != nullptr) {
  1430. continuous_block_map[it.second] = it.first;
  1431. it.second->input_index_ = it.first;
  1432. continuous_blocks.emplace_back(it.second);
  1433. }
  1434. }
  1435. if (continuous_block_map.size() != continuous_blocks.size()) {
  1436. GELOGW("Node:%s continuous input map size:%zu vector size:%zu", block_map.first.c_str(),
  1437. continuous_block_map.size(), continuous_blocks.size());
  1438. continue;
  1439. }
  1440. ReAssignContinuousBlocks(memory_blocks_, continuous_block_map, dest_memory_blocks, continuous_blocks, "input");
  1441. memory_blocks_.swap(dest_memory_blocks);
  1442. }
  1443. }
  1444. void BlockMemAssigner::ReuseBlocksByLifeTime(size_t range_size) {
  1445. // 1 means block size is same so no need to do this
  1446. if (range_size <= 1) {
  1447. return;
  1448. }
  1449. for (size_t i = 0; i < memory_blocks_.size(); ++i) {
  1450. auto parent = memory_blocks_[i];
  1451. if (parent == nullptr || parent->deleted_block_ || parent->continuous_block_) {
  1452. continue;
  1453. }
  1454. if (parent->reuse_mem_ && !IsPostReuse(parent)) {
  1455. parent->reuse_mem_ = false;
  1456. }
  1457. for (size_t j = i + 1; j < memory_blocks_.size(); ++j) {
  1458. auto child = memory_blocks_[j];
  1459. if (child == nullptr) {
  1460. continue;
  1461. }
  1462. // If node is before atomic_addr_clean node, the continus memory can't be reused.
  1463. if (!parent->NodeTypeIndexList().empty() && child->continuous_block_) {
  1464. auto node = parent->NodeTypeIndexList()[0].node;
  1465. if (node == nullptr || node->GetOpDesc() == nullptr || (node->GetOpDesc()->GetId() < GetAtomicAddrCleanId())) {
  1466. continue;
  1467. }
  1468. }
  1469. parent->AddLifeReuseBlock(child, total_node_depend_stream_life_);
  1470. }
  1471. }
  1472. }
  1473. ///
  1474. /// @ingroup domi_omg
  1475. /// @brief traverse memory size, resize, calculate offset
  1476. /// @param [in&out] memory_blocks_ memory block, after calculating offset
  1477. ///
  1478. void BlockMemAssigner::ResizeMemoryBlocks() {
  1479. for (auto &memory_block : memory_blocks_) {
  1480. if (memory_block == nullptr || memory_block->deleted_block_ || memory_block->is_zero_copy_) {
  1481. continue;
  1482. }
  1483. if (memory_block->memory_type_ == RT_MEMORY_HBM) {
  1484. if (memory_block->first_continuous_block_) {
  1485. mem_offset_ += MEM_ALIGN_SIZE;
  1486. }
  1487. memory_block->Resize();
  1488. memory_block->SetHeadOffset(mem_offset_);
  1489. mem_offset_ += memory_block->Size();
  1490. memory_block->SetTailOffset(mem_offset_ - 1);
  1491. } else if (memory_block->memory_type_ == RT_MEMORY_P2P_DDR) {
  1492. if (memory_block->first_continuous_block_) {
  1493. p2p_mem_offset_ += MEM_ALIGN_SIZE;
  1494. }
  1495. memory_block->Resize();
  1496. memory_block->SetHeadOffset(p2p_mem_offset_);
  1497. p2p_mem_offset_ += memory_block->Size();
  1498. memory_block->SetTailOffset(p2p_mem_offset_ - 1);
  1499. }
  1500. }
  1501. GELOGD("mem_offset_ exclude zero_copy_memory is %zu, p2p_mem_offset_ exclude zero_copy_memory is %zu.",
  1502. mem_offset_, p2p_mem_offset_);
  1503. }
  1504. ///
  1505. /// @ingroup domi
  1506. /// @brief given NodeTypeIndex, set offset in Op's OpDef
  1507. /// @param [in&out] node_type_index <node, memory type, id>
  1508. /// @param [in] offset offset to be set
  1509. /// @param [in] size memory size
  1510. /// @param [in] real_size memory size in need
  1511. /// @return Status result
  1512. ///
  1513. void SetOffsetSize(const NodeTypeIndex &node_type, const MemoryBlock *block,
  1514. size_t real_size, size_t no_align_size, bool child_block) {
  1515. ge::OpDescPtr op_desc = node_type.node->GetOpDesc();
  1516. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(op_desc == nullptr, return, "op_desc is null.");
  1517. string graph_name = node_type.node->GetOwnerComputeGraph()->GetName();
  1518. vector<int64_t> memorys_type;
  1519. int64_t offset = block->HeadOffset();
  1520. size_t end = node_type.life_time_end;
  1521. bool has_mem_type_attr = ge::AttrUtils::GetListInt(op_desc, ATTR_NAME_OUTPUT_MEM_TYPE_LIST, memorys_type);
  1522. if (node_type.mem_type == kOutput) {
  1523. vector<int64_t> output_list = op_desc->GetOutputOffset();
  1524. for (auto i = static_cast<uint32_t>(output_list.size()); i < node_type.index + 1; i++) {
  1525. output_list.emplace_back(kInvalidOffset);
  1526. }
  1527. if (output_list.empty()) {
  1528. GELOGW("Empty output");
  1529. return;
  1530. }
  1531. static const set<string> kSetOffsetTypes = { DATA_TYPE, AIPP_DATA_TYPE, MULTISHAPE, NETOUTPUT };
  1532. if ((kSetOffsetTypes.count(op_desc->GetType()) > 0) && !IsKnownSubgraphData(node_type.node)) {
  1533. if ((output_list[node_type.index] == kInvalidOffset) || (output_list[node_type.index] < offset)) {
  1534. output_list.at(node_type.index) = offset;
  1535. }
  1536. } else {
  1537. // fusion: keep the original other type offset value from op_desc
  1538. bool set_out_offset = (!has_mem_type_attr) ||
  1539. (memorys_type.size() > node_type.index && memorys_type[node_type.index] != RT_MEMORY_L1);
  1540. if (set_out_offset) {
  1541. output_list.at(node_type.index) = offset;
  1542. }
  1543. }
  1544. op_desc->SetOutputOffset(output_list);
  1545. } else if (node_type.mem_type == kWorkspace) {
  1546. vector<int64_t> workspace_list;
  1547. workspace_list = op_desc->GetWorkspace();
  1548. for (auto i = static_cast<uint32_t>(workspace_list.size()); i < node_type.index + 1; i++) {
  1549. workspace_list.emplace_back(kInvalidOffset);
  1550. }
  1551. vector<int64_t> workspace_mem_type;
  1552. bool has_workspace_mem_type = ge::AttrUtils::GetListInt(op_desc, TVM_ATTR_NAME_WORKSPACE_TYPE, workspace_mem_type);
  1553. // fusion: keep the original other type offset value from op_desc
  1554. bool set_workspace_offset = (!has_workspace_mem_type) ||
  1555. (workspace_mem_type.size() > node_type.index && workspace_mem_type[node_type.index] != RT_MEMORY_L1);
  1556. if (set_workspace_offset) {
  1557. workspace_list.at(node_type.index) = offset;
  1558. }
  1559. op_desc->SetWorkspace(workspace_list);
  1560. }
  1561. GELOGI("[IMAS]Set %s name[%s] %s[%u] offset to [%ld] streamid[%ld] size[%zu] realsize[%zu]"
  1562. " noalignsize[%zu] life time begin[%zu] life time end[%zu] child[%d:%d:%d:%d] isref[%d].", graph_name.c_str(),
  1563. op_desc->GetName().c_str(), node_type.GetMemType().c_str(), node_type.index, offset, op_desc->GetStreamId(),
  1564. block->Size(), real_size, no_align_size, op_desc->GetId(), end, child_block, block->reuse_mem_,
  1565. block->continuous_block_, block->deleted_block_, node_type.ref_input);
  1566. }
  1567. void SetBlockOpMemOffset(MemoryBlock *block, bool child_block) {
  1568. if (block == nullptr) {
  1569. return;
  1570. }
  1571. size_t index = 0;
  1572. size_t real_size = 0;
  1573. size_t no_align_size = 0;
  1574. auto real_size_list_size = block->RealSizeList().size();
  1575. for (const NodeTypeIndex &node_type_index : block->NodeTypeIndexList()) {
  1576. if (index < real_size_list_size) {
  1577. real_size = block->RealSizeList()[index];
  1578. no_align_size = block->NoAlignSizeList()[index];
  1579. }
  1580. SetOffsetSize(node_type_index, block, real_size, no_align_size, child_block);
  1581. index++;
  1582. }
  1583. }
  1584. void BlockMemAssigner::SetOpMemOffset(bool is_zero_copy) {
  1585. for (MemoryBlock *memory_block : memory_blocks_) {
  1586. if (memory_block == nullptr || memory_block->deleted_block_) {
  1587. continue;
  1588. }
  1589. if ((is_zero_copy && !memory_block->is_zero_copy_) || (!is_zero_copy && memory_block->is_zero_copy_)) {
  1590. continue;
  1591. }
  1592. SetBlockOpMemOffset(memory_block, false);
  1593. for (MemoryBlock *child_block : memory_block->ChildBlockList()) {
  1594. SetBlockOpMemOffset(child_block, true);
  1595. }
  1596. }
  1597. if (!is_zero_copy) {
  1598. for (const NodeTypeIndex &node_type_index : zero_memory_list_) {
  1599. MemoryBlock block(0, 0);
  1600. SetOffsetSize(node_type_index, &block, 0, 0, false);
  1601. }
  1602. }
  1603. }
  1604. Status BlockMemAssigner::Assign() {
  1605. vector<int64_t> ranges;
  1606. if (GetMemoryRanges(ranges) != SUCCESS) {
  1607. GELOGE(FAILED, "GetMemoryRanges Fail!");
  1608. return FAILED;
  1609. }
  1610. GE_IF_BOOL_EXEC(ranges.empty(), return SUCCESS);
  1611. AssignMemoryWithReuse(ranges);
  1612. SetOpMemOffset(false);
  1613. return SUCCESS;
  1614. }
  1615. bool BlockMemAssigner::CheckIsZeroMemNodeType(const string &node_type) const {
  1616. return (node_type == VARIABLE) || (node_type == CONSTANT) || (node_type == MULTISHAPE) ||
  1617. (node_type == HCOMBROADCAST) || (node_type == CONSTANTOP) ||
  1618. (node_type == ASSIGNADD) || (node_type == ASSIGNSUB) || (node_type == ASSIGN) || (node_type == HVDWAIT) ||
  1619. (node_type == HVDCALLBACKBROADCAST);
  1620. }
  1621. bool BlockMemAssigner::GetWorkSpaceMemoryType(const NodePtr &node, size_t index, int64_t &memory_type) {
  1622. memory_type = RT_MEMORY_HBM;
  1623. vector<int64_t> workspace_memory_type;
  1624. auto op_desc = node->GetOpDesc();
  1625. bool has_workspace_mem_type_attr =
  1626. ge::AttrUtils::GetListInt(op_desc, TVM_ATTR_NAME_WORKSPACE_TYPE, workspace_memory_type);
  1627. if (has_workspace_mem_type_attr && (workspace_memory_type.size() <= index)) {
  1628. GELOGE(INTERNAL_ERROR, "node[%s], workspace_memory size error![index:%zu, workspace:%zu]",
  1629. node->GetName().c_str(), index, workspace_memory_type.size());
  1630. return false;
  1631. }
  1632. memory_type = has_workspace_mem_type_attr ? workspace_memory_type[index] : RT_MEMORY_HBM;
  1633. return true;
  1634. }
  1635. } // namespace ge

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