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 80 kB

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

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