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

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

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