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.

somas.cc 70 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847
  1. /**
  2. * Copyright 2020-2021 Huawei Technologies Co., Ltd
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. * http://www.apache.org/licenses/LICENSE-2.0
  7. * Unless required by applicable law or agreed to in writing, software
  8. * distributed under the License is distributed on an "AS IS" BASIS,
  9. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. * See the License for the specific language governing permissions and
  11. * limitations under the License.
  12. */
  13. #include "backend/optimizer/somas/somas.h"
  14. #include <algorithm>
  15. #include <cstdio>
  16. #include <fstream>
  17. #include <iterator>
  18. #include <memory>
  19. #include <numeric>
  20. #include <set>
  21. #include <sstream>
  22. #include "backend/optimizer/somas/somas_node.h"
  23. #include "backend/optimizer/somas/somas_solver_pre.h"
  24. #include "backend/optimizer/somas/somas_stream.h"
  25. #include "backend/optimizer/somas/somas_tensor.h"
  26. #ifdef ENABLE_D
  27. #include "runtime/device/ascend/ascend_stream_assign.h"
  28. #endif
  29. #include "backend/optimizer/common/helper.h"
  30. #include "utils/ms_context.h"
  31. #include "debug/common.h"
  32. #ifdef ENABLE_DUMP_IR
  33. #include "debug/rdr/running_data_recorder.h"
  34. #endif
  35. #include "common/thread_pool.h"
  36. #include "profiler/device/common/memory_profiling.h"
  37. using mindspore::profiler::MemoryProfiling;
  38. using mindspore::profiler::NodeMemory;
  39. using mindspore::profiler::TensorMemory;
  40. namespace mindspore {
  41. namespace somas {
  42. constexpr auto kGapSize = 512;
  43. constexpr auto kParallelComputeSizeThreshold = 2000;
  44. constexpr auto kGraphId = "graph_id";
  45. constexpr auto kHashId = "hash_id";
  46. constexpr auto kMemOffset = "mem_offset";
  47. constexpr auto kNodeSize = "node_size";
  48. constexpr auto kTensorSize = "tensor_size";
  49. constexpr auto kContiguousSize = "contiguous_size";
  50. constexpr auto kRefNodeSize = "ref_node_size";
  51. constexpr auto kStreamSize = "stream_size";
  52. constexpr auto kStreamGroupSize = "stream_group_size";
  53. constexpr auto kTensors = "tensors";
  54. constexpr auto kTensorId = "tensor_id";
  55. constexpr auto kSize = "size";
  56. constexpr auto kOriSize = "ori_size";
  57. constexpr auto kLifelongValue = "lifelong_value";
  58. constexpr auto kLifeStart = "life_start";
  59. constexpr auto kLifeEnd = "life_end";
  60. constexpr auto kOffset = "offset";
  61. std::map<TensorType, std::string> tensor_type_name_map = {{kCommon, "Common"},
  62. {kOutputOnly, "OutputOnly"},
  63. {kWorkspace, "Workspace"},
  64. {kGetNextOutput, "GetNextOutput"},
  65. {kSummaryInput, "SummaryInput"},
  66. {kRefNodeInput, "RefNodeInput"},
  67. {kRefNodeOutput, "RefNodeOutput"},
  68. {kUnknown, "Unknown"}};
  69. std::map<LifeLongType, std::string> life_long_name_map = {{kLifeLongNone, "LifeLongNone"},
  70. {kLifeLongGraphAll, "LifeLongGraphAll"},
  71. {kLifeLongGraphStart, "LifeLongGraphStart"},
  72. {kLifeLongGraphEnd, "LifeLongGraphEnd"}};
  73. bool Somas::Allocate(const session::KernelGraph *graph) {
  74. auto ret = InitSomasTensors(graph);
  75. if (!ret) {
  76. MS_LOG(EXCEPTION) << "Somas Initialize Failed.";
  77. }
  78. if (tensors_list_.empty()) {
  79. MS_LOG(INFO) << "No Tensor for Somas";
  80. return true;
  81. }
  82. ret = CalcSomasModelHash(graph);
  83. if (ret) {
  84. std::string filename =
  85. save_graphs_path_ + "/somas_meta/" + "somas_graph" + std::to_string(graph->graph_id()) + "_" + hash_id_ + ".json";
  86. ret = LoadSomasResult(graph, filename);
  87. if (ret) {
  88. MS_LOG(INFO) << "Load Somas Cache file " << filename << " Successfully.";
  89. GenGraphStatisticInfo();
  90. return ret;
  91. } else {
  92. for (auto &tensor : tensors_list_) {
  93. tensor->offset_ = 0;
  94. }
  95. }
  96. } else {
  97. MS_LOG(ERROR) << "Calculate somas's model hash id failed.";
  98. }
  99. // Computing Conflict pairs
  100. MS_LOG(INFO) << "Start Computing Conflict Pairs";
  101. ComputeConflictPairs();
  102. MS_LOG(INFO) << "End Computing Conflict Pairs";
  103. ret = Assign(graph);
  104. if (!ret) {
  105. MS_LOG(EXCEPTION) << "Somas Assign Failed.";
  106. }
  107. SaveSomasResult(graph);
  108. GenGraphStatisticInfo();
  109. return ret;
  110. }
  111. bool Somas::CalcSomasModelHash(const session::KernelGraph *graph) {
  112. auto model_str = SomasInfo(true);
  113. hash_id_ = std::to_string(std::hash<std::string>()(model_str));
  114. MS_LOG(INFO) << "Graph " << graph->graph_id() << "'s SOMAS Model hash id is " << hash_id_;
  115. std::string filename =
  116. save_graphs_path_ + "/somas_meta/" + "somas_graph" + std::to_string(graph->graph_id()) + "_" + hash_id_ + ".info";
  117. if (filename.size() > PATH_MAX) {
  118. MS_LOG(WARNING) << "File path " << filename << " is too long.";
  119. return false;
  120. }
  121. auto real_path = Common::GetRealPath(filename);
  122. if (!real_path.has_value()) {
  123. MS_LOG(WARNING) << "Get real path failed. path=" << filename;
  124. return false;
  125. }
  126. std::ifstream ifs(real_path.value());
  127. if (ifs) {
  128. MS_LOG(INFO) << "Graph " << graph->graph_id() << "'s SOMAS Model file " << real_path.value() << " is exist.";
  129. ifs.close();
  130. return true;
  131. }
  132. ChangeFileMode(real_path.value(), S_IRWXU);
  133. std::ofstream ofs(real_path.value());
  134. if (!ofs.is_open()) {
  135. MS_LOG(WARNING) << "Open file '" << real_path.value() << "' failed!";
  136. return false;
  137. }
  138. ofs << model_str << std::endl;
  139. ofs.close();
  140. return true;
  141. }
  142. bool Somas::SaveSomasResult(const session::KernelGraph *graph) {
  143. nlohmann::json somas_json;
  144. somas_json[kGraphId] = graph->graph_id();
  145. somas_json[kHashId] = hash_id_;
  146. somas_json[kMemOffset] = mem_offset_;
  147. somas_json[kNodeSize] = nodes_list_.size();
  148. somas_json[kTensorSize] = tensors_list_.size();
  149. somas_json[kContiguousSize] = contiguous_tensors_list_.size();
  150. somas_json[kRefNodeSize] = ref_node_constraints_.size();
  151. somas_json[kStreamSize] = streams_list_.size();
  152. somas_json[kStreamGroupSize] = streams_groups_.size();
  153. std::vector<nlohmann::json> tensors_json;
  154. for (auto &tensor : tensors_list_) {
  155. nlohmann::json tensor_json;
  156. tensor_json[kTensorId] = tensor->GetId();
  157. tensor_json[kSize] = tensor->GetAlignedSize();
  158. tensor_json[kOriSize] = tensor->GetOriginalSize();
  159. tensor_json[kLifelongValue] = tensor->lifelong_value_;
  160. tensor_json[kLifeStart] = tensor->lifetime_.start_;
  161. tensor_json[kLifeEnd] = tensor->lifetime_.end_;
  162. tensor_json[kOffset] = tensor->GetOffset();
  163. tensors_json.emplace_back(tensor_json);
  164. }
  165. somas_json[kTensors] = tensors_json;
  166. std::string filename =
  167. save_graphs_path_ + "/somas_meta/" + "somas_graph" + std::to_string(graph->graph_id()) + "_" + hash_id_ + ".json";
  168. if (filename.size() > PATH_MAX) {
  169. MS_LOG(WARNING) << "File path " << filename << " is too long.";
  170. return false;
  171. }
  172. auto real_path = Common::GetRealPath(filename);
  173. if (!real_path.has_value()) {
  174. MS_LOG(WARNING) << "Get real path failed. path=" << filename;
  175. return false;
  176. }
  177. ChangeFileMode(real_path.value(), S_IRWXU);
  178. std::ofstream ofs(real_path.value());
  179. if (!ofs.is_open()) {
  180. MS_LOG(WARNING) << "Open file '" << real_path.value() << "' failed!";
  181. return false;
  182. }
  183. ofs << somas_json.dump() << std::endl;
  184. ofs.close();
  185. return true;
  186. }
  187. bool Somas::LoadSomasResult(const session::KernelGraph *graph, const string filename) {
  188. if (filename.length() <= strlen(".json")) {
  189. MS_LOG(WARNING) << "please check somas cache file path.";
  190. return false;
  191. }
  192. std::ifstream somas_json_fs(filename);
  193. if (!somas_json_fs.is_open()) {
  194. MS_LOG(INFO) << "Open json file: " << filename << " error, Somas Cache Missed.";
  195. return false;
  196. }
  197. nlohmann::json somas_json;
  198. try {
  199. somas_json_fs >> somas_json;
  200. somas_json_fs.close();
  201. } catch (std::exception &e) {
  202. MS_LOG(WARNING) << "Parse json file error: " << filename << ", sleep 500ms and retry again.";
  203. somas_json_fs.close();
  204. usleep(500000);
  205. std::ifstream retry_tmp(filename);
  206. if (!retry_tmp.is_open()) {
  207. MS_LOG(INFO) << "Open json file: " << filename << " error, please check kernel_meta.";
  208. return false;
  209. }
  210. retry_tmp >> somas_json;
  211. retry_tmp.close();
  212. }
  213. auto ret = VerifySomasResult(graph, somas_json);
  214. if (!ret) {
  215. MS_LOG(WARNING) << "Verify Somas Result Failed.";
  216. return false;
  217. }
  218. auto mem_offset = somas_json[kMemOffset];
  219. mem_offset_ = mem_offset;
  220. ret = UpdateTensorsOffset(somas_json[kTensors]);
  221. return ret;
  222. }
  223. bool Somas::VerifySomasResult(const session::KernelGraph *graph, const nlohmann::json &somas_json) const {
  224. auto graph_id = somas_json[kGraphId];
  225. auto hash_id = somas_json[kHashId];
  226. auto node_size = somas_json[kNodeSize];
  227. auto tensor_size = somas_json[kTensorSize];
  228. auto contiguous_size = somas_json[kContiguousSize];
  229. auto ref_node_size = somas_json[kRefNodeSize];
  230. auto stream_size = somas_json[kStreamSize];
  231. auto stream_group_size = somas_json[kStreamGroupSize];
  232. if (graph_id != graph->graph_id()) {
  233. MS_LOG(WARNING) << "Mismatch graph id " << graph_id << " vs " << graph->graph_id();
  234. return false;
  235. }
  236. if (hash_id != hash_id_) {
  237. MS_LOG(WARNING) << "Mismatch hash id " << hash_id << " vs " << hash_id_;
  238. return false;
  239. }
  240. if (node_size != nodes_list_.size()) {
  241. MS_LOG(WARNING) << "Mismatch node size " << node_size << " vs " << nodes_list_.size();
  242. return false;
  243. }
  244. if (tensor_size != tensors_list_.size()) {
  245. MS_LOG(WARNING) << "Mismatch tensor size " << tensor_size << " vs " << tensors_list_.size();
  246. return false;
  247. }
  248. if (contiguous_size != contiguous_tensors_list_.size()) {
  249. MS_LOG(WARNING) << "Mismatch contiguous size " << contiguous_size << " vs " << contiguous_tensors_list_.size();
  250. return false;
  251. }
  252. if (ref_node_size != ref_node_constraints_.size()) {
  253. MS_LOG(WARNING) << "Mismatch ref node size " << ref_node_size << " vs " << ref_node_constraints_.size();
  254. return false;
  255. }
  256. if (stream_size != streams_list_.size()) {
  257. MS_LOG(WARNING) << "Mismatch stream size " << stream_size << " vs " << streams_list_.size();
  258. return false;
  259. }
  260. if (stream_group_size != streams_groups_.size()) {
  261. MS_LOG(WARNING) << "Mismatch stream group size " << stream_group_size << " vs " << streams_groups_.size();
  262. return false;
  263. }
  264. return true;
  265. }
  266. bool Somas::UpdateTensorsOffset(const std::vector<nlohmann::json> &tensors_json) {
  267. bool ret = true;
  268. for (auto &tensor_json : tensors_json) {
  269. auto tensor_id = tensor_json[kTensorId];
  270. auto size = tensor_json[kSize];
  271. auto ori_size = tensor_json[kOriSize];
  272. auto lifelong_value = tensor_json[kLifelongValue];
  273. auto life_start = tensor_json[kLifeStart];
  274. auto life_end = tensor_json[kLifeEnd];
  275. auto offset = tensor_json[kOffset];
  276. auto iter = tensors_map_.find(tensor_id);
  277. if (iter != tensors_map_.end()) {
  278. if (size != iter->second->aligned_size_) {
  279. MS_LOG(WARNING) << "Mismatch size of tensor " << tensor_id << " " << size << " vs "
  280. << iter->second->aligned_size_;
  281. ret = false;
  282. break;
  283. }
  284. if (ori_size != iter->second->GetOriginalSize()) {
  285. MS_LOG(WARNING) << "Mismatch original size of tensor " << tensor_id << " " << ori_size << " vs "
  286. << iter->second->GetOriginalSize();
  287. ret = false;
  288. break;
  289. }
  290. if (lifelong_value != iter->second->lifelong_value_) {
  291. MS_LOG(WARNING) << "Mismatch lifelong value of tensor " << tensor_id << " " << lifelong_value << " vs "
  292. << iter->second->lifelong_value_;
  293. ret = false;
  294. break;
  295. }
  296. if (life_start != iter->second->lifetime_.start_) {
  297. MS_LOG(WARNING) << "Mismatch life start of tensor " << tensor_id << " " << life_start << " vs "
  298. << iter->second->lifetime_.start_;
  299. ret = false;
  300. break;
  301. }
  302. if (life_end != iter->second->lifetime_.end_) {
  303. MS_LOG(WARNING) << "Mismatch life start of tensor " << tensor_id << " " << life_end << " vs "
  304. << iter->second->lifetime_.end_;
  305. ret = false;
  306. break;
  307. }
  308. // verify pass, update memory offset
  309. iter->second->offset_ = offset;
  310. } else {
  311. MS_LOG(WARNING) << "Can't find tensor " << tensor_id;
  312. ret = false;
  313. break;
  314. }
  315. }
  316. return ret;
  317. }
  318. bool Somas::InitSomasTensors(const session::KernelGraph *graph) {
  319. MS_EXCEPTION_IF_NULL(graph);
  320. InitBasicInfo(graph);
  321. IndependentNodeOutputProcess(graph);
  322. SummaryInputProcess(graph);
  323. RefNodeProcess(graph);
  324. NonTaskSplitProcess(graph);
  325. UnReuseNodeProcess(graph);
  326. GenContiguousList(graph);
  327. GetNextOutputProcess(graph);
  328. if (tensors_list_.empty()) {
  329. MS_LOG(INFO) << "No Tensor from graph " << graph->graph_id();
  330. return true;
  331. }
  332. MS_LOG(INFO) << "Created " << streams_list_.size() << " streams (" << streams_groups_.size() << " groups), "
  333. << nodes_list_.size() << " nodes, " << tensors_list_.size() << " tensors, and "
  334. << contiguous_tensors_list_.size() << " contiguous lists";
  335. #ifdef ENABLE_DUMP_IR
  336. SubModuleId module = SubModuleId::SM_OPTIMIZER;
  337. std::string tag = "somas";
  338. std::string filename = "somas_pre_processed_info_" + std::to_string(graph->graph_id());
  339. mindspore::RDR::RecordString(module, tag, SomasInfo(), filename);
  340. filename = "somas_offline_log_" + std::to_string(graph->graph_id());
  341. mindspore::RDR::RecordString(module, tag, Offline(), filename);
  342. #endif
  343. if (save_graphs_) {
  344. std::string file_path =
  345. save_graphs_path_ + "/" + "somas_pre_processed_info_" + std::to_string(graph->graph_id()) + ".ir";
  346. DumpSomasInfoIR(file_path);
  347. std::string offline_file_path =
  348. save_graphs_path_ + "/" + "somas_offline_log_" + std::to_string(graph->graph_id()) + ".ir";
  349. DumpOfflineIR(offline_file_path);
  350. }
  351. return true;
  352. }
  353. void Somas::InitSomasStreamAndNode(const session::KernelGraph *graph) {
  354. MS_EXCEPTION_IF_NULL(graph);
  355. streams_list_ = {};
  356. nodes_list_ = {};
  357. size_t node_index = 0;
  358. auto kernel_cnodes = graph->execution_order();
  359. for (const auto &kernel : kernel_cnodes) {
  360. SomasStreamPtr stream;
  361. auto stream_id = AnfAlgo::GetStreamId(kernel);
  362. auto it = find_if(streams_list_.begin(), streams_list_.end(),
  363. [stream_id](const SomasStreamPtr &s) { return s->GetId() == stream_id; });
  364. if (it == streams_list_.end()) {
  365. stream = std::make_shared<SomasStream>(stream_id);
  366. streams_list_.push_back(stream);
  367. } else {
  368. stream = *it;
  369. }
  370. // Node
  371. NodeType type = kCommonNode;
  372. if (AnfAlgo::IsCommunicationOp(kernel)) {
  373. type = kCommunicationNode;
  374. }
  375. auto node = std::make_shared<SomasNode>(node_index, type, stream);
  376. MS_EXCEPTION_IF_NULL(node);
  377. node->scope_full_name_ = kernel->fullname_with_scope();
  378. nodes_list_.push_back(node);
  379. stream->nodes_.push_back(node);
  380. auto key = kernel.get();
  381. nodes_map_[key] = node;
  382. node_index++;
  383. }
  384. }
  385. void Somas::InitSomasOutputAndWorkspaceTensors(const session::KernelGraph *graph) {
  386. MS_EXCEPTION_IF_NULL(graph);
  387. tensors_list_ = {};
  388. size_t tensor_index = 0;
  389. auto kernel_cnodes = graph->execution_order();
  390. for (const auto &kernel : kernel_cnodes) {
  391. auto node = nodes_map_[kernel.get()];
  392. MS_EXCEPTION_IF_NULL(node);
  393. auto stream = node->GetStream();
  394. MS_EXCEPTION_IF_NULL(stream);
  395. // Output Tensor
  396. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  397. MS_EXCEPTION_IF_NULL(kernel_mod);
  398. auto output_sizes = kernel_mod->GetOutputSizeList();
  399. for (const auto &size : output_sizes) {
  400. auto output_tensor_index = tensor_index;
  401. tensor_index++;
  402. // Set all output tensor lifelong to true.
  403. auto tensor = std::make_shared<SomasTensor>(output_tensor_index, node, stream, size, kLifeLongNone);
  404. tensor->lifetime_.start_ = node->GetId();
  405. tensor->lifetime_.end_ = node->GetId();
  406. tensor->type_ = kOutputOnly;
  407. tensors_list_.push_back(tensor);
  408. tensors_map_[output_tensor_index] = tensor;
  409. stream->tensors_.push_back(tensor);
  410. node->tensors_.insert(tensor);
  411. node->output_tensors_.push_back(tensor);
  412. }
  413. // WorkSpace Tensor
  414. auto workspace_sizes = kernel_mod->GetWorkspaceSizeList();
  415. for (const auto &size : workspace_sizes) {
  416. auto workspace_tensor_index = tensor_index;
  417. tensor_index++;
  418. SomasTensorPtr tensor = std::make_shared<SomasTensor>(workspace_tensor_index, node, stream, size, kLifeLongNone);
  419. tensor->type_ = kWorkspace;
  420. tensor->lifetime_.start_ = node->GetId();
  421. tensor->lifetime_.end_ = node->GetId();
  422. tensors_list_.push_back(tensor);
  423. tensors_map_[workspace_tensor_index] = tensor;
  424. stream->tensors_.push_back(tensor);
  425. node->tensors_.insert(tensor);
  426. node->workspace_tensors_.push_back(tensor);
  427. }
  428. }
  429. }
  430. void Somas::InitSomasInputTensors(const session::KernelGraph *graph) {
  431. MS_EXCEPTION_IF_NULL(graph);
  432. bool is_all_nop_node = opt::IsAllNopNode(graph);
  433. auto kernel_cnodes = graph->execution_order();
  434. for (const auto &kernel : kernel_cnodes) {
  435. if (AnfAlgo::GetCNodeName(kernel) != kAtomicAddrCleanOpName) {
  436. InitCommonNodeInputs(is_all_nop_node, kernel);
  437. } else {
  438. InitAtomicCleanInputs(is_all_nop_node, kernel);
  439. }
  440. }
  441. }
  442. void Somas::InitCommonNodeInputs(bool is_all_nop_node, const CNodePtr &kernel) {
  443. auto node = nodes_map_[kernel.get()];
  444. MS_EXCEPTION_IF_NULL(node);
  445. auto stream = node->GetStream();
  446. MS_EXCEPTION_IF_NULL(stream);
  447. // Input Tensor
  448. auto input_tensor_num = AnfAlgo::GetInputTensorNum(kernel);
  449. size_t real_input_index = 0;
  450. for (size_t i = 0; i < input_tensor_num; i++) {
  451. auto input_node = kernel->input(i + 1);
  452. session::KernelWithIndex prenode_index;
  453. if (is_all_nop_node) {
  454. prenode_index = AnfAlgo::VisitKernelWithReturnType(input_node, 0, false);
  455. } else {
  456. prenode_index = AnfAlgo::VisitKernelWithReturnType(input_node, 0, true);
  457. }
  458. if (AnfAlgo::CheckPrimitiveType(prenode_index.first, prim::kPrimMakeTuple)) {
  459. MS_LOG(EXCEPTION) << "Input node [" << input_node->DebugString() << "]'s input " << i << " is MakeTuple";
  460. }
  461. if (!AnfAlgo::IsRealCNodeKernel(prenode_index.first)) {
  462. auto op_name = AnfAlgo::GetCNodeName(kernel);
  463. TypeId input_origin_type = AnfAlgo::GetPrevNodeOutputInferDataType(kernel, i);
  464. if ((op_name == kDynamicRNNOpName || op_name == kDynamicGRUV2OpName) && input_origin_type == kMetaTypeNone) {
  465. continue;
  466. }
  467. auto parameter = GetSomasParameters(prenode_index.first, prenode_index.second);
  468. node->input_parameters_map_[real_input_index] = parameter;
  469. real_input_index++;
  470. MS_LOG(DEBUG) << "Input [" << prenode_index.first->fullname_with_scope() << "] is not a real cnode kernel.";
  471. continue;
  472. }
  473. auto iter = nodes_map_.find(prenode_index.first.get());
  474. if (iter == nodes_map_.end()) {
  475. MS_LOG(EXCEPTION) << "Kernel[" << kernel->fullname_with_scope() << "]'s input " << i << " ["
  476. << prenode_index.first->fullname_with_scope() << "] is not init.";
  477. }
  478. auto pre_somas_node = iter->second;
  479. if (prenode_index.second > pre_somas_node->output_tensors_.size()) {
  480. MS_LOG(EXCEPTION) << "Output index " << prenode_index.second << " exceed input node ["
  481. << prenode_index.first->fullname_with_scope() << "]'s outputs size "
  482. << pre_somas_node->output_tensors_.size();
  483. }
  484. auto input_somas_tensor = pre_somas_node->output_tensors_[prenode_index.second];
  485. MS_EXCEPTION_IF_NULL(input_somas_tensor);
  486. node->input_tensors_.push_back(input_somas_tensor);
  487. real_input_index++;
  488. if (input_somas_tensor->type_ == kOutputOnly) {
  489. input_somas_tensor->type_ = kCommon;
  490. }
  491. input_somas_tensor->destinations_.insert(node);
  492. input_somas_tensor->destinationStreams_.insert(stream);
  493. if (input_somas_tensor->lifetime_.end_ < node->GetId()) {
  494. input_somas_tensor->lifetime_.end_ = node->GetId();
  495. }
  496. if (node != pre_somas_node) {
  497. node->ancestor_nodes_.insert(pre_somas_node);
  498. }
  499. auto input_tensor_stream = input_somas_tensor->GetSourceStream();
  500. if (input_tensor_stream != stream) {
  501. stream->ancestor_streams_.insert(input_tensor_stream);
  502. input_somas_tensor->between_streams_ = true;
  503. }
  504. }
  505. }
  506. void Somas::InitAtomicCleanInputs(bool is_all_nop_node, const CNodePtr &kernel) {
  507. auto node = nodes_map_[kernel.get()];
  508. MS_EXCEPTION_IF_NULL(node);
  509. auto stream = node->GetStream();
  510. MS_EXCEPTION_IF_NULL(stream);
  511. MS_EXCEPTION_IF_NULL(kernel->inputs()[1]);
  512. auto pre_node = (kernel->inputs()[1])->cast<CNodePtr>();
  513. auto iter = nodes_map_.find(pre_node.get());
  514. if (iter == nodes_map_.end()) {
  515. MS_LOG(EXCEPTION) << "Kernel[" << kernel->fullname_with_scope() << "]'s input [" << pre_node->fullname_with_scope()
  516. << "] is not init.";
  517. }
  518. auto pre_somas_node = iter->second;
  519. // set clean output tensors
  520. if (AnfAlgo::HasNodeAttr(kAttrAtomicOutputIndexs, pre_node)) {
  521. auto clean_output_indexs = AnfAlgo::GetNodeAttr<std::vector<size_t>>(pre_node, kAttrAtomicOutputIndexs);
  522. for (auto index : clean_output_indexs) {
  523. if (index > pre_somas_node->output_tensors_.size()) {
  524. MS_LOG(EXCEPTION) << "Output index " << index << " exceed input node [" << pre_node->fullname_with_scope()
  525. << "]'s outputs size " << pre_somas_node->output_tensors_.size();
  526. }
  527. auto input_somas_tensor = pre_somas_node->output_tensors_[index];
  528. MS_EXCEPTION_IF_NULL(input_somas_tensor);
  529. node->input_tensors_.push_back(input_somas_tensor);
  530. input_somas_tensor->destinations_.insert(node);
  531. input_somas_tensor->destinationStreams_.insert(stream);
  532. if (input_somas_tensor->lifetime_.start_ > node->GetId()) {
  533. input_somas_tensor->lifetime_.start_ = node->GetId();
  534. }
  535. node->ancestor_nodes_.insert(pre_somas_node);
  536. auto input_tensor_stream = input_somas_tensor->GetSourceStream();
  537. if (input_tensor_stream != stream) {
  538. stream->ancestor_streams_.insert(input_tensor_stream);
  539. input_somas_tensor->between_streams_ = true;
  540. }
  541. }
  542. }
  543. // set clean workspace tensors
  544. if (AnfAlgo::HasNodeAttr(kAttrAtomicWorkspaceIndexs, pre_node)) {
  545. auto clean_workspace_indexs = AnfAlgo::GetNodeAttr<std::vector<size_t>>(pre_node, kAttrAtomicWorkspaceIndexs);
  546. for (const auto &index : clean_workspace_indexs) {
  547. if (index > pre_somas_node->output_tensors_.size()) {
  548. MS_LOG(EXCEPTION) << "Workspace index " << index << " exceed input node [" << pre_node->fullname_with_scope()
  549. << "]'s Workspace size " << pre_somas_node->workspace_tensors_.size();
  550. }
  551. auto input_somas_tensor = pre_somas_node->workspace_tensors_[index];
  552. MS_EXCEPTION_IF_NULL(input_somas_tensor);
  553. node->input_tensors_.push_back(input_somas_tensor);
  554. input_somas_tensor->destinations_.insert(node);
  555. input_somas_tensor->destinationStreams_.insert(stream);
  556. if (input_somas_tensor->lifetime_.start_ > node->GetId()) {
  557. input_somas_tensor->lifetime_.start_ = node->GetId();
  558. }
  559. node->ancestor_nodes_.insert(pre_somas_node);
  560. auto input_tensor_stream = input_somas_tensor->GetSourceStream();
  561. if (input_tensor_stream != stream) {
  562. stream->ancestor_streams_.insert(input_tensor_stream);
  563. input_somas_tensor->between_streams_ = true;
  564. }
  565. }
  566. }
  567. }
  568. SomasParameterPtr Somas::CreateSomasParameters(AnfNodePtr node, size_t index) {
  569. auto id = parameters_list_.size();
  570. auto device_addr = AnfAlgo::GetOutputAddr(node, index);
  571. if (device_addr == nullptr) {
  572. MS_LOG(EXCEPTION) << "Node " << node->fullname_with_scope() << " has no device address before Somas.";
  573. }
  574. auto param = std::make_shared<SomasParameter>(id, node, index, device_addr->GetPtr(), device_addr->GetSize());
  575. parameters_list_.push_back(param);
  576. return param;
  577. }
  578. SomasParameterPtr Somas::GetSomasParameters(AnfNodePtr node, size_t index) {
  579. auto key = node.get();
  580. auto iter = parameters_map_.find(key);
  581. if (iter != parameters_map_.end()) {
  582. auto it = std::find_if(iter->second.begin(), iter->second.end(),
  583. [index](SomasParameterPtr param) -> bool { return index == param->output_index_; });
  584. if (it != iter->second.end()) {
  585. return *it;
  586. } else {
  587. auto new_param = CreateSomasParameters(node, index);
  588. iter->second.push_back(new_param);
  589. return new_param;
  590. }
  591. } else {
  592. auto new_param = CreateSomasParameters(node, index);
  593. parameters_map_[key].push_back(new_param);
  594. return new_param;
  595. }
  596. }
  597. void Somas::InitBasicInfo(const session::KernelGraph *graph) {
  598. MS_EXCEPTION_IF_NULL(graph);
  599. #ifdef ENABLE_D
  600. streams_groups_ = device::ascend::AscendStreamAssign::GetInstance().get_stream_group();
  601. #endif
  602. InitSomasStreamAndNode(graph);
  603. InitSomasOutputAndWorkspaceTensors(graph);
  604. InitSomasInputTensors(graph);
  605. auto context_ptr = MsContext::GetInstance();
  606. MS_EXCEPTION_IF_NULL(context_ptr);
  607. #ifdef ENABLE_DUMP_IR
  608. SubModuleId module = SubModuleId::SM_OPTIMIZER;
  609. std::string tag = "somas";
  610. std::string filename = "somas_initial_info_" + std::to_string(graph->graph_id());
  611. mindspore::RDR::RecordString(module, tag, SomasInfo(), filename);
  612. #endif
  613. save_graphs_ = context_ptr->get_param<bool>(MS_CTX_SAVE_GRAPHS_FLAG);
  614. save_graphs_path_ = context_ptr->get_param<std::string>(MS_CTX_SAVE_GRAPHS_PATH);
  615. if (save_graphs_path_.empty()) {
  616. save_graphs_path_ = ".";
  617. }
  618. if (save_graphs_) {
  619. std::string file_path = save_graphs_path_ + "/" + "somas_initial_info_" + std::to_string(graph->graph_id()) + ".ir";
  620. DumpSomasInfoIR(file_path);
  621. }
  622. }
  623. void Somas::GetNextOutputProcess(const session::KernelGraph *graph) {
  624. MS_EXCEPTION_IF_NULL(graph);
  625. auto kernel_cnodes = graph->execution_order();
  626. size_t total_size = 0;
  627. for (const auto &kernel : kernel_cnodes) {
  628. if (AnfAlgo::GetCNodeName(kernel) != kGetNextOpName) {
  629. continue;
  630. }
  631. auto iter = nodes_map_.find(kernel.get());
  632. if (iter != nodes_map_.end()) {
  633. auto getnext_output_tensors = iter->second->output_tensors_;
  634. for (auto &tensor : getnext_output_tensors) {
  635. total_size += tensor->GetAlignedSize();
  636. tensor->lifelong_value_ = kLifeLongGraphAll;
  637. tensor->type_ = kGetNextOutput;
  638. }
  639. }
  640. }
  641. MS_LOG(INFO) << "Special Tensor total size: GetNext Output " << total_size;
  642. }
  643. void Somas::IndependentNodeOutputProcess(const session::KernelGraph *graph) {
  644. MS_EXCEPTION_IF_NULL(graph);
  645. auto kernel_cnodes = graph->execution_order();
  646. size_t total_size = 0;
  647. for (const auto &kernel : kernel_cnodes) {
  648. bool independent = AnfAlgo::IsIndependentNode(kernel);
  649. if (!independent) {
  650. continue;
  651. }
  652. auto iter = nodes_map_.find(kernel.get());
  653. if (iter != nodes_map_.end()) {
  654. auto semi_reuse_output_tensors = iter->second->output_tensors_;
  655. for (auto &tensor : semi_reuse_output_tensors) {
  656. total_size += tensor->GetAlignedSize();
  657. tensor->lifelong_value_ = kLifeLongGraphAll;
  658. }
  659. }
  660. }
  661. MS_LOG(INFO) << "Special Tensor total size: Independent Node output " << total_size;
  662. }
  663. void Somas::SummaryInputProcess(const session::KernelGraph *graph) {
  664. MS_EXCEPTION_IF_NULL(graph);
  665. bool summary_exist = graph->summary_node_exist();
  666. if (!summary_exist) {
  667. return;
  668. }
  669. auto summary_nodes = graph->summary_nodes();
  670. if (summary_nodes.empty()) {
  671. return;
  672. }
  673. size_t total_summary_size = 0;
  674. for (auto &node_item : summary_nodes) {
  675. auto node = node_item.second.first;
  676. size_t index = IntToSize(node_item.second.second);
  677. auto iter = nodes_map_.find(node.get());
  678. if (iter != nodes_map_.end()) {
  679. auto input_node = iter->second;
  680. if (index < input_node->output_tensors_.size()) {
  681. auto tensor = iter->second->output_tensors_[index];
  682. tensor->lifelong_value_ = kLifeLongGraphAll;
  683. tensor->type_ = kSummaryInput;
  684. total_summary_size += tensor->GetAlignedSize();
  685. MS_LOG(INFO) << "Set summary node input tensor's lifelong, node: " << node->fullname_with_scope()
  686. << " index: " << index;
  687. } else {
  688. MS_LOG(WARNING) << "Index exceed size, node " << node->fullname_with_scope() << " index: " << index
  689. << " size: " << input_node->output_tensors_.size();
  690. }
  691. } else {
  692. MS_LOG(WARNING) << "Can't find summary input node " << node->fullname_with_scope() << " index: " << index;
  693. }
  694. }
  695. MS_LOG(INFO) << "Special Tensor total size: SummaryNodes: " << total_summary_size;
  696. }
  697. void Somas::RefNodeProcess(const session::KernelGraph *graph) {
  698. MS_EXCEPTION_IF_NULL(graph);
  699. auto kernel_cnodes = graph->execution_order();
  700. size_t total_output_size = 0;
  701. size_t total_input_size = 0;
  702. for (const auto &kernel : kernel_cnodes) {
  703. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  704. if (kernel_mod == nullptr) {
  705. MS_LOG(WARNING) << "Kernel mode is NULL Of " << kernel->fullname_with_scope();
  706. continue;
  707. }
  708. auto output_sizes = kernel_mod->GetOutputSizeList();
  709. size_t output_index = 0;
  710. for (const auto &size : output_sizes) {
  711. auto out_index = output_index;
  712. output_index++;
  713. session::AnfWithOutIndex out_pair(kernel, out_index);
  714. if (graph->IsInRefOutputMap(out_pair)) {
  715. auto origin_pair = graph->GetRefCorrespondOutput(out_pair);
  716. MS_EXCEPTION_IF_NULL(origin_pair.first);
  717. auto output_tensor = nodes_map_[kernel.get()]->output_tensors_[out_index];
  718. MS_EXCEPTION_IF_NULL(output_tensor);
  719. output_tensor->type_ = kRefNodeOutput;
  720. total_output_size += size;
  721. if (AnfAlgo::IsRealCNodeKernel(origin_pair.first)) {
  722. auto ori_node = origin_pair.first->cast<CNodePtr>();
  723. auto ori_index = origin_pair.second;
  724. auto input_tensor = nodes_map_[ori_node.get()]->output_tensors_[ori_index];
  725. MS_EXCEPTION_IF_NULL(input_tensor);
  726. input_tensor->type_ = kRefNodeInput;
  727. total_input_size += input_tensor->aligned_size_;
  728. std::vector<size_t> refnode_input_output;
  729. refnode_input_output.push_back(input_tensor->GetId());
  730. refnode_input_output.push_back(output_tensor->GetId());
  731. ref_node_constraints_.push_back(refnode_input_output);
  732. MS_LOG(INFO) << "RefNode: input " << input_tensor->GetId() << " output " << output_tensor->GetId();
  733. }
  734. }
  735. }
  736. }
  737. MS_LOG(INFO) << "Special Tensor total size: RefNode: input " << total_input_size << " output " << total_output_size;
  738. }
  739. void Somas::NonTaskSplitProcess(const session::KernelGraph *graph) {
  740. MS_EXCEPTION_IF_NULL(graph);
  741. auto kernel_cnodes = graph->execution_order();
  742. for (const auto &kernel : kernel_cnodes) {
  743. auto op_name = AnfAlgo::GetCNodeName(kernel);
  744. if ((op_name == kSplitOpName || op_name == kSplitVOpName) && AnfAlgo::HasNodeAttr(kAttrNonTask, kernel)) {
  745. std::vector<size_t> refnode_input_output;
  746. auto node = nodes_map_[kernel.get()];
  747. if (node->input_tensors_.size() == 0) {
  748. MS_LOG(EXCEPTION) << op_name << " has no input tensor, can not do split non_task process.";
  749. }
  750. auto input_tensor = node->input_tensors_[0];
  751. input_tensor->type_ = kRefNodeInput;
  752. refnode_input_output.push_back(input_tensor->GetId());
  753. for (auto &output_tensor : node->output_tensors_) {
  754. output_tensor->type_ = kRefNodeOutput;
  755. refnode_input_output.push_back(output_tensor->GetId());
  756. }
  757. ref_node_constraints_.push_back(refnode_input_output);
  758. }
  759. }
  760. }
  761. void Somas::UnReuseNodeProcess(const session::KernelGraph *graph) {
  762. MS_EXCEPTION_IF_NULL(graph);
  763. vector<string> full_name_list = {};
  764. if (full_name_list.size() == 0) {
  765. return;
  766. }
  767. auto kernel_cnodes = graph->execution_order();
  768. for (const auto &kernel : kernel_cnodes) {
  769. auto full_name = kernel->fullname_with_scope();
  770. auto iter = std::find(full_name_list.begin(), full_name_list.end(), full_name);
  771. if (iter != full_name_list.end()) {
  772. MS_LOG(INFO) << "Set UnReuse Node in somas, Node:" << full_name;
  773. auto key = kernel.get();
  774. auto somas_node = nodes_map_[key];
  775. // input
  776. auto inputs = somas_node->input_tensors_;
  777. for (auto &input : inputs) {
  778. input->lifelong_value_ = kLifeLongGraphAll;
  779. }
  780. // output
  781. auto outputs = somas_node->output_tensors_;
  782. MS_LOG(INFO) << "Output size of " << kernel->fullname_with_scope() << " is " << outputs.size();
  783. for (auto &output : outputs) {
  784. output->lifelong_value_ = kLifeLongGraphAll;
  785. }
  786. // workspace
  787. auto workspaces = somas_node->workspace_tensors_;
  788. for (auto &workspace : workspaces) {
  789. workspace->lifelong_value_ = kLifeLongGraphAll;
  790. }
  791. }
  792. }
  793. }
  794. void Somas::GenContiguousList(const session::KernelGraph *graph) {
  795. MS_EXCEPTION_IF_NULL(graph);
  796. for (const auto &node : nodes_list_) {
  797. MS_EXCEPTION_IF_NULL(node);
  798. if (node->GetType() != kCommunicationNode) {
  799. continue;
  800. }
  801. // Contiguous input
  802. if ((!node->input_tensors_.empty()) && (!node->input_tensors_[0]->contiguous_)) {
  803. node->input_tensors_[0]->aligned_size_ += kGapSize;
  804. node->input_tensors_[node->input_tensors_.size() - 1]->aligned_size_ += kGapSize;
  805. std::vector<size_t> inputs;
  806. for (const auto &input_tensor : node->input_tensors_) {
  807. comm_input_total_size_ += input_tensor->aligned_size_;
  808. input_tensor->contiguous_ = true;
  809. inputs.push_back(input_tensor->GetId());
  810. }
  811. contiguous_tensors_list_.push_back(inputs);
  812. }
  813. // Contiguous output
  814. if ((!node->output_tensors_.empty()) && (!node->output_tensors_[0]->contiguous_)) {
  815. node->output_tensors_[0]->aligned_size_ += kGapSize;
  816. node->output_tensors_[node->output_tensors_.size() - 1]->aligned_size_ += kGapSize;
  817. std::vector<size_t> outputs;
  818. for (const auto &output_tensor : node->output_tensors_) {
  819. comm_output_total_size_ += output_tensor->aligned_size_;
  820. output_tensor->contiguous_ = true;
  821. outputs.push_back(output_tensor->GetId());
  822. }
  823. contiguous_tensors_list_.push_back(outputs);
  824. }
  825. }
  826. }
  827. void Somas::PreprocessingConflicts() {
  828. // Compute ancestor streams
  829. for (auto stream : streams_list_) {
  830. stream->ComputeAncestorStreams();
  831. }
  832. // Preset ancestor streams for node
  833. for (auto node : nodes_list_) {
  834. node->PresetAncestorStreams(streams_list_);
  835. }
  836. // Compute ancestor nodes : needs to be executed in topological order
  837. for (auto node : nodes_list_) {
  838. node->ComputeAncestorNodes();
  839. }
  840. // Compute MaxDestinationId for between-stream tensors
  841. for (auto tensor : tensors_list_) {
  842. if (tensor->IsBetweenStreams()) {
  843. tensor->ComputeMaxDestinationId();
  844. }
  845. }
  846. // Preprocessing for stream groups
  847. for (auto group : streams_groups_) {
  848. vector<SomasStreamPtr> previous_streams;
  849. for (int64_t stream_id : group) {
  850. auto it = std::find_if(streams_list_.begin(), streams_list_.end(),
  851. [stream_id](const SomasStreamPtr &stream) { return stream->GetId() == stream_id; });
  852. if (it != streams_list_.end()) {
  853. for (auto stream : previous_streams) {
  854. (*it)->ancestor_streams_group_.insert(stream);
  855. }
  856. previous_streams.push_back(*it);
  857. }
  858. }
  859. }
  860. // Atomic: fix any issues on saved lifetimes of tensors
  861. for (auto tensor : tensors_list_) {
  862. MS_EXCEPTION_IF_NULL(tensor);
  863. for (auto node : tensor->destinations_) {
  864. MS_EXCEPTION_IF_NULL(node);
  865. MS_EXCEPTION_IF_NULL(tensor->GetSourceNode());
  866. if (tensor->GetSourceNode()->GetId() > node->GetId()) {
  867. tensor->lifetime_.start_ = node->GetId();
  868. }
  869. }
  870. MS_EXCEPTION_IF_NULL(tensor->GetSourceNode());
  871. if (tensor->GetSourceNode()->GetId() > tensor->lifetime_.end_) {
  872. tensor->lifetime_.end_ = tensor->GetSourceNode()->GetId();
  873. }
  874. }
  875. }
  876. void Somas::ComputeConflictPairs() {
  877. if (tensors_list_.empty()) {
  878. MS_LOG(INFO) << "No Tensor for Conflict computing";
  879. return;
  880. }
  881. MS_LOG(INFO) << "Start Preprocessing Conflicts";
  882. PreprocessingConflicts();
  883. MS_LOG(INFO) << "End Preprocessing Conflicts";
  884. MS_LOG(INFO) << "Start Conflict Computing (Bitset Model)";
  885. auto start_conflict = std::chrono::system_clock::now();
  886. std::sort(nodes_list_.begin(), nodes_list_.end(), NodeSort);
  887. UpdateTensorDestinations();
  888. MS_LOG(INFO) << "Start Bitset";
  889. std::vector<DynamicBitSet> nodes_dependency;
  890. size_t count = nodes_list_.back()->GetId() + 1;
  891. for (size_t i = 0; i < count; i++) {
  892. nodes_dependency.emplace_back(count);
  893. }
  894. MS_LOG(INFO) << "Start Path Computing";
  895. // Loop to compute ancestor paths via bitset for time dependence
  896. for (const auto &node : nodes_list_) {
  897. for (const auto &ancestor : node->ancestor_nodes_) {
  898. nodes_dependency[node->GetId()].SetBitTrue(ancestor->GetId());
  899. Union(&nodes_dependency[node->GetId()], &nodes_dependency[ancestor->GetId()]);
  900. }
  901. }
  902. MS_LOG(INFO) << "End Path Computing";
  903. MS_LOG(INFO) << "Start Tensor Relation Computing";
  904. count = tensors_list_.back()->GetId() + 1;
  905. for (size_t i = 0; i < count; i++) {
  906. reuse_matrix_.emplace_back(count);
  907. }
  908. if (tensors_list_.size() < kParallelComputeSizeThreshold) {
  909. ComputeMultiTensorConflicts(tensors_list_, tensors_list_, nodes_dependency, &reuse_matrix_);
  910. } else {
  911. MS_LOG(INFO) << "Tensor Num " << tensors_list_.size() << " is larger than " << kParallelComputeSizeThreshold;
  912. MS_LOG(INFO) << "Enter Multi-Thread Mode...";
  913. size_t process_num = common::ThreadPool::GetInstance().GetSyncRunThreadNum();
  914. MS_LOG(INFO) << "Threads Num is " << process_num;
  915. size_t start_index = 0;
  916. size_t total_size = tensors_list_.size();
  917. size_t job_size = total_size / process_num;
  918. if (job_size == 0) {
  919. job_size = total_size;
  920. }
  921. std::vector<common::Task> tasks;
  922. while (start_index < total_size) {
  923. size_t end_index = (start_index + job_size) > total_size ? total_size : start_index + job_size;
  924. auto jobs = std::vector<SomasTensorPtr>(tensors_list_.begin() + start_index, tensors_list_.begin() + end_index);
  925. auto task = [this, jobs, &nodes_dependency]() {
  926. this->ComputeMultiTensorConflicts(jobs, tensors_list_, nodes_dependency, &reuse_matrix_);
  927. return common::SUCCESS;
  928. };
  929. tasks.emplace_back(task);
  930. start_index += job_size;
  931. }
  932. common::ThreadPool::GetInstance().SyncRun(tasks);
  933. }
  934. MS_LOG(INFO) << "End Tensor Relation Computing";
  935. auto end_conflict = std::chrono::system_clock::now();
  936. MS_LOG(INFO) << "End Conflict Computing (Bitset Model)(time taken "
  937. << std::chrono::duration_cast<std::chrono::milliseconds>(end_conflict - start_conflict).count() << "ms)";
  938. }
  939. void Somas::UpdateTensorDestinations() {
  940. // Loop to add edges within each stream (node order within stream)
  941. for (const auto &stream : streams_list_) {
  942. auto &nodes = stream->nodes_;
  943. std::sort(nodes.begin(), nodes.end(), NodeSort);
  944. for (size_t i = 1; i < nodes.size(); i++) {
  945. const auto &previous_node = nodes[i - 1];
  946. const auto &current_node = nodes[i];
  947. current_node->ancestor_nodes_.insert(previous_node);
  948. }
  949. }
  950. // Loop to add edges from end to beginning of next group
  951. for (const auto &group : streams_groups_) {
  952. for (size_t i = 1; i < group.size(); i++) {
  953. int64_t previous_stream = group[i - 1];
  954. int64_t current_stream = group[i];
  955. auto it =
  956. std::find_if(streams_list_.begin(), streams_list_.end(),
  957. [previous_stream](const SomasStreamPtr &stream) { return stream->GetId() == previous_stream; });
  958. if (it == streams_list_.end()) {
  959. continue;
  960. }
  961. auto &last_node_in_prev_stream = (*it)->nodes_.back();
  962. it = std::find_if(streams_list_.begin(), streams_list_.end(),
  963. [current_stream](const SomasStreamPtr &stream) { return stream->GetId() == current_stream; });
  964. if (it == streams_list_.end()) {
  965. continue;
  966. }
  967. auto &first_node_in_cur_stream = (*it)->nodes_.front();
  968. first_node_in_cur_stream->ancestor_nodes_.insert(last_node_in_prev_stream);
  969. }
  970. }
  971. // Loop to avoid tensors with empty destinations (add itself)
  972. for (const auto &tensor : tensors_list_) {
  973. if (tensor->destinations_.size() == 0) {
  974. tensor->destinations_.insert(tensor->GetSourceNode());
  975. }
  976. }
  977. }
  978. void Somas::ComputeMultiTensorConflicts(const std::vector<SomasTensorPtr> &calc_tensors_list,
  979. const std::vector<SomasTensorPtr> &all_tensors_list,
  980. const vector<DynamicBitSet> &nodes_dependency,
  981. std::vector<DynamicBitSet> *tensor_relation) const {
  982. auto start = std::chrono::system_clock::now();
  983. MS_LOG(INFO) << "Start Computing Conflicts Pairs, tensors list size is " << calc_tensors_list.size();
  984. for (size_t i = 0; i < calc_tensors_list.size(); i++) {
  985. auto calc_tensor = calc_tensors_list[i];
  986. if (calc_tensor->IsLifelong() || calc_tensor->IsRefOverlap() || calc_tensor->GetAlignedSize() == 0) {
  987. continue;
  988. }
  989. ComputeOneTensorConflicts(calc_tensor, all_tensors_list, nodes_dependency, tensor_relation);
  990. }
  991. auto end = std::chrono::system_clock::now();
  992. MS_LOG(INFO) << "End Computing Conflicts Pairs (time taken "
  993. << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms)";
  994. }
  995. void Somas::ComputeOneTensorConflicts(const std::shared_ptr<SomasTensor> &calc_tensor,
  996. const std::vector<SomasTensorPtr> &all_tensors_list,
  997. const vector<DynamicBitSet> &nodes_dependency,
  998. std::vector<DynamicBitSet> *tensor_relation) const {
  999. for (size_t j = 0; j < all_tensors_list.size(); j++) {
  1000. auto target_tensor = all_tensors_list[j];
  1001. if (calc_tensor == target_tensor || target_tensor->IsLifelong() || target_tensor->IsRefOverlap() ||
  1002. target_tensor->GetAlignedSize() == 0) {
  1003. continue;
  1004. }
  1005. size_t calc_src_node = calc_tensor->GetSourceNode()->GetId();
  1006. size_t target_src_node = target_tensor->GetSourceNode()->GetId();
  1007. if (calc_src_node == target_src_node) {
  1008. continue;
  1009. }
  1010. if ((*tensor_relation)[calc_tensor->GetId()].IsBitTrue(target_tensor->GetId()) ||
  1011. (*tensor_relation)[target_tensor->GetId()].IsBitTrue(calc_tensor->GetId())) {
  1012. continue;
  1013. }
  1014. bool reuse = true;
  1015. // check calc_tensor's all consumers is target_tensor's source node's dependency or not
  1016. for (const auto &dst_node : calc_tensor->destinations_) {
  1017. if (nodes_dependency[target_src_node].IsBitTrue(dst_node->GetId()) == false) {
  1018. // calc_tensor's consumer is not in target_tensor's source node's dependency, not sure this consumer is done or
  1019. // not when target_tensor produced
  1020. reuse = false;
  1021. break;
  1022. } else if (target_src_node == dst_node->GetId()) {
  1023. // calc_tensor is target_tensor's source node's input, can't reuse
  1024. reuse = false;
  1025. break;
  1026. } else {
  1027. // calc_tensor's consumer is in target_tensor's source node's dependency, this consumer is done when
  1028. // target_tensor produced
  1029. reuse = true;
  1030. }
  1031. }
  1032. if (reuse) {
  1033. // calc_tensor and target_tensor have dependencies so they can reuse each other
  1034. (*tensor_relation)[calc_tensor->GetId()].SetBitTrue(target_tensor->GetId());
  1035. (*tensor_relation)[target_tensor->GetId()].SetBitTrue(calc_tensor->GetId());
  1036. }
  1037. }
  1038. }
  1039. bool Somas::NodeSort(SomasNodePtr node1, SomasNodePtr node2) { return node1->GetId() < node2->GetId(); }
  1040. bool Somas::Assign(const session::KernelGraph *graph) {
  1041. if (tensors_list_.empty()) {
  1042. MS_LOG(INFO) << "No Tensor for Assigner";
  1043. return true;
  1044. }
  1045. // Ref Node Preprocessing
  1046. UpdateRefTensorsConflict();
  1047. std::map<size_t, size_t> contiguous_list_with_ref_index_map = GetContiguousListContainRefTensor();
  1048. vector<vector<size_t>> contiguous_tensors_list_removed_ref = contiguous_tensors_list_;
  1049. std::set<vector<size_t>> contiguous_tensors_list_to_remove;
  1050. for (auto ref_list_pair : contiguous_list_with_ref_index_map) {
  1051. contiguous_tensors_list_to_remove.insert(contiguous_tensors_list_[ref_list_pair.second]);
  1052. }
  1053. for (auto contiguous_list : contiguous_tensors_list_to_remove) {
  1054. auto iterator = std::find(contiguous_tensors_list_removed_ref.begin(), contiguous_tensors_list_removed_ref.end(),
  1055. contiguous_list);
  1056. if (iterator != contiguous_tensors_list_removed_ref.end()) {
  1057. contiguous_tensors_list_removed_ref.erase(iterator);
  1058. } else {
  1059. MS_LOG(WARNING) << "Could not find contiguous list to remove for ref";
  1060. }
  1061. }
  1062. MS_LOG(INFO) << "End Solving Preprocessing for Ref Node";
  1063. UpdateRefOverlapTensorsConflicts();
  1064. #ifdef SOMAS_DEBUG
  1065. // Compute number of constraints for each tensor
  1066. auto tensors_num = tensors_list_.size();
  1067. for (auto tensor1 : tensors_list_) {
  1068. auto ones_num = reuse_matrix_[tensor1->GetId()].CountOnesNum();
  1069. tensor1->num_constraints_ = tensors_num - ones_num;
  1070. }
  1071. #endif
  1072. // Prepare solver info
  1073. MS_LOG(INFO) << "Start Loop to create solver info";
  1074. for (auto tensor : tensors_list_) {
  1075. if (tensor->GetSolverTensorDesc() != nullptr) {
  1076. SomasSolverTensorDescPtr pSolverTensor = tensor->GetSolverTensorDesc();
  1077. solver_tensor_desc_list_.insert(
  1078. std::pair<size_t, SomasSolverTensorDescPtr>(pSolverTensor->index_, pSolverTensor));
  1079. }
  1080. }
  1081. MS_LOG(INFO) << "End Loop to create solver info";
  1082. MS_LOG(INFO) << "Start Solving";
  1083. if (solver_tensor_desc_list_.empty()) {
  1084. MS_LOG(INFO) << "solver_tensor_desc_list is empty.";
  1085. return true;
  1086. }
  1087. somas_solver_ = std::make_shared<SomasSolverPre>();
  1088. auto status = somas_solver_->Solving(graph, &solver_tensor_desc_list_, &reuse_matrix_,
  1089. contiguous_tensors_list_removed_ref, false);
  1090. MS_LOG(INFO) << "End Solving";
  1091. if (status != SUCCESS) {
  1092. GenGraphStatisticInfo();
  1093. MS_LOG(EXCEPTION) << "SOMAS Solving Failed.";
  1094. }
  1095. // Update solver_tensor_desc offset to tensors list
  1096. for (const auto &tensor : tensors_list_) {
  1097. tensor->SetOffset();
  1098. }
  1099. UpdateRefTensorsOffset();
  1100. UpdateContiguousTensorsOffset(contiguous_list_with_ref_index_map);
  1101. // Set mem_offset_ value by solver result
  1102. mem_offset_ = static_cast<size_t>(somas_solver_->GetMaxOffset());
  1103. return true;
  1104. }
  1105. std::map<size_t, size_t> Somas::GetContiguousListContainRefTensor() {
  1106. // key: contiguous list index with ref node input; value: contiguous list index with ref node output
  1107. std::map<size_t, size_t> contiguous_list_with_ref_index_map;
  1108. std::map<size_t, size_t> ref_tensors_in_contiguous_map = GetRefTensorsInContiguousList();
  1109. std::map<size_t, std::map<size_t, std::set<size_t>>> contiguous_ref_list_error_check_map;
  1110. for (auto ref_pair : ref_tensors_in_contiguous_map) {
  1111. size_t ref_first = ref_pair.first;
  1112. size_t ref_second = ref_pair.second;
  1113. bool found_first = false;
  1114. bool found_second = false;
  1115. size_t index_first = 0;
  1116. size_t index_second = 0;
  1117. size_t index_in_list_first = 0;
  1118. size_t index_in_list_second = 0;
  1119. for (size_t index = 0; index < contiguous_tensors_list_.size() && (!found_first || !found_second); index++) {
  1120. if (!found_first) {
  1121. auto iterator_first =
  1122. std::find(contiguous_tensors_list_[index].begin(), contiguous_tensors_list_[index].end(), ref_first);
  1123. if (iterator_first != contiguous_tensors_list_[index].end()) {
  1124. index_first = index;
  1125. index_in_list_first = iterator_first - contiguous_tensors_list_[index].begin();
  1126. found_first = true;
  1127. }
  1128. }
  1129. if (!found_second) {
  1130. auto iterator_second =
  1131. std::find(contiguous_tensors_list_[index].begin(), contiguous_tensors_list_[index].end(), ref_second);
  1132. if (iterator_second != contiguous_tensors_list_[index].end()) {
  1133. index_second = index;
  1134. index_in_list_second = iterator_second - contiguous_tensors_list_[index].begin();
  1135. found_second = true;
  1136. }
  1137. }
  1138. }
  1139. if (!found_first) {
  1140. MS_LOG(WARNING) << "Contiguous ref tensor " << ref_first << " not found in any contiguous list";
  1141. }
  1142. if (!found_second) {
  1143. MS_LOG(WARNING) << "Contiguous ref tensor " << ref_second << " not found in any contiguous list";
  1144. }
  1145. if (contiguous_list_with_ref_index_map.find(index_first) == contiguous_list_with_ref_index_map.end() ||
  1146. contiguous_list_with_ref_index_map[index_first] == index_second) {
  1147. contiguous_list_with_ref_index_map[index_first] = index_second;
  1148. // Checking for error cases
  1149. if (index_in_list_first != index_in_list_second) {
  1150. MS_LOG(WARNING) << "Inconsistency in contiguous ref: tensor " << ref_first << " in position "
  1151. << index_in_list_first << " of contiguous list " << index_first << " and tensor " << ref_second
  1152. << " in position " << index_in_list_second << " of contiguous list " << index_second;
  1153. }
  1154. contiguous_ref_list_error_check_map[index_first][index_second].insert(index_in_list_first);
  1155. } else {
  1156. MS_LOG(WARNING) << "Contiguous list " << index_first << " associated (ref node) with two other contiguous lists: "
  1157. << contiguous_list_with_ref_index_map[index_first] << " and " << index_second;
  1158. }
  1159. }
  1160. for (auto check_list_pair : contiguous_ref_list_error_check_map) {
  1161. auto first_list = check_list_pair.first;
  1162. auto index_set_map = check_list_pair.second;
  1163. for (auto index_set : index_set_map) {
  1164. auto second_list = index_set.first;
  1165. if (contiguous_tensors_list_[first_list].size() != contiguous_tensors_list_[second_list].size()) {
  1166. MS_LOG(WARNING) << "Contiguous lists " << first_list << " and " << second_list
  1167. << " considered in ref do not have the same size";
  1168. }
  1169. for (size_t x = 0; x < contiguous_tensors_list_[second_list].size(); x++) {
  1170. if (contiguous_ref_list_error_check_map[first_list][second_list].count(x) == 0) {
  1171. MS_LOG(WARNING) << "Contiguous lists " << first_list << " and " << second_list
  1172. << " considered in ref: ref pair at in-lists index " << x << " has not been considered";
  1173. }
  1174. }
  1175. }
  1176. }
  1177. return contiguous_list_with_ref_index_map;
  1178. }
  1179. std::map<size_t, size_t> Somas::GetRefTensorsInContiguousList() {
  1180. // key: refnode input value: refnode output
  1181. std::map<size_t, size_t> ref_tensors_in_contiguous_map;
  1182. for (auto ref_node_list : ref_node_constraints_) {
  1183. // Count contiguous tensors in ref list
  1184. size_t contiguous_in_ref_list = std::count_if(ref_node_list.begin(), ref_node_list.end(),
  1185. [this](size_t tid) { return tensors_map_[tid]->contiguous_; });
  1186. // Keep info about contiguous and check for errors
  1187. if (ref_node_list.size() > 2 && contiguous_in_ref_list > 0) {
  1188. MS_LOG(WARNING) << "Ref node of size greater than two with at least one contiguous tensor in";
  1189. }
  1190. if (ref_node_list.size() == 2 && contiguous_in_ref_list == 1) {
  1191. MS_LOG(WARNING) << "Ref node of size two with only one contiguous tensor" << ref_node_list[0] << ":"
  1192. << tensors_map_[ref_node_list[0]]->contiguous_ << ", " << ref_node_list[1] << ":"
  1193. << tensors_map_[ref_node_list[1]]->contiguous_;
  1194. }
  1195. if (ref_node_list.size() == 2 && contiguous_in_ref_list == 2) {
  1196. ref_tensors_in_contiguous_map[ref_node_list[0]] = ref_node_list[1];
  1197. }
  1198. }
  1199. return ref_tensors_in_contiguous_map;
  1200. }
  1201. void Somas::UpdateContiguousTensorsOffset(const std::map<size_t, size_t> &contiguous_ref_list_map) {
  1202. // Handle contiguous ref node
  1203. for (auto ref_list_pair : contiguous_ref_list_map) {
  1204. size_t index_first = ref_list_pair.first;
  1205. size_t index_second = ref_list_pair.second;
  1206. for (size_t x = 0; x < contiguous_tensors_list_[index_second].size(); x++) {
  1207. tensors_map_[contiguous_tensors_list_[index_second][x]]->offset_ =
  1208. tensors_map_[contiguous_tensors_list_[index_first][x]]->offset_;
  1209. }
  1210. }
  1211. // Contiguous gaps postprocessing
  1212. for (auto list : contiguous_tensors_list_) {
  1213. tensors_map_[list[0]]->offset_ += kGapSize;
  1214. }
  1215. }
  1216. void Somas::UpdateRefTensorsOffset() {
  1217. // Ref Node Postprocessing
  1218. MS_LOG(INFO) << "\nStart Solving Postprocessing for Ref Node";
  1219. // Set offset for rest of ref node list (ignored by solver due to ref node preprocessing)
  1220. for (auto ref_node_list : ref_node_constraints_) {
  1221. for (size_t i = 1; i < ref_node_list.size(); ++i) {
  1222. tensors_map_[ref_node_list[i]]->offset_ = tensors_map_[ref_node_list[0]]->offset_;
  1223. }
  1224. }
  1225. }
  1226. void Somas::UpdateRefOverlapTensorsConflicts() {
  1227. // Ref Overlap Preprocessing
  1228. MS_LOG(INFO) << "Start Solving Preprocessing for Ref Overlap";
  1229. // In ConflictComputing(), by use of ref_overlap_ flag, each tensor in a ref_overlap_list has all entries 1 in
  1230. // cannot_reuse_ array Here, we allow reuse only among tensors in same list
  1231. for (auto ref_overlap_list : ref_overlap_constraints_) {
  1232. for (size_t tid_1 : ref_overlap_list) {
  1233. for (size_t tid_2 : ref_overlap_list) {
  1234. reuse_matrix_[tid_1].SetBitTrue(tid_2);
  1235. reuse_matrix_[tid_2].SetBitTrue(tid_1);
  1236. }
  1237. }
  1238. }
  1239. MS_LOG(INFO) << "End Solving Preprocessing for Ref Overlap";
  1240. }
  1241. void Somas::UpdateRefTensorsConflict() {
  1242. // Keep all constraints for first tensor in list
  1243. for (auto ref_node_list : ref_node_constraints_) {
  1244. size_t tid_0 = ref_node_list[0];
  1245. for (SomasTensorPtr tensor : tensors_list_) {
  1246. if (reuse_matrix_[tid_0].IsBitTrue(tensor->GetId()) == false) {
  1247. continue;
  1248. }
  1249. for (size_t tid : ref_node_list) {
  1250. if (reuse_matrix_[tid].IsBitTrue(tensor->GetId()) == false) {
  1251. reuse_matrix_[tid_0].SetBitFalse(tensor->GetId());
  1252. reuse_matrix_[tensor->GetId()].SetBitFalse(tid_0);
  1253. break;
  1254. }
  1255. }
  1256. }
  1257. // Set rest to size 0, so that solver ignores them (if not contiguous)
  1258. for (size_t i = 1; i < ref_node_list.size(); ++i) {
  1259. if (!tensors_map_[ref_node_list[i]]->contiguous_) {
  1260. tensors_map_[ref_node_list[i]]->aligned_size_ = 0;
  1261. }
  1262. }
  1263. }
  1264. }
  1265. std::string Somas::GetSplitName(const std::string &scope_name) const {
  1266. auto indx = scope_name.rfind('/');
  1267. if (indx == std::string::npos) {
  1268. return scope_name;
  1269. } else {
  1270. if (indx < scope_name.size() - 1) {
  1271. auto split_name = scope_name.substr(indx + 1);
  1272. return split_name;
  1273. }
  1274. return scope_name;
  1275. }
  1276. }
  1277. std::string Somas::SomasInfo(bool calc_hash) {
  1278. std::ostringstream oss;
  1279. if (!calc_hash) {
  1280. DumpParameters(oss);
  1281. }
  1282. DumpTensors(oss);
  1283. DumpNodes(oss);
  1284. oss << "\n\nAll Stream Groups:\n\n";
  1285. for (const auto &stream_group : streams_groups_) {
  1286. for (const auto &stream : stream_group) {
  1287. oss << "stm" << stream << " ";
  1288. }
  1289. oss << "\n";
  1290. }
  1291. if (!ref_node_constraints_.empty()) {
  1292. oss << "\n\nAll Ref Node Info:\n\n";
  1293. for (const auto &ref_in_out : ref_node_constraints_) {
  1294. oss << "refnode input-output:";
  1295. for (const auto &item : ref_in_out) {
  1296. oss << "%" << item << "T ";
  1297. }
  1298. oss << "\n";
  1299. }
  1300. }
  1301. return oss.str();
  1302. }
  1303. void Somas::DumpNodes(std::ostringstream &oss) const {
  1304. oss << "\n\nAll Nodes:\n\n";
  1305. for (const auto &node : nodes_list_) {
  1306. auto scope_name = node->scope_full_name_;
  1307. std::string split_name = GetSplitName(scope_name);
  1308. oss << "$" << node->GetId() << "\t" << split_name << "\t" << static_cast<int>(node->GetType()) << "\t";
  1309. auto input_num = node->input_tensors_.size() + node->input_parameters_map_.size();
  1310. oss << "inputs[";
  1311. size_t tensor_index = 0;
  1312. for (size_t input_index = 0; input_index < input_num; input_index++) {
  1313. auto iter = node->input_parameters_map_.find(input_index);
  1314. if (iter != node->input_parameters_map_.end()) {
  1315. oss << "%" << iter->second->id_ << "P"
  1316. << ", ";
  1317. } else {
  1318. oss << "%" << node->input_tensors_[tensor_index]->GetId() << "T"
  1319. << ", ";
  1320. tensor_index++;
  1321. }
  1322. }
  1323. oss << "]";
  1324. oss << "\toutputs[";
  1325. for (const auto &out : node->output_tensors_) {
  1326. oss << "%" << out->GetId() << "T"
  1327. << ", ";
  1328. }
  1329. oss << "]";
  1330. oss << "\tworkspace[";
  1331. for (const auto &wk : node->workspace_tensors_) {
  1332. oss << "%" << wk->GetId() << "T"
  1333. << ", ";
  1334. }
  1335. oss << "]";
  1336. oss << "\tstreamID["
  1337. << "@" << node->GetStream()->GetId() << "]\n";
  1338. }
  1339. }
  1340. void Somas::DumpTensors(std::ostringstream &oss) const {
  1341. oss << "\n\nAll Tensors:\n\n";
  1342. oss << "index:"
  1343. << "\tsize:"
  1344. << "\treal_size:"
  1345. << "\toffset:"
  1346. << "\taddr:"
  1347. << "\ttype:"
  1348. << "\tlifelong:"
  1349. << "\tlife_start:"
  1350. << "\tlife_end:"
  1351. << "\tsource node name:\n";
  1352. for (const auto &tensor : tensors_list_) {
  1353. auto scope_name = tensor->GetSourceNode()->scope_full_name_;
  1354. std::string split_name = GetSplitName(scope_name);
  1355. oss << "%" << tensor->GetId() << "T"
  1356. << "\t"
  1357. << "#" << tensor->GetAlignedSize() << "S"
  1358. << "\t"
  1359. << "#" << tensor->GetOriginalSize() << "S"
  1360. << "\t"
  1361. << "&" << tensor->GetOffset() << ""
  1362. << "\t"
  1363. << "&" << static_cast<void *>(tensor->GetOffset() + mem_base_addr_) << "\t"
  1364. << tensor_type_name_map[tensor->type_] << "\t" << tensor->IsLifelong() << "\t" << tensor->lifetime_.start_
  1365. << "\t" << tensor->lifetime_.end_ << "\t" << split_name << "\n";
  1366. }
  1367. }
  1368. void Somas::DumpParameters(std::ostringstream &oss) const {
  1369. oss << "All Parameters:\n\n";
  1370. oss << "index:"
  1371. << "\tsize:"
  1372. << "\tstart_addr:"
  1373. << "\tsource node name:"
  1374. << "\tnode out index:\n";
  1375. for (const auto &param : parameters_list_) {
  1376. oss << "%" << param->id_ << "P"
  1377. << "\t"
  1378. << "#" << param->size_ << "S"
  1379. << "\t"
  1380. << "&" << param->addr_ << "\t" << param->source_node_->fullname_with_scope() << "\t" << param->output_index_
  1381. << "\n";
  1382. }
  1383. }
  1384. void Somas::DumpSomasInfoIR(const string filename) {
  1385. if (filename.size() > PATH_MAX) {
  1386. MS_LOG(ERROR) << "File path " << filename << " is too long.";
  1387. return;
  1388. }
  1389. auto real_path = Common::GetRealPath(filename);
  1390. if (!real_path.has_value()) {
  1391. MS_LOG(ERROR) << "Get real path failed. path=" << filename;
  1392. return;
  1393. }
  1394. ChangeFileMode(real_path.value(), S_IRWXU);
  1395. std::ofstream ofs(real_path.value());
  1396. if (!ofs.is_open()) {
  1397. MS_LOG(ERROR) << "Open dump file '" << real_path.value() << "' failed!";
  1398. return;
  1399. }
  1400. ofs << SomasInfo();
  1401. ofs.close();
  1402. }
  1403. std::string Somas::Offline() {
  1404. std::ostringstream oss;
  1405. for (auto tensor : tensors_list_) {
  1406. if (tensor->IsOutputOnly() || tensor->type_ == TensorType::kRefNodeOutput) {
  1407. oss << "Somas EDGE ERROR src=n" << tensor->GetSourceNode()->GetId()
  1408. << ", srcstm=" << tensor->GetSourceStream()->GetId() << ", dst=nc"
  1409. << ", dststm=nc"
  1410. << ", workspace=0, size=" << tensor->GetOriginalSize()
  1411. << ", lifelong=" << static_cast<int>(tensor->lifelong_value_) << ", tid=" << tensor->GetId()
  1412. << ", start=" << tensor->lifetime_.start_ << ", end=" << tensor->lifetime_.end_ << std::endl;
  1413. } else {
  1414. std::map<size_t, size_t> dest_infos;
  1415. for (SomasNodePtr dest_node : tensor->destinations_) {
  1416. dest_infos.insert(std::make_pair(dest_node->GetId(), dest_node->GetStream()->GetId()));
  1417. }
  1418. for (auto dest_info : dest_infos) {
  1419. oss << "Somas EDGE src=n" << tensor->GetSourceNode()->GetId()
  1420. << ", srcstm=" << tensor->GetSourceStream()->GetId() << ", dst=n" << dest_info.first
  1421. << ", dststm=" << dest_info.second << ", workspace=" << static_cast<int>(tensor->type_ == kWorkspace)
  1422. << ", size=" << tensor->GetOriginalSize() << ", lifelong=" << static_cast<int>(tensor->lifelong_value_)
  1423. << ", tid=" << tensor->GetId() << ", start=" << tensor->lifetime_.start_
  1424. << ", end=" << tensor->lifetime_.end_ << std::endl;
  1425. }
  1426. }
  1427. }
  1428. for (vector<size_t> tList : contiguous_tensors_list_) {
  1429. oss << "Somas CONTIGUOUS";
  1430. for (size_t tid : tList) {
  1431. oss << " " << tid;
  1432. }
  1433. oss << std::endl;
  1434. }
  1435. for (const auto &group : streams_groups_) {
  1436. oss << "Somas GROUP";
  1437. for (int64_t sid : group) {
  1438. oss << " " << sid;
  1439. }
  1440. oss << std::endl;
  1441. }
  1442. return oss.str();
  1443. }
  1444. void Somas::DumpOfflineIR(const string filename) {
  1445. MS_LOG(INFO) << "Printing somas-log-from-graph log: " << filename;
  1446. if (filename.size() > PATH_MAX) {
  1447. MS_LOG(ERROR) << "File path " << filename << " is too long.";
  1448. return;
  1449. }
  1450. auto real_path = Common::GetRealPath(filename);
  1451. if (!real_path.has_value()) {
  1452. MS_LOG(ERROR) << "Get real path failed. path=" << filename;
  1453. return;
  1454. }
  1455. ChangeFileMode(real_path.value(), S_IRWXU);
  1456. std::ofstream ofs(real_path.value());
  1457. if (!ofs.is_open()) {
  1458. MS_LOG(ERROR) << "Open dump file '" << real_path.value() << "' failed!";
  1459. return;
  1460. }
  1461. ofs << Offline();
  1462. ofs.close();
  1463. }
  1464. std::string Somas::SomasMemory() {
  1465. std::ostringstream oss;
  1466. std::map<size_t, size_t> mem_map;
  1467. for (auto tensor : tensors_list_) {
  1468. mem_map[tensor->GetOffset()] = 0;
  1469. }
  1470. size_t num = 0;
  1471. for (auto iter = mem_map.begin(); iter != mem_map.end(); ++iter, ++num) {
  1472. iter->second = num;
  1473. }
  1474. std::map<size_t, std::map<size_t, SomasTensorPtr>> mem_list;
  1475. for (const auto &tensor : tensors_list_) {
  1476. size_t key = tensor->offset_;
  1477. auto iter = mem_list.find(key);
  1478. if (iter == mem_list.end()) {
  1479. std::map<size_t, SomasTensorPtr> id_tensor_map;
  1480. id_tensor_map[tensor->GetId()] = tensor;
  1481. mem_list[key] = id_tensor_map;
  1482. } else {
  1483. iter->second[tensor->GetId()] = tensor;
  1484. }
  1485. }
  1486. oss << "mem_id:"
  1487. << "\tstart_offset:"
  1488. << "\tend_offset:"
  1489. << "\ttensor_id:"
  1490. << "\torigin_size:"
  1491. << "\talign_size:"
  1492. << "\tstart_addr:"
  1493. << "\tend_addr:"
  1494. << "\ttype:"
  1495. << "\tsrc_node:"
  1496. << "\tsrc_stm_id:"
  1497. << "lifetime_start\t"
  1498. << "lifetime_end\n";
  1499. for (const auto &mem : mem_list) {
  1500. auto id_tensor_map = mem.second;
  1501. for (const auto &id_tensor : id_tensor_map) {
  1502. auto tensor = id_tensor.second;
  1503. std::string scope_name;
  1504. size_t src_stm_id = 0xffff;
  1505. if (tensor->GetSourceNode() != nullptr) {
  1506. scope_name = tensor->GetSourceNode()->scope_full_name_;
  1507. src_stm_id = tensor->GetSourceNode()->GetStream()->GetId();
  1508. } else {
  1509. scope_name = "Somas Tensor";
  1510. }
  1511. std::string split_name = GetSplitName(scope_name);
  1512. oss << "#" << mem_map[tensor->GetOffset()] << "\t" << tensor->GetOffset() << "\t"
  1513. << tensor->GetOffset() + tensor->GetAlignedSize() << "\t%" << tensor->GetId() << "T\t"
  1514. << tensor->GetOriginalSize() << "\t" << tensor->GetAlignedSize() << "\t&"
  1515. << static_cast<void *>(tensor->GetOffset() + mem_base_addr_) << "\t&"
  1516. << static_cast<void *>(tensor->GetOffset() + mem_base_addr_ + tensor->GetAlignedSize()) << "\t"
  1517. << tensor_type_name_map[tensor->type_] << "\t" << split_name << "\tstm" << src_stm_id << "\t"
  1518. << tensor->lifetime_.start_ << "\t" << tensor->lifetime_.end_ << "\n";
  1519. }
  1520. }
  1521. return oss.str();
  1522. }
  1523. void Somas::DumpSomasMemoryIR(const string filename) {
  1524. if (filename.size() > PATH_MAX) {
  1525. MS_LOG(ERROR) << "File path " << filename << " is too long.";
  1526. return;
  1527. }
  1528. auto real_path = Common::GetRealPath(filename);
  1529. if (!real_path.has_value()) {
  1530. MS_LOG(ERROR) << "Get real path failed. path=" << filename;
  1531. return;
  1532. }
  1533. ChangeFileMode(real_path.value(), S_IRWXU);
  1534. std::ofstream ofs(real_path.value());
  1535. if (!ofs.is_open()) {
  1536. MS_LOG(ERROR) << "Open dump file '" << real_path.value() << "' failed!";
  1537. return;
  1538. }
  1539. ofs << SomasMemory();
  1540. ofs.close();
  1541. }
  1542. size_t Somas::CalcLowerBound() const {
  1543. size_t max_node_id = std::accumulate(tensors_list_.begin(), tensors_list_.end(), 0, [](size_t max_id, auto tensor) {
  1544. return std::max(max_id, tensor->lifetime_.end_);
  1545. });
  1546. std::map<size_t, size_t> lifetime_lb;
  1547. for (size_t time = 0; time <= max_node_id; time++) {
  1548. lifetime_lb[time] = 0;
  1549. }
  1550. size_t lower, upper;
  1551. for (auto tensor : tensors_list_) {
  1552. if (tensor->lifelong_value_ == kLifeLongGraphAll) {
  1553. lower = 0;
  1554. upper = max_node_id;
  1555. } else {
  1556. lower = tensor->lifetime_.start_;
  1557. upper = tensor->lifetime_.end_;
  1558. }
  1559. for (size_t time = lower; time <= upper; time++) {
  1560. lifetime_lb[time] += tensor->GetAlignedSize();
  1561. }
  1562. }
  1563. size_t max_lifetime = 0;
  1564. for (size_t time = 0; time <= max_node_id; time++) {
  1565. if (max_lifetime < lifetime_lb[time]) {
  1566. max_lifetime = lifetime_lb[time];
  1567. }
  1568. }
  1569. return max_lifetime;
  1570. }
  1571. void Somas::GenGraphStatisticInfo() {
  1572. lower_bound_ = CalcLowerBound();
  1573. for (const auto &tensor : tensors_list_) {
  1574. upper_bound_ += tensor->aligned_size_;
  1575. if (tensor->type_ == kWorkspace) {
  1576. workspace_total_size_ += tensor->aligned_size_;
  1577. }
  1578. if (tensor->lifelong_value_ == kLifeLongGraphAll) {
  1579. lifelong_all_total_size_ += tensor->aligned_size_;
  1580. } else if (tensor->lifelong_value_ == kLifeLongGraphStart) {
  1581. lifelong_start_total_size_ += tensor->aligned_size_;
  1582. } else if (tensor->lifelong_value_ == kLifeLongGraphEnd) {
  1583. lifelong_end_total_size_ += tensor->aligned_size_;
  1584. }
  1585. }
  1586. const double giga = 1024. * 1024. * 1024.;
  1587. MS_LOG(INFO) << "Lower Bound: " << lower_bound_ << " (" << lower_bound_ / giga
  1588. << " GB), Upper Bound: " << upper_bound_ << " (" << upper_bound_ / giga << " GB)";
  1589. MS_LOG(INFO) << "\nTotal Dynamic Size (Upper Bound):\t" << upper_bound_ << "\n"
  1590. << "Theoretical Optimal Size (Lower Bound):\t" << lower_bound_ << "\n"
  1591. << "Total Workspace Size:\t" << workspace_total_size_ << "\n"
  1592. << "Total Communication Input Tensor Size:\t" << comm_input_total_size_ << "\n"
  1593. << "Total Communication Output Tensor Size:\t" << comm_output_total_size_ << "\n"
  1594. << "Total LifeLong All Tensor Size:\t" << lifelong_all_total_size_ << "\n"
  1595. << "Total LifeLong Start Tensor Size:\t" << lifelong_start_total_size_ << "\n"
  1596. << "Total LifeLong End Tensor Size:\t" << lifelong_end_total_size_ << "\n"
  1597. << "Reused Size(Allocate Size):\t" << GetTotalMemSize() << "\n\n\n";
  1598. }
  1599. uint8_t *Somas::GetNodeOutputPtr(const AnfNodePtr &node, size_t index) const {
  1600. auto key = node.get();
  1601. auto iter = nodes_map_.find(key);
  1602. uint8_t *ptr = nullptr;
  1603. if (iter != nodes_map_.end()) {
  1604. if (index >= iter->second->output_tensors_.size()) {
  1605. MS_LOG(EXCEPTION) << "index:[" << index << "] is larger than it's workspace size:["
  1606. << iter->second->output_tensors_.size() << "]";
  1607. }
  1608. auto output_tensor = iter->second->output_tensors_[index];
  1609. ptr = mem_base_addr_ + output_tensor->offset_;
  1610. } else {
  1611. MS_LOG(EXCEPTION) << "node [" << AnfAlgo::GetCNodeName(node) << "] don't exist in nodes_map";
  1612. }
  1613. return ptr;
  1614. }
  1615. uint8_t *Somas::GetNodeWorkSpacePtr(const AnfNodePtr &node, size_t index) const {
  1616. auto key = node.get();
  1617. auto iter = nodes_map_.find(key);
  1618. uint8_t *ptr = nullptr;
  1619. if (iter != nodes_map_.end()) {
  1620. if (index >= iter->second->workspace_tensors_.size()) {
  1621. MS_LOG(EXCEPTION) << "index:[" << index << "] is larger than it's workspace size:["
  1622. << iter->second->workspace_tensors_.size() << "]";
  1623. }
  1624. auto workspace_tensor = iter->second->workspace_tensors_[index];
  1625. ptr = mem_base_addr_ + workspace_tensor->offset_;
  1626. }
  1627. return ptr;
  1628. }
  1629. void Somas::ConvertToProfilingNode(uint32_t graph_id) {
  1630. #ifdef ENABLE_D
  1631. auto graph_node = MemoryProfiling::GetInstance().GetGraphMemoryNode(graph_id);
  1632. if (graph_node == nullptr) {
  1633. graph_node = MemoryProfiling::GetInstance().AddGraphMemoryNode(graph_id);
  1634. MS_LOG(INFO) << "Add graph memory node for dynamic memory profiling, graph id is " << graph_id;
  1635. }
  1636. for (const auto &tensor : tensors_list_) {
  1637. TensorMemory tensor_memory;
  1638. tensor_memory.SetTensorId(tensor->GetId());
  1639. tensor_memory.SetAlignedSize(tensor->GetAlignedSize());
  1640. tensor_memory.SetType(tensor_type_name_map[tensor->type_]);
  1641. tensor_memory.SetLifeStart(tensor->lifetime_.start_);
  1642. tensor_memory.SetLifeEnd(tensor->lifetime_.end_);
  1643. tensor_memory.SetLifeLong(life_long_name_map[tensor->lifelong_value_]);
  1644. graph_node->AddTensorMemory(tensor_memory);
  1645. }
  1646. for (const auto &node : nodes_list_) {
  1647. NodeMemory node_memory;
  1648. std::string name = GetSplitName(node->scope_full_name_);
  1649. node_memory.SetNodeName(name);
  1650. node_memory.SetNodeId(node->GetId());
  1651. for (const auto &tensor : node->input_tensors_) {
  1652. node_memory.AddInputTensorId(tensor->GetId());
  1653. }
  1654. for (const auto &tensor : node->output_tensors_) {
  1655. node_memory.AddOutputTensorId(tensor->GetId());
  1656. }
  1657. for (const auto &tensor : node->workspace_tensors_) {
  1658. node_memory.AddWorkSpaceTensorId(tensor->GetId());
  1659. }
  1660. graph_node->AddNodeMemory(node_memory);
  1661. }
  1662. #endif
  1663. }
  1664. } // namespace somas
  1665. } // namespace mindspore