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

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