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

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

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