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

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

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