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.

cond_remove_pass.cc 15 kB

5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. /**
  2. * Copyright 2020 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "graph/passes/cond_remove_pass.h"
  17. #include "common/op/ge_op_utils.h"
  18. #include "graph/utils/graph_utils.h"
  19. #include "graph/utils/node_utils.h"
  20. #include "graph/utils/type_utils.h"
  21. namespace {
  22. const uint32_t kConditionIndexNum = 1;
  23. const uint32_t kElseBranchIndex = 1;
  24. const uint32_t kTrueIndex = 1;
  25. const uint32_t kFalseIndex = 0;
  26. /// Extra 8 bytes store pointer of string
  27. /// Extra 8 bytes store length of string
  28. /// Extra 1 byte store '\0'
  29. #ifndef ONLY_COMPILE_OPEN_SRC
  30. const int32_t kStrHeadLen = sizeof(ge::StringHead) + 1;
  31. #else
  32. const int32_t kStrHeadLen = 9;
  33. #endif
  34. const int32_t kInvalidRetVal = -1;
  35. }
  36. namespace ge {
  37. Status CondRemovePass::Run(NodePtr &node) {
  38. GE_CHECK_NOTNULL(node);
  39. ComputeGraphPtr graph = nullptr;
  40. OutDataAnchorPtr cond_out_anchor = nullptr;
  41. InDataAnchorPtr cond_in_anchor = nullptr;
  42. Status ret = GetCondInfo(node, graph, cond_out_anchor, cond_in_anchor);
  43. if (ret == NOT_CHANGED) {
  44. return SUCCESS;
  45. } else if (ret != SUCCESS) {
  46. GELOGE(FAILED, "Get cond_info for node %s failed.", node->GetName().c_str());
  47. return FAILED;
  48. }
  49. int32_t cond_index = 0;
  50. GELOGD("Handle cond remove for node %s.", node->GetOpDesc()->GetName().c_str());
  51. bool if_cond_const = CheckIfCondConstInput(cond_out_anchor, cond_in_anchor, cond_index);
  52. if (!if_cond_const || (cond_index < 0)) {
  53. return ge::SUCCESS;
  54. }
  55. ComputeGraphPtr chosen_graph = nullptr;
  56. const std::string &node_type = node->GetType();
  57. // Keep chosen branch
  58. if (kIfOpTypes.count(node_type) != 0) {
  59. ret = GetIfChosenBranch(node, static_cast<uint32_t>(cond_index), chosen_graph);
  60. if (ret != ge::SUCCESS) {
  61. return ge::FAILED;
  62. }
  63. } else if (kCaseOpTypes.count(node_type) != 0) {
  64. ret = GetCaseChosenBranch(node, static_cast<uint32_t>(cond_index), chosen_graph);
  65. if (ret != ge::SUCCESS) {
  66. return ge::FAILED;
  67. }
  68. } else {
  69. return ge::SUCCESS;
  70. }
  71. // Remove unused link from cond->node
  72. ret = RemoveDeadCondLink(static_cast<int32_t>(IF_COND_INPUT), node);
  73. if (ret != ge::SUCCESS) {
  74. return ge::FAILED;
  75. }
  76. // Copy If/Case node's relations to the new node
  77. ret = ReplaceIfCaseNodeWithPartitioncall(node, chosen_graph);
  78. if (ret != ge::SUCCESS) {
  79. return ge::FAILED;
  80. }
  81. // Isolate and delete the old node
  82. ret = IsolateAndDeleteNode(node, std::vector<int>());
  83. return ret;
  84. }
  85. Status CondRemovePass::RemoveDeadCondLink(const int32_t index, const NodePtr &node) {
  86. const auto &in_anchor = node->GetInDataAnchor(index);
  87. const auto &peerout_anchor = in_anchor->GetPeerOutAnchor();
  88. if (GraphUtils::RemoveEdge(peerout_anchor, in_anchor) != SUCCESS) {
  89. GELOGE(FAILED, "Remove edge from node %s index %d to node %s index %d.",
  90. peerout_anchor->GetOwnerNode()->GetName().c_str(), peerout_anchor->GetIdx(),
  91. in_anchor->GetOwnerNode()->GetName().c_str(), in_anchor->GetIdx());
  92. return FAILED;
  93. }
  94. return SUCCESS;
  95. }
  96. Status CondRemovePass::GetCaseChosenBranch(const NodePtr &node, const uint32_t cond_index,
  97. ComputeGraphPtr &compute_graph) {
  98. uint32_t subgraph_names_size = static_cast<uint32_t>(node->GetOpDesc()->GetSubgraphInstanceNames().size());
  99. uint32_t cond_index_new = cond_index;
  100. if (subgraph_names_size == 0) {
  101. GELOGE(FAILED, "Node %s has none subgraph.", node->GetName().c_str());
  102. return ge::FAILED;
  103. }
  104. // If cond index is over the maimum subgraph number, choose the last subgraph
  105. if (cond_index >= subgraph_names_size) {
  106. cond_index_new = subgraph_names_size - 1;
  107. }
  108. const auto &chosen_branch_name = node->GetOpDesc()->GetSubgraphInstanceName(cond_index_new);
  109. if (chosen_branch_name.empty()) {
  110. GELOGE(FAILED, "Node %s has no subgraph, index is %u.", node->GetName().c_str(), cond_index_new);
  111. return ge::FAILED;
  112. }
  113. auto chosen_graph = GraphUtils::FindRootGraph(node->GetOwnerComputeGraph())->GetSubgraph(chosen_branch_name);
  114. compute_graph = chosen_graph;
  115. // Remove graph from node, in order for remove connection from this node to chosen branch
  116. node->GetOpDesc()->RemoveSubgraphInstanceName(chosen_branch_name);
  117. return ge::SUCCESS;
  118. }
  119. Status CondRemovePass::GetIfChosenBranch(const NodePtr &node, const uint32_t cond, ComputeGraphPtr &compute_graph) {
  120. uint32_t subgraph_names_size = static_cast<uint32_t>(node->GetOpDesc()->GetSubgraphInstanceNames().size());
  121. uint32_t cond_index_new = 0;
  122. if (subgraph_names_size == 0) {
  123. GELOGE(FAILED, "Node %s has none subgraph.", node->GetName().c_str());
  124. return ge::FAILED;
  125. }
  126. // If cond is false, else branch
  127. if (cond == 0) {
  128. cond_index_new = kElseBranchIndex;
  129. }
  130. const auto &chosen_branch_name = node->GetOpDesc()->GetSubgraphInstanceName(cond_index_new);
  131. if (chosen_branch_name.empty()) {
  132. GELOGE(FAILED, "Node %s has no subgraph, index is %u.", node->GetName().c_str(), cond_index_new);
  133. return ge::FAILED;
  134. }
  135. auto chosen_graph = GraphUtils::FindRootGraph(node->GetOwnerComputeGraph())->GetSubgraph(chosen_branch_name);
  136. if (chosen_graph == nullptr) {
  137. GELOGE(FAILED, "Can not find branch %s in node %s's parent graph %s.", chosen_branch_name.c_str(),
  138. node->GetName().c_str(), node->GetOwnerComputeGraph()->GetName().c_str());
  139. return ge::FAILED;
  140. }
  141. compute_graph = chosen_graph;
  142. // Remove graph from node, in order for remove connection from this node to chosen branch
  143. node->GetOpDesc()->RemoveSubgraphInstanceName(chosen_branch_name);
  144. return ge::SUCCESS;
  145. }
  146. int32_t CondRemovePass::GetCondIndex(const ConstGeTensorPtr &tensor) {
  147. if (tensor == nullptr) {
  148. return kInvalidRetVal;
  149. }
  150. const uint8_t *data_ptr = tensor->GetData().data();
  151. size_t tensor_size = tensor->GetData().size();
  152. const auto type = tensor->GetTensorDesc().GetDataType();
  153. GELOGD("Data type is %d, tensor_size is %zu.", type, tensor_size);
  154. switch (type) {
  155. case DT_STRING:
  156. return static_cast<int32_t>(((tensor_size - kStrHeadLen) > 0) ? kTrueIndex : kFalseIndex);
  157. case DT_BOOL:
  158. return static_cast<int32_t>(*reinterpret_cast<const bool *>(data_ptr));
  159. case DT_FLOAT:
  160. return static_cast<int32_t>(*reinterpret_cast<const float *>(data_ptr));
  161. case DT_DOUBLE:
  162. return static_cast<int32_t>(*reinterpret_cast<const double *>(data_ptr));
  163. case DT_INT8:
  164. case DT_UINT8:
  165. return static_cast<int32_t>(*data_ptr);
  166. case DT_FLOAT16:
  167. case DT_INT16:
  168. case DT_UINT16:
  169. return static_cast<int32_t>(*reinterpret_cast<const int16_t *>(data_ptr));
  170. case DT_INT32:
  171. return static_cast<int32_t>(*reinterpret_cast<const int32_t *>(data_ptr));
  172. case DT_UINT32:
  173. return *reinterpret_cast<const int32_t *>(data_ptr);
  174. case DT_INT64:
  175. case DT_UINT64:
  176. return static_cast<int32_t>(*reinterpret_cast<const int64_t *>(data_ptr));
  177. default:
  178. return static_cast<int32_t>(*data_ptr);
  179. }
  180. }
  181. bool CondRemovePass::CheckIfCondConstInput(const OutDataAnchorPtr &cond_out_anchor,
  182. const InDataAnchorPtr &cond_in_anchor, int32_t &cond_index) {
  183. // if pre or next anchor is null, return
  184. CHECK_FALSE_EXEC(cond_out_anchor != nullptr, return false);
  185. CHECK_FALSE_EXEC(cond_in_anchor != nullptr, return false);
  186. const auto &out_node = cond_out_anchor->GetOwnerNode();
  187. const auto &cur_node = cond_in_anchor->GetOwnerNode();
  188. OpDescPtr op_desc = cur_node->GetOpDesc();
  189. GE_CHECK_NOTNULL_EXEC(op_desc, return false);
  190. GeTensorDesc cond_tensor = out_node->GetOpDesc()->GetOutputDesc(static_cast<uint32_t>(cond_out_anchor->GetIdx()));
  191. GELOGI("Check if condition is const for node %s.", op_desc->GetName().c_str());
  192. if (kConstOpTypes.count(out_node->GetOpDesc()->GetType()) == 0) {
  193. return false;
  194. }
  195. // Case node only support int32 input
  196. if ((kCaseOpTypes.count(cur_node->GetType()) != 0) && (cond_tensor.GetDataType() != DT_INT32)) {
  197. GELOGW("Check input failed, node is %s, condition datatype is %s.", op_desc->GetName().c_str(),
  198. TypeUtils::DataTypeToSerialString(cond_tensor.GetDataType()).c_str());
  199. return false;
  200. }
  201. // Get weights from peer node
  202. auto weights = OpDescUtils::GetWeights(out_node);
  203. if (weights.size() <= static_cast<size_t>(cond_out_anchor->GetIdx())) {
  204. GELOGI("Get weights of node %s out index %d, weight size %zu is not fit for data index %d.",
  205. out_node->GetName().c_str(), cond_out_anchor->GetIdx(), weights.size(), cond_out_anchor->GetIdx());
  206. return false;
  207. }
  208. ConstGeTensorPtr tensor = weights[cond_out_anchor->GetIdx()];
  209. GE_CHECK_NOTNULL_EXEC(tensor, return false);
  210. bool if_zero_dim = false;
  211. if (!cond_tensor.GetShape().IsScalar()) {
  212. for (size_t dim = 0; dim < cond_tensor.GetShape().GetDimNum(); dim++) {
  213. if (cond_tensor.GetShape().GetDim(dim) == 0) {
  214. if_zero_dim = true;
  215. break;
  216. }
  217. }
  218. // If dim num is not zero and do not has zero dim, index is 1, else index is 0
  219. cond_index = static_cast<int32_t>((cond_tensor.GetShape().GetDimNum() != 0) && !if_zero_dim);
  220. } else {
  221. // Get condition index
  222. cond_index = GetCondIndex(tensor);
  223. }
  224. GELOGD("Condition index is %d, node name is %s, anchor index is %d, dim num is %zu, zero dim flag %d", cond_index,
  225. op_desc->GetName().c_str(), cond_out_anchor->GetIdx(), cond_tensor.GetShape().GetDimNum(), if_zero_dim);
  226. return true;
  227. }
  228. Status CondRemovePass::ReplaceIfCaseNodeWithPartitioncall(const NodePtr &node, const ComputeGraphPtr &save_branch) {
  229. // Add compute graph to new node
  230. const auto &input_desc_size = node->GetOpDesc()->GetInputsSize();
  231. const auto &output_desc_size = node->GetOpDesc()->GetOutputsSize();
  232. // Create subgraph opdesc & node
  233. auto partitioncall_opdesc =
  234. CreateSubgraphOpDesc(node, save_branch->GetName(), input_desc_size - kConditionIndexNum, output_desc_size);
  235. auto partitioncall_node = node->GetOwnerComputeGraph()->AddNode(partitioncall_opdesc);
  236. // Link node's peerout anchors to new node's inanchors
  237. for (const auto &input_anchor : node->GetAllInAnchors()) {
  238. for (const auto &peerout_anchor : input_anchor->GetPeerAnchors()) {
  239. if (GraphUtils::AddEdge(peerout_anchor, partitioncall_node->GetInAnchor(
  240. input_anchor->GetIdx() - kConditionIndexNum)) != ge::GRAPH_SUCCESS) {
  241. GELOGE(FAILED, "Add edge failed, from node:%s idx:%d to node:%s idx:%d, input num:%zu, output num:%zu",
  242. peerout_anchor->GetOwnerNode()->GetName().c_str(), peerout_anchor->GetIdx(),
  243. partitioncall_node->GetName().c_str(), input_anchor->GetIdx(), input_desc_size,
  244. output_desc_size);
  245. return FAILED;
  246. }
  247. }
  248. }
  249. // Remove If / Case anchor and peer in anchor
  250. // Link new node's out anchors to node's peer inanchors
  251. for (const auto &output_anchor : node->GetAllOutAnchors()) {
  252. for (const auto &peerin_anchor : output_anchor->GetPeerAnchors()) {
  253. if (GraphUtils::RemoveEdge(node->GetOutAnchor(output_anchor->GetIdx()), peerin_anchor) != ge::GRAPH_SUCCESS) {
  254. GELOGE(FAILED, "Remove edge failed, from node:%s idx:%d to node:%s idx:%d, input num:%zu, output num:%zu",
  255. node->GetName().c_str(), output_anchor->GetIdx(), peerin_anchor->GetOwnerNode()->GetName().c_str(),
  256. peerin_anchor->GetIdx(), input_desc_size, output_desc_size);
  257. return FAILED;
  258. }
  259. if (GraphUtils::AddEdge(partitioncall_node->GetOutAnchor(output_anchor->GetIdx()), peerin_anchor) !=
  260. ge::GRAPH_SUCCESS) {
  261. GELOGE(FAILED, "Add edge failed, from node:%s idx:%d to node:%s idx:%d, input num:%zu, output num:%zu",
  262. partitioncall_node->GetName().c_str(), output_anchor->GetIdx(),
  263. peerin_anchor->GetOwnerNode()->GetName().c_str(), peerin_anchor->GetIdx(), input_desc_size,
  264. output_desc_size);
  265. return FAILED;
  266. }
  267. }
  268. }
  269. // update save branch information
  270. std::map<uint32_t, uint32_t> input_mapping;
  271. uint32_t new_input_num = static_cast<uint32_t>(node->GetOpDesc()->GetAllInputsSize()) - kConditionIndexNum;
  272. for (uint32_t i = 0; i < new_input_num; i++) {
  273. // original index + 1 map to index
  274. input_mapping[i + 1] = i;
  275. }
  276. save_branch->UpdateInputMapping(input_mapping);
  277. save_branch->SetParentNode(partitioncall_node);
  278. save_branch->SetParentGraph(node->GetOwnerComputeGraph());
  279. return SUCCESS;
  280. }
  281. ///
  282. /// @brief Create op_desc for subgraph node
  283. /// @param [in] name
  284. /// @param [in] input_num
  285. /// @param [in] output_num
  286. /// @return OpDescPtr
  287. ///
  288. OpDescPtr CondRemovePass::CreateSubgraphOpDesc(const NodePtr &node, const std::string &name, size_t input_num,
  289. size_t output_num) {
  290. OpDescBuilder op_desc_builder(name, PARTITIONEDCALL);
  291. op_desc_builder.AddDynamicInput("args", input_num).AddDynamicOutput("output", output_num);
  292. OpDescPtr op_desc = op_desc_builder.Build();
  293. GE_CHECK_NOTNULL_EXEC(op_desc, return nullptr);
  294. size_t index = op_desc->GetSubgraphInstanceNames().size();
  295. op_desc->AddSubgraphName("f");
  296. op_desc->SetSubgraphInstanceName(static_cast<uint32_t>(index), name);
  297. auto node_desc = node->GetOpDesc();
  298. GE_CHECK_NOTNULL_EXEC(node_desc, return nullptr);
  299. for (size_t i = 0; i < input_num; ++i) {
  300. (void)op_desc->UpdateInputDesc(i, node_desc->GetInputDesc(i + 1));
  301. }
  302. for (size_t i = 0; i < output_num; ++i) {
  303. (void)op_desc->UpdateOutputDesc(i, node_desc->GetOutputDesc(i));
  304. }
  305. return op_desc;
  306. }
  307. ///
  308. /// @brief Get cond info for if/case node
  309. /// @param [in] node: If/Case op
  310. /// @param [out] graph: owner_graph of if node
  311. /// @param [out] cond_out_anchor: peer_cond_anchor
  312. /// @param [out] cond_in_anchor: cond_input of if
  313. /// @return Status
  314. ///
  315. Status CondRemovePass::GetCondInfoForIfCase(const NodePtr &node, ComputeGraphPtr &graph,
  316. OutDataAnchorPtr &cond_out_anchor, InDataAnchorPtr &cond_in_anchor) {
  317. GE_CHECK_NOTNULL(node);
  318. graph = node->GetOwnerComputeGraph();
  319. GE_CHECK_NOTNULL(graph);
  320. cond_in_anchor = node->GetInDataAnchor(IF_COND_INPUT);
  321. GE_CHECK_NOTNULL(cond_in_anchor);
  322. cond_out_anchor = cond_in_anchor->GetPeerOutAnchor();
  323. GE_CHECK_NOTNULL(cond_out_anchor);
  324. return SUCCESS;
  325. }
  326. Status CondRemovePass::GetCondInfo(const NodePtr &node, ComputeGraphPtr &graph, OutDataAnchorPtr &cond_out_anchor,
  327. InDataAnchorPtr &cond_in_anchor) {
  328. GE_CHECK_NOTNULL(node);
  329. std::string type = node->GetType();
  330. if ((kIfOpTypes.count(type) != 0) || (kCaseOpTypes.count(type) != 0)) {
  331. if (GetCondInfoForIfCase(node, graph, cond_out_anchor, cond_in_anchor) != SUCCESS) {
  332. GELOGE(FAILED, "Get cond_info for if/case node failed.");
  333. return FAILED;
  334. }
  335. } else {
  336. GELOGD("no need cond_remove_pass for node %s.", node->GetName().c_str());
  337. return NOT_CHANGED;
  338. }
  339. return SUCCESS;
  340. }
  341. }

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