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.

mem_rw_conflict_optimize.cc 31 kB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. /**
  2. * Copyright 2020 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 <string>
  14. #include <vector>
  15. #include "common/ge/ge_util.h"
  16. #include "graph/common/omg_util.h"
  17. #include "graph/debug/ge_attr_define.h"
  18. #include "graph/optimize/graph_optimize.h"
  19. #include "graph/utils/graph_utils.h"
  20. #include "graph/utils/node_utils.h"
  21. namespace {
  22. using namespace ge;
  23. const int kIdentityAnchorIndex = 0;
  24. // rw type of input.
  25. enum class InputRWType {
  26. kReadOnly, // Normal op input only read
  27. kWriteable, // Op like Assign/ApplyMomentum
  28. kScopeWriteable, // Op like hcom_allreduce, it will modify input ,but not expect take effect on pre ouput
  29. kInvalidRWType
  30. };
  31. // rw type of output
  32. enum class OutputRWType {
  33. kReadOnly, // 1.const output 2.not ref output but has several peer output
  34. kSoftRead, // not ref output but only has one output node
  35. kWriteable, // ref output. Like Assign/ApplyMomentum
  36. kInvalidRWType
  37. };
  38. // input and output rw_type of one node. key is anchor_idx, value is rw_type
  39. struct NodeInputOutputRWType {
  40. map<uint32_t, InputRWType> input_rw_type_map;
  41. map<uint32_t, OutputRWType> output_rw_type_map;
  42. };
  43. // input and output rw_type of node in current graph
  44. thread_local map<string, NodeInputOutputRWType> node_rwtype_map_;
  45. ///
  46. /// @brief Convert input rw_type enum to string. For log print.
  47. /// @param rw_type
  48. /// @return rw_type_name
  49. ///
  50. static std::string InputRWTypeToSerialString(InputRWType rw_type) {
  51. const static char *names[4] = {"ReadOnly", "Writeable", "ScopeWriteable", "InvalidRWType"};
  52. return names[static_cast<int>(rw_type)];
  53. }
  54. ///
  55. /// @brief Convert output rw_type enum to string. For log print.
  56. /// @param rw_type
  57. /// @return rw_type_name
  58. ///
  59. static std::string OutputRWTypeToSerialString(OutputRWType rw_type) {
  60. const static char *names[4] = {"ReadOnly", "SoftRead", "Writeable", "InvalidRWType"};
  61. return names[static_cast<int>(rw_type)];
  62. }
  63. OutputRWType GetSingleNodeOutputRWTypeByIndex(const Node &node, uint32_t index) {
  64. auto op_desc = node.GetOpDesc();
  65. if (op_desc == nullptr) {
  66. return OutputRWType::kInvalidRWType;
  67. }
  68. if (op_desc->GetType() == VARIABLE) {
  69. return OutputRWType::kWriteable;
  70. }
  71. // check if it is ref output
  72. auto input_names = op_desc->GetAllInputName();
  73. for (auto &input_name_2_idx : input_names) {
  74. if (op_desc->GetOutputNameByIndex(index) == input_name_2_idx.first) {
  75. return OutputRWType::kWriteable;
  76. }
  77. }
  78. // check if it is ref switch
  79. std::string type;
  80. if ((node.GetType() == FRAMEWORK_OP_TYPE) && AttrUtils::GetStr(op_desc, ATTR_NAME_FRAMEWORK_ORIGINAL_TYPE, type)
  81. && (type == REFSWITCH)) {
  82. return OutputRWType::kWriteable;
  83. }
  84. if (op_desc->GetType() == CONSTANT || op_desc->GetType() == CONSTANTOP) {
  85. return OutputRWType::kReadOnly;
  86. }
  87. auto out_data_anchor = node.GetOutDataAnchor(index);
  88. if (out_data_anchor == nullptr) {
  89. return OutputRWType::kInvalidRWType;
  90. }
  91. if (out_data_anchor->GetPeerInDataNodesSize() > 1) {
  92. return OutputRWType::kReadOnly;
  93. } else {
  94. return OutputRWType::kSoftRead;
  95. }
  96. }
  97. ///
  98. /// @brief Get input rw_type of one node with sub graph. It will return rw_type after solve conflict scene.
  99. /// @param rw_type_set
  100. /// @return
  101. ///
  102. InputRWType GetInputRwTypeInConflict(const std::set<int> &rw_type_set) {
  103. // for input rw type calc
  104. int total_rw_type = 0;
  105. for (const auto rw : rw_type_set) {
  106. total_rw_type += rw;
  107. }
  108. switch (total_rw_type) {
  109. case 0:
  110. return InputRWType::kReadOnly; // all input rw type is readonly
  111. case 2:
  112. return InputRWType::kScopeWriteable; // readonly 2 scope_writeable
  113. case 3:
  114. return InputRWType::kWriteable; // all input rw type is writeable or readonly 2 writeable
  115. case 5:
  116. return InputRWType::kInvalidRWType; // writeable 2 scope_writeable
  117. default:
  118. return InputRWType::kInvalidRWType;
  119. }
  120. }
  121. NodePtr CreateIdentityAfterSrcNode(const Node &src_node, int out_anchor_idx) {
  122. if (src_node.GetOpDesc() == nullptr) {
  123. return nullptr;
  124. }
  125. static std::atomic_long identity_num(0);
  126. auto next_num = identity_num.fetch_add(1);
  127. // 1. create new identity op desc
  128. string identity_name = src_node.GetName() + "_" + IDENTITY + std::to_string(next_num);
  129. auto identity_opdesc = MakeShared<OpDesc>(identity_name, IDENTITY);
  130. if (identity_opdesc == nullptr) {
  131. GELOGE(OUT_OF_MEMORY, "Failed to insert identity node, name %s", identity_name.c_str());
  132. return nullptr;
  133. }
  134. auto data_desc = src_node.GetOpDesc()->GetOutputDesc(out_anchor_idx);
  135. // 2. add input_desc & output_desc for new identity
  136. Status ret = identity_opdesc->AddInputDesc("x", data_desc);
  137. if (ret != SUCCESS) {
  138. GELOGE(ret, "Add Input desc failed for new identity %s.", identity_name.c_str());
  139. return nullptr;
  140. }
  141. ret = identity_opdesc->AddOutputDesc("y", data_desc);
  142. if (ret != SUCCESS) {
  143. GELOGE(ret, "Add Output desc failed for new Identity %s.", identity_name.c_str());
  144. return nullptr;
  145. }
  146. GELOGI("Insert new Identity node %s.", identity_name.c_str());
  147. auto graph = src_node.GetOwnerComputeGraph();
  148. if (graph == nullptr) {
  149. GELOGE(GRAPH_PARAM_INVALID, "Node %s owner compute graph is null.", src_node.GetName().c_str());
  150. return nullptr;
  151. }
  152. return graph->AddNode(identity_opdesc);
  153. }
  154. OutputRWType GetOutputRWTypeByIndex(const Node &node, uint32_t index) {
  155. auto op_desc = node.GetOpDesc();
  156. if (op_desc == nullptr) {
  157. return OutputRWType::kInvalidRWType;
  158. }
  159. if (op_desc->GetType() == WHILE) {
  160. return OutputRWType::kSoftRead;
  161. }
  162. vector<string> subgraph_names = op_desc->GetSubgraphInstanceNames();
  163. if (subgraph_names.empty()) {
  164. // single node without sub graph
  165. return GetSingleNodeOutputRWTypeByIndex(node, index);
  166. } else {
  167. // node with sub graph
  168. auto output_node_vec = NodeUtils::GetSubgraphOutputNodes(node);
  169. auto output_rw_type = OutputRWType::kInvalidRWType;
  170. if (output_node_vec.size() == 1) {
  171. // find rw type from map.
  172. auto iter = node_rwtype_map_.find(output_node_vec.at(0)->GetName());
  173. if (iter == node_rwtype_map_.end()) {
  174. GELOGW("Can not find rw type of node %s from map.It could take some effect on following preprocess.",
  175. output_node_vec.at(0)->GetName().c_str());
  176. return OutputRWType::kInvalidRWType;
  177. }
  178. auto index_2_output_rw_type = iter->second.output_rw_type_map.find(index);
  179. if (index_2_output_rw_type == iter->second.output_rw_type_map.end()) {
  180. GELOGW("Can not find rw type of node %s from map.It could take some effect on following preprocess.",
  181. output_node_vec.at(0)->GetName().c_str());
  182. return OutputRWType::kInvalidRWType;
  183. }
  184. output_rw_type = index_2_output_rw_type->second;
  185. } else {
  186. output_rw_type = OutputRWType::kSoftRead;
  187. }
  188. // check peer input
  189. auto out_data_anchor = node.GetOutDataAnchor(index);
  190. if (out_data_anchor == nullptr) {
  191. return OutputRWType::kInvalidRWType;
  192. }
  193. if (out_data_anchor->GetPeerInDataNodesSize() > 1) {
  194. return OutputRWType::kReadOnly;
  195. } else {
  196. return output_rw_type;
  197. }
  198. }
  199. }
  200. InputRWType GetSingleNodeInputRWTypeByIndex(const Node &node, uint32_t index) {
  201. auto op_desc = node.GetOpDesc();
  202. if (op_desc == nullptr) {
  203. return InputRWType::kInvalidRWType;
  204. }
  205. if (op_desc->GetType() == HCOMALLREDUCE || op_desc->GetType() == HCOMALLGATHER
  206. || op_desc->GetType() == HCOMREDUCESCATTER) {
  207. return InputRWType::kScopeWriteable;
  208. }
  209. // check if it is ref input
  210. auto output_names = op_desc->GetAllOutputName();
  211. for (auto &output_name_2_idx : output_names) {
  212. if (op_desc->GetInputNameByIndex(index) == output_name_2_idx.first) {
  213. return InputRWType::kWriteable;
  214. }
  215. }
  216. // check if it is ref switch
  217. std::string type;
  218. if ((node.GetType() == FRAMEWORK_OP_TYPE) && (AttrUtils::GetStr(op_desc, ATTR_NAME_FRAMEWORK_ORIGINAL_TYPE, type))
  219. && (type == REFSWITCH) && (index == 0)) {
  220. return InputRWType::kWriteable;
  221. }
  222. return InputRWType::kReadOnly;
  223. }
  224. InputRWType GetInputRWTypeByIndex(const Node &node, uint32_t index) {
  225. auto op_desc = node.GetOpDesc();
  226. if (op_desc == nullptr) {
  227. return InputRWType::kInvalidRWType;
  228. }
  229. if (op_desc->GetType() == WHILE) {
  230. return InputRWType::kScopeWriteable;
  231. }
  232. vector<string> subgraph_names = op_desc->GetSubgraphInstanceNames();
  233. if (subgraph_names.empty()) {
  234. // single node without sub graph
  235. return GetSingleNodeInputRWTypeByIndex(node, index);
  236. } else {
  237. // node with sub graph
  238. std::set<int> node_rw_type_set;
  239. auto data_node_vec = NodeUtils::GetSubgraphDataNodesByIndex(node, index);
  240. // get all input data node in subgraph
  241. std::set<int> anchor_rw_type_set;
  242. for (const auto &data_node : data_node_vec) {
  243. // Data only has 1 out data anchor. Here just take first out data anchor. And index 0 is valid.
  244. auto out_data_anchor = data_node->GetOutDataAnchor(0);
  245. if (out_data_anchor == nullptr) {
  246. continue;
  247. }
  248. auto data_op_desc = data_node->GetOpDesc();
  249. if (data_op_desc == nullptr) {
  250. continue;
  251. }
  252. // find rw type from map.
  253. auto iter = node_rwtype_map_.find(data_op_desc->GetName());
  254. if (iter == node_rwtype_map_.end()) {
  255. GELOGW("Can not find rw type of node %s from map.It could take some effect on following preprocess.",
  256. data_op_desc->GetName().c_str());
  257. return InputRWType::kInvalidRWType;
  258. }
  259. auto input_rw_type = iter->second.input_rw_type_map.find(out_data_anchor->GetIdx());
  260. if (input_rw_type == iter->second.input_rw_type_map.end()) {
  261. GELOGW("Can not find rw type of node %s from map.It could take some effect on following preprocess.",
  262. data_op_desc->GetName().c_str());
  263. return InputRWType::kInvalidRWType;
  264. }
  265. anchor_rw_type_set.emplace(static_cast<int>(input_rw_type->second));
  266. }
  267. return GetInputRwTypeInConflict(anchor_rw_type_set);
  268. }
  269. }
  270. Status MarkRWTypeForSubgraph(const ComputeGraphPtr &sub_graph) {
  271. for (const auto &node : sub_graph->GetDirectNode()) {
  272. GE_CHECK_NOTNULL(node);
  273. GE_CHECK_NOTNULL(node->GetOpDesc());
  274. std::set<int> anchor_rw_type_set;
  275. if (node->GetType() == DATA) {
  276. // calc all input_rw_type of peer output , as input_rw_type of DATA. Index 0 is valid.
  277. auto anchor_2_node_vec = NodeUtils::GetOutDataNodesWithAnchorByIndex(*node, 0);
  278. for (const auto anchor_2_node_pair : anchor_2_node_vec) {
  279. auto input_rw_type = GetInputRWTypeByIndex(*anchor_2_node_pair.second, anchor_2_node_pair.first->GetIdx());
  280. GELOGD("Input rw type of Node %s %dth input anchor is %s", anchor_2_node_pair.second->GetName().c_str(),
  281. anchor_2_node_pair.first->GetIdx(), InputRWTypeToSerialString(input_rw_type).c_str());
  282. anchor_rw_type_set.emplace(static_cast<int>(input_rw_type));
  283. }
  284. auto anchor_rw_type = GetInputRwTypeInConflict(anchor_rw_type_set);
  285. GELOGD("Input rw type of Node %s is %s", node->GetName().c_str(),
  286. InputRWTypeToSerialString(anchor_rw_type).c_str());
  287. map<uint32_t, InputRWType> input_rw_type_map{std::make_pair(0, anchor_rw_type)};
  288. NodeInputOutputRWType data_rw_type{input_rw_type_map};
  289. node_rwtype_map_.emplace(std::make_pair(node->GetName(), data_rw_type));
  290. }
  291. if (node->GetType() == NETOUTPUT) {
  292. // calc all output_rw_type of peer input , as output_rw_type of DATA
  293. map<uint32_t, OutputRWType> output_rw_type_map;
  294. for (const auto &in_data_anchor : node->GetAllInDataAnchors()) {
  295. GE_CHECK_NOTNULL(in_data_anchor);
  296. auto pre_out_anchor = in_data_anchor->GetPeerOutAnchor();
  297. GE_CHECK_NOTNULL(pre_out_anchor);
  298. auto pre_node = pre_out_anchor->GetOwnerNode();
  299. GE_CHECK_NOTNULL(pre_node);
  300. auto pre_output_rw_type = GetOutputRWTypeByIndex(*pre_node, pre_out_anchor->GetIdx());
  301. GELOGD("Output rw type of Node %s %dth output anchor is %s", pre_node->GetName().c_str(),
  302. pre_out_anchor->GetIdx(), OutputRWTypeToSerialString(pre_output_rw_type).c_str());
  303. if (pre_output_rw_type == OutputRWType::kWriteable) {
  304. // insert identity
  305. auto identity_node = CreateIdentityAfterSrcNode(*pre_node, pre_out_anchor->GetIdx());
  306. GE_CHECK_NOTNULL(identity_node);
  307. auto ret = GraphUtils::InsertNodeBetweenDataAnchors(pre_out_anchor, in_data_anchor, identity_node);
  308. if (ret != SUCCESS) {
  309. GELOGE(ret, "Fail to insert identity");
  310. return ret;
  311. }
  312. GELOGI("InsertNode %s between %s and %s successfully.", identity_node->GetName().c_str(),
  313. pre_node->GetName().c_str(), node->GetName().c_str());
  314. }
  315. output_rw_type_map.emplace(std::make_pair(in_data_anchor->GetIdx(), OutputRWType::kSoftRead));
  316. }
  317. NodeInputOutputRWType output_rw_type{{}, output_rw_type_map};
  318. node_rwtype_map_.emplace(std::make_pair(node->GetName(), output_rw_type));
  319. }
  320. }
  321. return SUCCESS;
  322. }
  323. ///
  324. /// @brief Reverse traversal all subgraph and mark rw_type for Data/Netoutput.
  325. /// @param sub_graph_vecgs
  326. ///
  327. Status MarkRWTypeForAllSubgraph(const vector<ComputeGraphPtr> &sub_graph_vec) {
  328. for (auto iter = sub_graph_vec.rbegin(); iter != sub_graph_vec.rend(); ++iter) {
  329. auto parent_node = (*iter)->GetParentNode();
  330. if (parent_node == nullptr) {
  331. GELOGD("Current sub graph has no parent node. Ignore it.");
  332. continue;
  333. }
  334. if (parent_node->GetType() == WHILE) {
  335. continue;
  336. }
  337. auto ret = MarkRWTypeForSubgraph(*iter);
  338. if (ret != SUCCESS) {
  339. return ret;
  340. }
  341. }
  342. return SUCCESS;
  343. }
  344. ///
  345. /// @brief Check identity is near subgraph.
  346. /// Eg. As output of Data node in subgraph
  347. /// or as input of Netoutput of subgraph
  348. /// or as input of one node with subgraph
  349. /// or as output of one node with subgraph
  350. /// @param node
  351. /// @return is_near_subgraph
  352. ///
  353. bool CheckIdentityIsNearSubgraph(const Node &node) {
  354. for (const auto &in_node : node.GetInDataNodes()) {
  355. auto in_node_opdesc = in_node->GetOpDesc();
  356. if (in_node_opdesc == nullptr) {
  357. continue;
  358. }
  359. // near entrance of subgraph
  360. if (in_node->GetType() == DATA && NodeUtils::IsSubgraphInput(in_node)) {
  361. return true;
  362. }
  363. // near subgraph
  364. if (!in_node_opdesc->GetSubgraphInstanceNames().empty()) {
  365. return true;
  366. }
  367. }
  368. for (const auto &out_node : node.GetOutDataNodes()) {
  369. auto out_node_opdesc = out_node->GetOpDesc();
  370. if (out_node_opdesc == nullptr) {
  371. continue;
  372. }
  373. // near output of subgraph
  374. if (out_node->GetType() == NETOUTPUT && NodeUtils::IsSubgraphOutput(out_node)) {
  375. return true;
  376. }
  377. // near subgraph
  378. if (!out_node_opdesc->GetSubgraphInstanceNames().empty()) {
  379. return true;
  380. }
  381. }
  382. return false;
  383. }
  384. enum ConflictResult { DO_NOTHING, WRONG_GRAPH, INSERT_IDENTITY };
  385. vector<vector<ConflictResult>> output_2_input_rwtype = {{DO_NOTHING, WRONG_GRAPH, INSERT_IDENTITY},
  386. {DO_NOTHING, WRONG_GRAPH, DO_NOTHING},
  387. {DO_NOTHING, DO_NOTHING, INSERT_IDENTITY}};
  388. ConflictResult GetConflictResultBetweenNode(const OutputRWType output_rw_type, const InputRWType input_rw_type) {
  389. if (output_rw_type == OutputRWType::kInvalidRWType || input_rw_type == InputRWType::kInvalidRWType) {
  390. return WRONG_GRAPH;
  391. }
  392. auto n = static_cast<int>(output_rw_type);
  393. auto m = static_cast<int>(input_rw_type);
  394. // no need to check index or container, because container and index is all defined.
  395. return output_2_input_rwtype[n][m];
  396. }
  397. ///
  398. /// @brief Keep identity_node which near subgraph or has multi output
  399. /// @param node
  400. /// @return
  401. ///
  402. Status RemoveNoUseIdentity(const NodePtr &node) {
  403. if (node->GetInDataNodes().empty() || node->GetOutDataNodesSize() > 1) {
  404. return SUCCESS;
  405. }
  406. if (node->GetOutDataNodesSize() == 1 && node->GetOutDataNodes().at(0)->GetType() == STREAMMERGE) {
  407. return SUCCESS;
  408. }
  409. if (CheckIdentityIsNearSubgraph(*node)) {
  410. return SUCCESS;
  411. }
  412. GE_CHECK_NOTNULL(node->GetInDataAnchor(kIdentityAnchorIndex));
  413. auto pre_out_anchor = node->GetInDataAnchor(kIdentityAnchorIndex)->GetPeerOutAnchor();
  414. GE_CHECK_NOTNULL(pre_out_anchor);
  415. auto pre_node = pre_out_anchor->GetOwnerNode();
  416. auto pre_output_rw_type = GetOutputRWTypeByIndex(*pre_node, pre_out_anchor->GetIdx());
  417. auto anchor_2_outnode_vec = NodeUtils::GetOutDataNodesWithAnchorByIndex(*node, kIdentityAnchorIndex);
  418. ConflictResult conflict_result = WRONG_GRAPH;
  419. if (!anchor_2_outnode_vec.empty()) {
  420. auto anchor_2_outnode = anchor_2_outnode_vec.at(0);
  421. auto peer_input_rw_type = GetInputRWTypeByIndex(*anchor_2_outnode.second, anchor_2_outnode.first->GetIdx());
  422. GELOGD("Pre Node %s %dth output rw type is %s, peer node %s %dth input rw type is %s.", pre_node->GetName().c_str(),
  423. pre_out_anchor->GetIdx(), OutputRWTypeToSerialString(pre_output_rw_type).c_str(),
  424. anchor_2_outnode.second->GetName().c_str(), anchor_2_outnode.first->GetIdx(),
  425. InputRWTypeToSerialString(peer_input_rw_type).c_str());
  426. conflict_result = GetConflictResultBetweenNode(pre_output_rw_type, peer_input_rw_type);
  427. } else {
  428. // identity node has no out data node, it can be removed
  429. conflict_result = DO_NOTHING;
  430. }
  431. if (conflict_result != DO_NOTHING) {
  432. return SUCCESS;
  433. }
  434. GELOGI("No need insert Identity. Node %s need to remove.", node->GetName().c_str());
  435. auto ret = GraphUtils::IsolateNode(node, {0});
  436. if (ret != SUCCESS) {
  437. GELOGE(ret, "Fail to isolate node %s.", node->GetName().c_str());
  438. return ret;
  439. }
  440. ret = GraphUtils::RemoveNodeWithoutRelink(node->GetOwnerComputeGraph(), node);
  441. if (ret != SUCCESS) {
  442. GELOGE(ret, "Fail to isolate node %s.", node->GetName().c_str());
  443. return ret;
  444. }
  445. GELOGI("Pre node is %s and %dth output rw type is %s. Isolate and remove Identity node %s.",
  446. pre_node->GetName().c_str(), pre_out_anchor->GetIdx(), OutputRWTypeToSerialString(pre_output_rw_type).c_str(),
  447. node->GetName().c_str());
  448. return SUCCESS;
  449. }
  450. Status SplitIdentityAlongAnchor(const OutDataAnchorPtr &out_data_anchor, const InDataAnchorPtr &peer_in_data_anchor,
  451. const OutDataAnchorPtr &pre_out_data_anchor, NodePtr &pre_node) {
  452. // 1.check peer in node RW type.
  453. GE_CHECK_NOTNULL(peer_in_data_anchor);
  454. auto peer_in_data_node = peer_in_data_anchor->GetOwnerNode();
  455. GE_CHECK_NOTNULL(peer_in_data_node);
  456. auto input_rw_type = GetInputRWTypeByIndex(*peer_in_data_node, peer_in_data_anchor->GetIdx());
  457. auto ret = out_data_anchor->Unlink(peer_in_data_anchor);
  458. auto old_identity = out_data_anchor->GetOwnerNode();
  459. if (ret != SUCCESS) {
  460. GELOGE(ret, "Failed to unlink from %s %dth out to %s.", old_identity->GetName().c_str(), out_data_anchor->GetIdx(),
  461. peer_in_data_anchor->GetOwnerNode()->GetName().c_str());
  462. return ret;
  463. }
  464. if (input_rw_type == InputRWType::kScopeWriteable || input_rw_type == InputRWType::kWriteable) {
  465. auto new_identity = CreateIdentityAfterSrcNode(*pre_node, pre_out_data_anchor->GetIdx());
  466. GE_CHECK_NOTNULL(new_identity);
  467. if (GraphUtils::AddEdge(pre_out_data_anchor, new_identity->GetInDataAnchor(kIdentityAnchorIndex)) != SUCCESS
  468. || GraphUtils::AddEdge(new_identity->GetOutDataAnchor(kIdentityAnchorIndex), peer_in_data_anchor) != SUCCESS) {
  469. GELOGE(INTERNAL_ERROR, "Failed to insert Identity between node %s and %s",
  470. pre_out_data_anchor->GetOwnerNode()->GetName().c_str(),
  471. peer_in_data_anchor->GetOwnerNode()->GetName().c_str());
  472. return INTERNAL_ERROR;
  473. }
  474. // 2. copy in-control-edge from dst to Identity
  475. if (GraphUtils::CopyInCtrlEdges(peer_in_data_node, new_identity) != SUCCESS) {
  476. GELOGE(INTERNAL_ERROR, "Failed to copy in_control edges from node %s to %s", peer_in_data_node->GetName().c_str(),
  477. new_identity->GetName().c_str());
  478. return INTERNAL_ERROR;
  479. }
  480. GELOGI("Node %s intput rw type is %s. Insert Identity between %s and %s.", peer_in_data_node->GetName().c_str(),
  481. InputRWTypeToSerialString(input_rw_type).c_str(), pre_out_data_anchor->GetOwnerNode()->GetName().c_str(),
  482. peer_in_data_anchor->GetOwnerNode()->GetName().c_str());
  483. } else {
  484. // copy control edge to pre and peer node
  485. if (GraphUtils::CopyInCtrlEdges(old_identity, peer_in_data_node) != SUCCESS
  486. || GraphUtils::CopyOutCtrlEdges(old_identity, pre_node) != SUCCESS) {
  487. GELOGW("Fail to copy control edge from node %s.", old_identity->GetName().c_str());
  488. return FAILED;
  489. }
  490. // link identity pre node to next node directly
  491. if (GraphUtils::AddEdge(pre_out_data_anchor, peer_in_data_anchor) != SUCCESS) {
  492. GELOGW("Fail to link data edge from node %s to %s.", pre_out_data_anchor->GetOwnerNode()->GetName().c_str(),
  493. peer_in_data_anchor->GetOwnerNode()->GetName().c_str());
  494. return FAILED;
  495. }
  496. GELOGI("Node %s input rw type is %s, link data edge from Identity input node %s to out node %s directly.",
  497. peer_in_data_node->GetName().c_str(), InputRWTypeToSerialString(input_rw_type).c_str(),
  498. pre_node->GetName().c_str(), peer_in_data_node->GetName().c_str());
  499. }
  500. return SUCCESS;
  501. }
  502. Status SplitIdentity(const NodePtr &node) {
  503. GE_CHECK_NOTNULL(node);
  504. auto out_data_anchor = node->GetOutDataAnchor(kIdentityAnchorIndex);
  505. GE_CHECK_NOTNULL(out_data_anchor);
  506. if (out_data_anchor->GetPeerInDataNodesSize() <= 1) {
  507. return SUCCESS;
  508. }
  509. // get pre node and next node of identity
  510. GE_CHECK_NOTNULL(node->GetInDataAnchor(kIdentityAnchorIndex));
  511. auto pre_out_data_anchor = node->GetInDataAnchor(kIdentityAnchorIndex)->GetPeerOutAnchor();
  512. GE_CHECK_NOTNULL(pre_out_data_anchor);
  513. auto pre_node = pre_out_data_anchor->GetOwnerNode();
  514. GE_CHECK_NOTNULL(pre_node);
  515. for (const auto &peer_in_data_anchor : out_data_anchor->GetPeerInDataAnchors()) {
  516. Status ret = SplitIdentityAlongAnchor(out_data_anchor, peer_in_data_anchor, pre_out_data_anchor, pre_node);
  517. if (ret != SUCCESS) {
  518. GELOGE(ret, "Split identity node along anchor failed.");
  519. return ret;
  520. }
  521. }
  522. // 2.isolate Identity node with no data output
  523. if (node->GetOutDataNodesSize() == 0) {
  524. Status ret = GraphUtils::IsolateNode(node, {});
  525. if (ret != SUCCESS) {
  526. GELOGE(FAILED, "IsolateAndDelete identity node %s.", node->GetName().c_str());
  527. return FAILED;
  528. }
  529. ret = GraphUtils::RemoveNodeWithoutRelink(node->GetOwnerComputeGraph(), node);
  530. if (ret != SUCCESS) {
  531. GELOGE(FAILED, "IsolateAndDelete identity node %s.", node->GetName().c_str());
  532. return FAILED;
  533. }
  534. GELOGI("IsolateAndDelete identity node %s.", node->GetName().c_str());
  535. }
  536. return SUCCESS;
  537. }
  538. Status InsertIdentityAsNeeded(const NodePtr &node) {
  539. auto op_desc = node->GetOpDesc();
  540. GE_CHECK_NOTNULL(op_desc);
  541. if (node->GetOutDataNodesSize() == 0) {
  542. return SUCCESS;
  543. }
  544. for (const auto &out_data_anchor : node->GetAllOutDataAnchors()) {
  545. GE_CHECK_NOTNULL(out_data_anchor);
  546. auto output_rw_type = GetOutputRWTypeByIndex(*node, out_data_anchor->GetIdx());
  547. for (const auto &peer_in_data_anchor : out_data_anchor->GetPeerInDataAnchors()) {
  548. GE_CHECK_NOTNULL(peer_in_data_anchor);
  549. auto peer_in_node = peer_in_data_anchor->GetOwnerNode();
  550. GE_CHECK_NOTNULL(peer_in_node);
  551. auto input_rw_type = GetInputRWTypeByIndex(*peer_in_node, peer_in_data_anchor->GetIdx());
  552. GELOGD("Node %s output rw type is %s, Node %s input rw type is %s", node->GetName().c_str(),
  553. OutputRWTypeToSerialString(output_rw_type).c_str(), peer_in_node->GetName().c_str(),
  554. InputRWTypeToSerialString(input_rw_type).c_str());
  555. auto conflict_result = GetConflictResultBetweenNode(output_rw_type, input_rw_type);
  556. switch (conflict_result) {
  557. case DO_NOTHING:
  558. case WRONG_GRAPH:
  559. GELOGD("No need insert Identity.");
  560. continue;
  561. case INSERT_IDENTITY:
  562. auto identity_node = CreateIdentityAfterSrcNode(*node, out_data_anchor->GetIdx());
  563. if (identity_node == nullptr) {
  564. GELOGE(FAILED, "Create identity node failed.");
  565. return FAILED;
  566. }
  567. auto ret = GraphUtils::InsertNodeBetweenDataAnchors(out_data_anchor, peer_in_data_anchor, identity_node);
  568. if (ret != GRAPH_SUCCESS) {
  569. GELOGE(INTERNAL_ERROR, "Failed to insert reshape between node %s and %s", node->GetName().c_str(),
  570. peer_in_node->GetName().c_str());
  571. return INTERNAL_ERROR;
  572. }
  573. GELOGI("Insert Identity between %s and %s to handle memory conflict.", node->GetName().c_str(),
  574. peer_in_node->GetName().c_str());
  575. continue;
  576. }
  577. }
  578. }
  579. return SUCCESS;
  580. }
  581. Status HandleAllreduceDuplicateInput(ComputeGraphPtr &compute_graph) {
  582. for (const auto &node : compute_graph->GetDirectNode()) {
  583. if (node->GetType() == HCOMALLREDUCE) {
  584. std::set<OutDataAnchorPtr> pre_out_anchor_set;
  585. for (const auto &in_data_anchor : node->GetAllInDataAnchors()) {
  586. auto pre_out_anchor = in_data_anchor->GetPeerOutAnchor();
  587. GE_CHECK_NOTNULL(pre_out_anchor);
  588. if (pre_out_anchor_set.find(pre_out_anchor) == pre_out_anchor_set.end()) {
  589. pre_out_anchor_set.emplace(pre_out_anchor);
  590. continue;
  591. }
  592. // need insert identity
  593. auto pre_node = pre_out_anchor->GetOwnerNode();
  594. auto identity_node = CreateIdentityAfterSrcNode(*pre_node, pre_out_anchor->GetIdx());
  595. GE_CHECK_NOTNULL(identity_node);
  596. auto ret = GraphUtils::InsertNodeBetweenDataAnchors(pre_out_anchor, in_data_anchor, identity_node);
  597. GE_CHK_STATUS_RET(ret, "Fail to insert identity.");
  598. GELOGI("InsertNode %s between %s and %s successfully.", identity_node->GetName().c_str(),
  599. pre_node->GetName().c_str(), node->GetName().c_str())
  600. }
  601. }
  602. }
  603. return SUCCESS;
  604. }
  605. } // namespace
  606. namespace ge {
  607. Status GraphOptimize::CheckRWConflict(ComputeGraphPtr &compute_graph, bool &has_conflict) {
  608. node_rwtype_map_.clear();
  609. auto sub_graph_vec = compute_graph->GetAllSubgraphs();
  610. if (sub_graph_vec.empty()) {
  611. GELOGD("No sub graph here. Ignore memory conflict handle.");
  612. return SUCCESS;
  613. }
  614. // 1.loop all subgraph, mark rw type from inside to outside
  615. Status ret = MarkRWTypeForAllSubgraph(sub_graph_vec);
  616. if (ret != SUCCESS) {
  617. GELOGE(ret, "Fail to mark rw type for subgraph.");
  618. return ret;
  619. }
  620. has_conflict = false;
  621. for (const auto &node : compute_graph->GetAllNodes()) {
  622. auto op_desc = node->GetOpDesc();
  623. GE_CHECK_NOTNULL(op_desc);
  624. if (node->GetOutDataNodesSize() == 0) {
  625. return SUCCESS;
  626. }
  627. if (node->GetType() == WHILE) {
  628. return SUCCESS;
  629. }
  630. for (const auto &out_data_anchor : node->GetAllOutDataAnchors()) {
  631. GE_CHECK_NOTNULL(out_data_anchor);
  632. auto output_rw_type = GetOutputRWTypeByIndex(*node, out_data_anchor->GetIdx());
  633. for (const auto &peer_in_data_anchor : out_data_anchor->GetPeerInDataAnchors()) {
  634. GE_CHECK_NOTNULL(peer_in_data_anchor);
  635. auto peer_in_node = peer_in_data_anchor->GetOwnerNode();
  636. GE_CHECK_NOTNULL(peer_in_node);
  637. if (peer_in_node->GetType() == WHILE) {
  638. return SUCCESS;
  639. }
  640. auto input_rw_type = GetInputRWTypeByIndex(*peer_in_node, peer_in_data_anchor->GetIdx());
  641. auto conflict_result = GetConflictResultBetweenNode(output_rw_type, input_rw_type);
  642. switch (conflict_result) {
  643. case DO_NOTHING:
  644. GELOGD("No rw conflict.");
  645. continue;
  646. case WRONG_GRAPH:
  647. has_conflict = true;
  648. GELOGI("Node %s output rw type is %s, next node %s input_rw_type is %s.It is wrong graph.",
  649. node->GetName().c_str(), OutputRWTypeToSerialString(output_rw_type).c_str(),
  650. peer_in_node->GetName().c_str(), InputRWTypeToSerialString(input_rw_type).c_str());
  651. return SUCCESS;
  652. case INSERT_IDENTITY:
  653. GELOGD("There is rw conflict. It will handle later.");
  654. continue;
  655. }
  656. }
  657. }
  658. }
  659. return SUCCESS;
  660. }
  661. Status GraphOptimize::HandleMemoryRWConflict(ComputeGraphPtr &compute_graph) {
  662. GE_DUMP(compute_graph, "BeforeHandleMemConflict");
  663. node_rwtype_map_.clear();
  664. auto sub_graph_vec = compute_graph->GetAllSubgraphs();
  665. if (sub_graph_vec.empty()) {
  666. // only root graph, to handle allreduce servral input from one output anchor
  667. return HandleAllreduceDuplicateInput(compute_graph);
  668. }
  669. // 1.loop all subgraph, mark rw type from inside to outside
  670. Status ret = MarkRWTypeForAllSubgraph(sub_graph_vec);
  671. if (ret != SUCCESS) {
  672. GELOGE(ret, "Fail to mark rw type for subgraph.");
  673. return ret;
  674. }
  675. // 2.loop all node, including node in subgraph and handle memory rw conflict
  676. for (auto &node : compute_graph->GetAllNodes()) {
  677. // ignore while subgraph node
  678. const auto parent_node = node->GetOwnerComputeGraph()->GetParentNode();
  679. if ((parent_node != nullptr) && (kWhileOpTypes.count(parent_node->GetType()) > 0)) {
  680. continue;
  681. }
  682. // ignore data / netoutput of subgraph
  683. if (node->GetType() == DATA && AttrUtils::HasAttr(node->GetOpDesc(), ATTR_NAME_PARENT_NODE_INDEX)) {
  684. continue;
  685. }
  686. if (node->GetType() == NETOUTPUT && AttrUtils::HasAttr(node->GetOpDesc(), ATTR_NAME_PARENT_NODE_INDEX)) {
  687. continue;
  688. }
  689. if (node->GetType() == IDENTITY || node->GetType() == READVARIABLEOP) {
  690. // split identity
  691. ret = SplitIdentity(node);
  692. if (ret != SUCCESS) {
  693. GELOGE(ret, "Fail to split identity node %s.", node->GetName().c_str());
  694. return ret;
  695. }
  696. // remove no use identity
  697. ret = RemoveNoUseIdentity(node);
  698. if (ret != SUCCESS) {
  699. GELOGE(ret, "Fail to remove useless identity node %s.", node->GetName().c_str());
  700. return ret;
  701. }
  702. }
  703. // insert Identity
  704. ret = InsertIdentityAsNeeded(node);
  705. if (ret != SUCCESS) {
  706. GELOGE(ret, "Fail to insert Identity node.");
  707. return ret;
  708. }
  709. }
  710. GE_DUMP(compute_graph, "AfterHandleMemConflict");
  711. return SUCCESS;
  712. }
  713. } // namespace ge

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