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

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