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

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