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 18 kB

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

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