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

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