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.

infershape_pass.cc 16 kB

4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. /**
  2. * Copyright 2020-2021 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/infershape_pass.h"
  17. #include "common/util/error_manager/error_manager.h"
  18. #include "framework/common/debug/ge_log.h"
  19. #include "analyzer/analyzer.h"
  20. #include "framework/common/util.h"
  21. #include "graph/shape_refiner.h"
  22. #include "graph/utils/graph_utils.h"
  23. #include "graph/utils/node_utils.h"
  24. #include "common/omg_util.h"
  25. #include "graph/debug/ge_attr_define.h"
  26. #include "graph/utils/tensor_utils.h"
  27. #include "graph/utils/type_utils.h"
  28. #include "external/graph/operator_factory.h"
  29. namespace ge {
  30. namespace {
  31. constexpr int kSwitchExitAnchorIndex = 0;
  32. constexpr int kSwitchPredAnchorIndex = 1;
  33. void SerialShapeRange(const GeTensorDescPtr &desc, std::string &desc_str) {
  34. desc_str += "[";
  35. std::vector<std::pair<int64_t, int64_t>> shape_range;
  36. (void)desc->GetShapeRange(shape_range);
  37. for (const auto &pair : shape_range) {
  38. desc_str += "{";
  39. desc_str += std::to_string(pair.first) + "," + std::to_string(pair.second);
  40. desc_str += "},";
  41. }
  42. desc_str += "]";
  43. shape_range.clear();
  44. (void)desc->GetOriginShapeRange(shape_range);
  45. for (const auto &pair : shape_range) {
  46. desc_str += ",{";
  47. desc_str += std::to_string(pair.first) + "," + std::to_string(pair.second);
  48. desc_str += "},";
  49. }
  50. }
  51. void UpdateShapeAndDType(const GeTensorDescPtr &src, GeTensorDescPtr &dst) {
  52. dst->SetOriginShape(src->GetOriginShape());
  53. dst->SetShape(src->GetShape());
  54. dst->SetDataType(src->GetDataType());
  55. dst->SetOriginDataType(src->GetOriginDataType());
  56. vector<pair<int64_t, int64_t>> dst_shape_range;
  57. dst->GetShapeRange(dst_shape_range);
  58. dst->SetOriginShapeRange(dst_shape_range);
  59. ge::TensorUtils::SetRealDimCnt(*dst, static_cast<uint32_t>(src->GetShape().GetDims().size()));
  60. }
  61. } // namespace
  62. std::string InferShapePass::SerialTensorInfo(const GeTensorDescPtr &tensor_desc) const {
  63. std::stringstream ss;
  64. ss << "(shape:[" << tensor_desc->MutableShape().ToString() << "]),";
  65. ss << "(format:" << TypeUtils::FormatToSerialString(tensor_desc->GetFormat()) << "),";
  66. ss << "(dtype:" << TypeUtils::DataTypeToSerialString(tensor_desc->GetDataType()) << "),";
  67. ss << "(origin_shape:" << tensor_desc->GetOriginShape().ToString() << "),";
  68. ss << "(origin_format:" << TypeUtils::FormatToSerialString(tensor_desc->GetOriginFormat()) << "),";
  69. ss << "(origin_dtype:" << TypeUtils::DataTypeToSerialString(tensor_desc->GetOriginDataType()) << "),";
  70. string range_str;
  71. SerialShapeRange(tensor_desc, range_str);
  72. ss << "(shape_range:" << range_str << ")";
  73. return ss.str();
  74. }
  75. Status InferShapePass::SuspendV1LoopExitNodes(const NodePtr &node) {
  76. if (node->GetType() != SWITCH) {
  77. return SUCCESS;
  78. }
  79. auto pred_node = NodeUtils::GetInDataNodeByIndex(*node, kSwitchPredAnchorIndex);
  80. GE_CHECK_NOTNULL(pred_node);
  81. if (pred_node->GetType() != LOOPCOND) {
  82. return SUCCESS;
  83. }
  84. for (const auto &anchor_2_node : NodeUtils::GetOutDataNodesWithAnchorByIndex(*node, kSwitchExitAnchorIndex)) {
  85. GELOGI("Found v1 loop when infershape, suspend Exit node %s, type %s.", anchor_2_node.second->GetName().c_str(),
  86. anchor_2_node.second->GetType().c_str());
  87. auto &suspend_nodes = graphs_2_suspend_nodes_[GetCurrentGraphName()];
  88. if (suspend_nodes.nodes_set.insert(anchor_2_node.second).second) {
  89. suspend_nodes.nodes.push(anchor_2_node.second);
  90. AddNodeSuspend(anchor_2_node.second);
  91. }
  92. }
  93. return SUCCESS;
  94. }
  95. Status InferShapePass::Infer(NodePtr &node) {
  96. auto ret = InferShapeAndType(node);
  97. if (ret != GRAPH_SUCCESS) {
  98. auto graph = node->GetOwnerComputeGraph();
  99. GE_CHECK_NOTNULL(graph);
  100. auto root_graph = ge::GraphUtils::FindRootGraph(graph);
  101. GE_CHECK_NOTNULL(root_graph);
  102. analyzer::DataInfo analyze_info{root_graph->GetSessionID(), root_graph->GetGraphID(),
  103. analyzer::INFER_SHAPE, node, "InferShapeFailed!"};
  104. (void)Analyzer::GetInstance()->DoAnalyze(analyze_info);
  105. (void)Analyzer::GetInstance()->SaveAnalyzerDataToFile(root_graph->GetSessionID(),
  106. root_graph->GetGraphID());
  107. REPORT_CALL_ERROR("E19999", "Call InferShapeAndType for node:%s(%s) failed", node->GetName().c_str(),
  108. node->GetType().c_str());
  109. GELOGE(GE_GRAPH_INFERSHAPE_FAILED, "[Call][InferShapeAndType] for node:%s(%s) failed", node->GetName().c_str(),
  110. node->GetType().c_str());
  111. return GE_GRAPH_INFERSHAPE_FAILED;
  112. }
  113. return SUCCESS;
  114. }
  115. graphStatus InferShapePass::InferShapeAndType(NodePtr &node) {
  116. auto ret = SuspendV1LoopExitNodes(node);
  117. if (ret != SUCCESS) {
  118. GELOGE(ret, "Suspend V1 loop exit nodes failed.");
  119. return ret;
  120. }
  121. bool is_unknown_graph = node->GetOwnerComputeGraph()->GetGraphUnknownFlag();
  122. auto opdesc = node->GetOpDesc();
  123. if (node->Verify() != GRAPH_SUCCESS) {
  124. REPORT_CALL_ERROR("E19999", "Verifying %s failed.", node->GetName().c_str());
  125. GELOGE(GRAPH_FAILED, "[Call][Verify] Verifying %s failed.", node->GetName().c_str());
  126. return GRAPH_FAILED;
  127. }
  128. Operator op = OpDescUtils::CreateOperatorFromNode(node);
  129. if (!is_unknown_graph) {
  130. auto inference_context = ShapeRefiner::CreateInferenceContext(node);
  131. GE_CHECK_NOTNULL(inference_context);
  132. std::vector<AscendString> marks;
  133. inference_context->GetMarks(marks);
  134. GELOGD("create context for node:%s, marks %zu", node->GetName().c_str(), marks.size());
  135. op.SetInferenceContext(inference_context);
  136. }
  137. graphStatus status = CallInferShapeFunc(node, op);
  138. if (status != GRAPH_NODE_NEED_REPASS && status != GRAPH_PARAM_INVALID && status != GRAPH_SUCCESS) {
  139. // node like netoutput return param_invalid, but valid ?
  140. return GE_GRAPH_INFERSHAPE_FAILED;
  141. }
  142. UpdateCurNodeOutputDesc(node);
  143. if (!is_unknown_graph) {
  144. auto ctx_after_infer = op.GetInferenceContext();
  145. if (ctx_after_infer != nullptr) {
  146. std::vector<AscendString> marks;
  147. ctx_after_infer->GetMarks(marks);
  148. GELOGD("[%s] after infershape. mark:%zu", node->GetName().c_str(), marks.size());
  149. if (!ctx_after_infer->GetOutputHandleShapesAndTypes().empty() || !marks.empty()) {
  150. GELOGD("[%s] set inference context after. mark:%zu", node->GetName().c_str(),
  151. marks.size());
  152. ShapeRefiner::PushToContextMap(node, ctx_after_infer);
  153. }
  154. }
  155. }
  156. return (status == GRAPH_NODE_NEED_REPASS) ? GRAPH_NODE_NEED_REPASS : GRAPH_SUCCESS;
  157. }
  158. void InferShapePass::UpdateCurNodeOutputDesc(NodePtr &node) {
  159. auto op_desc = node->GetOpDesc();
  160. for (const auto &out_anchor : node->GetAllOutDataAnchors()) {
  161. auto output_tensor = op_desc->MutableOutputDesc(out_anchor->GetIdx());
  162. GE_IF_BOOL_EXEC(output_tensor == nullptr, continue);
  163. GE_IF_BOOL_EXEC(output_tensor->MutableShape().GetDims().empty(),
  164. output_tensor->SetOriginShape(output_tensor->GetShape()));
  165. ge::TensorUtils::SetRealDimCnt(*output_tensor, static_cast<uint32_t>(output_tensor->GetOriginShape().GetDims()
  166. .size()));
  167. output_tensor->SetOriginDataType(output_tensor->GetDataType());
  168. // set output origin shape range
  169. std::vector<std::pair<int64_t, int64_t>> range;
  170. (void)output_tensor->GetShapeRange(range);
  171. output_tensor->SetOriginShapeRange(range);
  172. GELOGD("node name is %s, origin shape is %ld, origin format is %s, origin data type is %s",
  173. node->GetName().c_str(), output_tensor->GetOriginShape().GetShapeSize(),
  174. TypeUtils::FormatToSerialString(output_tensor->GetOriginFormat()).c_str(),
  175. TypeUtils::DataTypeToSerialString(output_tensor->GetOriginDataType()).c_str());
  176. }
  177. }
  178. bool InferShapePass::SameTensorDesc(const GeTensorDescPtr &src, const GeTensorDescPtr &dst) {
  179. // check shape range
  180. vector<std::pair<int64_t, int64_t>> src_shape_range;
  181. vector<std::pair<int64_t, int64_t>> dst_shape_range;
  182. src->GetShapeRange(src_shape_range);
  183. dst->GetShapeRange(dst_shape_range);
  184. if (src_shape_range.size() != dst_shape_range.size()) {
  185. GELOGI("Src shape range size is %zu, dst shape range size is %zu, not same.", src_shape_range.size(),
  186. dst_shape_range.size());
  187. return false;
  188. }
  189. for (size_t i = 0; i < src_shape_range.size(); ++i) {
  190. if (src_shape_range[i].first != dst_shape_range[i].first ||
  191. src_shape_range[i].second != dst_shape_range[i].second) {
  192. GELOGI("Current dim %zu. Src shape range is [%lu-%lu], dst shape range is [%lu-%lu], not same.",
  193. i, src_shape_range[i].first, src_shape_range[i].second, dst_shape_range[i].first, dst_shape_range[i].second);
  194. return false;
  195. }
  196. }
  197. // check shape
  198. auto src_shape = src->GetShape();
  199. auto dst_shape = dst->GetShape();
  200. if (src_shape.GetDims() != dst_shape.GetDims() || src->GetOriginShape().GetDims() != dst->GetOriginShape().GetDims() ||
  201. src->GetDataType() != dst->GetDataType() || src->GetOriginDataType() != dst->GetOriginDataType()) {
  202. GELOGD(
  203. "Src shape is %s, origin_shape is %s, data_type is %s, origin data_type is %s; "
  204. "Dst shape is %s, origin_shape is %s, data_type is %s, original data_type is %s, not same.",
  205. src_shape.ToString().c_str(), src->GetOriginShape().ToString().c_str(),
  206. TypeUtils::DataTypeToSerialString(src->GetDataType()).c_str(),
  207. TypeUtils::DataTypeToSerialString(src->GetOriginDataType()).c_str(), dst_shape.ToString().c_str(),
  208. dst->GetOriginShape().ToString().c_str(), TypeUtils::DataTypeToSerialString(dst->GetDataType()).c_str(),
  209. TypeUtils::DataTypeToSerialString(dst->GetOriginDataType()).c_str());
  210. return false;
  211. }
  212. return true;
  213. }
  214. graphStatus InferShapePass::UpdateTensorDesc(const GeTensorDescPtr &src, GeTensorDescPtr &dst, bool &changed) {
  215. changed = false;
  216. if (SameTensorDesc(src, dst)) {
  217. GELOGD("Peer dst tensor_desc is same as src tensor_desc. No need update.");
  218. return SUCCESS;
  219. }
  220. changed = true;
  221. UpdateShapeAndDType(src, dst);
  222. GELOGD(
  223. "UpdatePeerInputDesc from src Node: shape: [%s], datatype: %s, original datatype is %s."
  224. "To dst Node: shape: [%s], datatype: %s, original datatype is %s.",
  225. src->GetShape().ToString().c_str(), TypeUtils::DataTypeToSerialString(src->GetDataType()).c_str(),
  226. TypeUtils::DataTypeToSerialString(src->GetOriginDataType()).c_str(), dst->GetShape().ToString().c_str(),
  227. TypeUtils::DataTypeToSerialString(dst->GetDataType()).c_str(),
  228. TypeUtils::DataTypeToSerialString(dst->GetOriginDataType()).c_str());
  229. return SUCCESS;
  230. }
  231. graphStatus InferShapePass::CallInferShapeFunc(NodePtr &node, Operator &op) {
  232. auto op_desc = node->GetOpDesc();
  233. const auto &op_type = op_desc->GetType();
  234. auto ret = op_desc->CallInferFunc(op);
  235. if (ret == GRAPH_PARAM_INVALID) {
  236. // Op ir no infer func, try to get infer func from operator factory
  237. auto node_op = ge::OperatorFactory::CreateOperator("node_op", op_desc->GetType().c_str());
  238. if (node_op.IsEmpty()) {
  239. GELOGW("get op from OperatorFactory fail. opType: %s", op_type.c_str());
  240. return ret;
  241. }
  242. GELOGD("get op from OperatorFactory success. opType: %s", op_type.c_str());
  243. auto temp_op_desc = ge::OpDescUtils::GetOpDescFromOperator(node_op);
  244. node_op.BreakConnect();
  245. if (temp_op_desc == nullptr) {
  246. REPORT_CALL_ERROR("E19999", "GetOpDescFromOperator failed, return nullptr.");
  247. GELOGE(GRAPH_FAILED, "[Get][OpDesc] temp op desc is null");
  248. return GRAPH_FAILED;
  249. }
  250. if (!op_desc->UpdateInputName(temp_op_desc->GetAllInputName())) {
  251. GELOGW("InferShapeAndType UpdateInputName failed");
  252. for (const auto &out_desc : op_desc->GetAllOutputsDescPtr()) {
  253. if (out_desc != nullptr && out_desc->GetShape().GetDims().empty()) {
  254. break;
  255. }
  256. return GRAPH_SUCCESS;
  257. }
  258. }
  259. if (!op_desc->UpdateOutputName(temp_op_desc->GetAllOutputName())) {
  260. GELOGW("InferShapeAndType UpdateOutputName failed");
  261. }
  262. op_desc->AddInferFunc(temp_op_desc->GetInferFunc());
  263. ret = op_desc->CallInferFunc(op);
  264. GELOGI("op CallInferFunc second. ret: %u", ret);
  265. }
  266. return ret;
  267. }
  268. graphStatus InferShapePass::UpdateOutputFromSubgraphs(const std::vector<GeTensorDescPtr> &src, GeTensorDescPtr &dst) {
  269. GELOGD("Enter update parent node shape for class branch op process");
  270. // check sub_graph shape.If not same ,do unknown shape process
  271. auto ref_out_tensor = src.at(0);
  272. ge::GeShape &ref_out_tensor_shape = ref_out_tensor->MutableShape();
  273. for (auto &tensor : src) {
  274. if (ref_out_tensor->GetDataType() != tensor->GetDataType()) {
  275. REPORT_INNER_ERROR("E19999", "Does not support diff dtype among all ref output, shape:%s",
  276. ref_out_tensor_shape.ToString().c_str());
  277. GELOGE(GRAPH_FAILED, "[Check][Param] node does not support diff dtype output");
  278. return GRAPH_FAILED;
  279. }
  280. auto shape = tensor->MutableShape();
  281. if (shape.GetDims().size() != ref_out_tensor_shape.GetDims().size()) {
  282. GELOGD("Shape from subgraph size: %lu, ref_out_tensor_shape size: %lu", shape.GetShapeSize(),
  283. ref_out_tensor_shape.GetShapeSize());
  284. ref_out_tensor_shape = GeShape(UNKNOWN_RANK);
  285. break;
  286. }
  287. for (size_t j = 0; j < ref_out_tensor_shape.GetDims().size(); j++) {
  288. if (ref_out_tensor_shape.GetDim(j) == shape.GetDim(j)) {
  289. continue;
  290. }
  291. GELOGD("j: %zu ,shape from subgraph size: %lu, ref_out_tensor_shape size: %lu", j, shape.GetShapeSize(),
  292. ref_out_tensor_shape.GetShapeSize());
  293. (void)ref_out_tensor_shape.SetDim(j, UNKNOWN_DIM);
  294. }
  295. }
  296. UpdateShapeAndDType(ref_out_tensor, dst);
  297. return GRAPH_SUCCESS;
  298. }
  299. graphStatus InferShapePass::UpdateOutputFromSubgraphsForMultiDims(const std::vector<GeTensorDescPtr> &src,
  300. GeTensorDescPtr &dst) {
  301. // check sub_graph shape. Get max for update.
  302. if (src.empty()) {
  303. GELOGI("Src subgraph shape is empty.");
  304. return SUCCESS;
  305. }
  306. int64_t max_size = 0;
  307. size_t max_shape_index = 0;
  308. auto &ref_out_tensor = src.at(0);
  309. for (size_t j = 0; j < src.size(); ++j) {
  310. auto &tensor = src.at(j);
  311. if (ref_out_tensor->GetDataType() != tensor->GetDataType()) {
  312. REPORT_INNER_ERROR("E19999", "node does not support diff dtype among all ref output");
  313. GELOGE(GRAPH_FAILED, "[Check][Param] node does not support diff dtype among all ref output");
  314. return GRAPH_FAILED;
  315. }
  316. auto shape = tensor->MutableShape();
  317. int64_t size = 1;
  318. for (auto dim : shape.GetDims()) {
  319. if (dim != 0 && INT64_MAX / dim < size) {
  320. REPORT_INNER_ERROR("E19999", "The shape:%s size overflow", shape.ToString().c_str());
  321. GELOGE(PARAM_INVALID, "[Check][Overflow] The shape size overflow");
  322. return PARAM_INVALID;
  323. }
  324. size *= dim;
  325. }
  326. if (size > max_size) {
  327. max_size = size;
  328. max_shape_index = j;
  329. }
  330. }
  331. UpdateShapeAndDType(src.at(max_shape_index), dst);
  332. return GRAPH_SUCCESS;
  333. }
  334. Status InferShapePass::OnSuspendNodesLeaked() {
  335. auto iter = graphs_2_suspend_nodes_.find(GetCurrentGraphName());
  336. if (iter == graphs_2_suspend_nodes_.end()) {
  337. GELOGI("Current graph %s no suspend node.", GetCurrentGraphName().c_str());
  338. return SUCCESS;
  339. }
  340. if (!iter->second.nodes.empty()) {
  341. AddNodeResume(iter->second.PopSuspendedNode());
  342. }
  343. return SUCCESS;
  344. }
  345. } // namespace ge

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