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

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