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

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

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