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

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

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