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

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