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.

shape_inference_engine.cc 16 kB

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
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
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. /**
  2. * Copyright 2019-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 "hybrid/executor/worker/shape_inference_engine.h"
  17. #include "graph/shape_refiner.h"
  18. #include "graph/utils/node_utils.h"
  19. #include "graph/utils/tensor_utils.h"
  20. #include "graph/utils/type_utils.h"
  21. #include "common/math/math_util.h"
  22. #include "hybrid/node_executor/node_executor.h"
  23. namespace ge {
  24. namespace {
  25. const int kAlignment = 32;
  26. }
  27. namespace hybrid {
  28. ShapeInferenceEngine::ShapeInferenceEngine(GraphExecutionContext *execution_context, SubgraphContext *subgraph_context)
  29. : execution_context_(execution_context),
  30. subgraph_context_(subgraph_context) {
  31. }
  32. Status ShapeInferenceEngine::InferShape(NodeState &node_state) {
  33. // Wait for all input shape become valid
  34. GE_CHK_STATUS_RET_NOLOG(node_state.GetShapeInferenceState().AwaitShapesReady(*execution_context_));
  35. auto &node_item = *node_state.GetNodeItem();
  36. // Wait for "const input nodes" if node's shape inference function requires any.
  37. // Even if output shape is static, there are cases that the const-input will be used in OpTiling and Execution
  38. GE_CHK_STATUS_RET_NOLOG(AwaitDependentNodes(node_state));
  39. if (node_item.is_output_shape_static && !node_item.is_need_force_infershape) {
  40. return SUCCESS;
  41. }
  42. const auto &guard = node_item.MutexGuard("InferShape");
  43. if (node_item.fused_subgraph != nullptr) {
  44. GE_CHK_STATUS_RET_NOLOG(InferShapeForSubgraph(node_item, *node_item.fused_subgraph));
  45. GE_CHK_STATUS_RET_NOLOG(CalcOutputTensorSizes(node_item));
  46. return SUCCESS;
  47. }
  48. (void)guard;
  49. // Skip shape inference for node of type DEPEND_COMPUTE
  50. if (node_item.shape_inference_type == DEPEND_COMPUTE) {
  51. GELOGD("[%s] Skipping node with unknown shape type DEPEND_COMPUTE", node_item.NodeName().c_str());
  52. return SUCCESS;
  53. }
  54. // Clear shape range in case shape inference func forgot to do it
  55. if (node_item.shape_inference_type == DEPEND_SHAPE_RANGE) {
  56. // in case InferFunc forgot to reset output shape
  57. for (auto &output_desc : node_item.op_desc->GetAllOutputsDescPtr()) {
  58. output_desc->SetShape(GeShape({UNKNOWN_DIM_NUM}));
  59. }
  60. }
  61. // Do shape inference
  62. // Skipping infer shape of input node.
  63. GELOGD("[%s] Start to invoke InferShapeAndType", node_item.NodeName().c_str());
  64. if (!node_state.MaySkipShapeInference()) {
  65. RECORD_SHAPE_INFERENCE_EVENT(execution_context_, node_item.NodeName().c_str(), "[InferShapeAndType] Start");
  66. GE_CHK_STATUS_RET(ShapeRefiner::InferShapeAndTypeForRunning(node_item.node, true),
  67. "[Invoke][InferShapeAndType] for %s failed.", node_item.NodeName().c_str());
  68. RECORD_SHAPE_INFERENCE_EVENT(execution_context_, node_item.NodeName().c_str(), "[InferShapeAndType] End");
  69. }
  70. // update output tensor sizes after shape inference
  71. // error if shape is still unknown and not of type DEPEND_SHAPE_RANGE
  72. RECORD_COMPILE_EVENT(execution_context_, node_item.NodeName().c_str(), "[CalcOpRunningParam] Start");
  73. GE_CHK_STATUS_RET_NOLOG(CalcOutputTensorSizes(node_item, node_item.shape_inference_type == DEPEND_SHAPE_RANGE));
  74. RECORD_COMPILE_EVENT(execution_context_, node_item.NodeName().c_str(), "[CalcOpRunningParam] End");
  75. GELOGD("[%s] [HybridTrace] After shape inference. Node = %s",
  76. node_item.NodeName().c_str(),
  77. node_item.DebugString().c_str());
  78. GELOGD("[%s] InferShapeAndType finished successfully.", node_item.NodeName().c_str());
  79. return SUCCESS;
  80. }
  81. Status ShapeInferenceEngine::AwaitDependentNodes(NodeState &node_state) {
  82. auto &node_item = *node_state.GetNodeItem();
  83. for (auto &src_node : node_item.dependents_for_shape_inference) {
  84. GELOGI("[%s] Start to wait for data dependent node: %s",
  85. node_item.NodeName().c_str(),
  86. src_node->GetName().c_str());
  87. RECORD_SHAPE_INFERENCE_EVENT(execution_context_,
  88. node_item.NodeName().c_str(),
  89. "[AwaitNodeDone] [%s] Start",
  90. src_node->GetName().c_str());
  91. HYBRID_CHK_STATUS_RET(subgraph_context_->Await(src_node), "[%s] Await node failed.", src_node->GetName().c_str());
  92. RECORD_SHAPE_INFERENCE_EVENT(execution_context_,
  93. node_item.NodeName().c_str(),
  94. "[AwaitNodeDone] [%s] End",
  95. src_node->GetName().c_str());
  96. GELOGI("[%s] Done waiting node.", src_node->GetName().c_str());
  97. }
  98. return SUCCESS;
  99. }
  100. Status ShapeInferenceEngine::PropagateOutputShapes(NodeState &node_state) {
  101. auto &node_item = *node_state.GetNodeItem();
  102. if (node_item.is_output_shape_static) {
  103. return SUCCESS;
  104. }
  105. // output shape will not be valid until compute is done.
  106. bool shape_is_future =
  107. node_item.shape_inference_type == DEPEND_SHAPE_RANGE || node_item.shape_inference_type == DEPEND_COMPUTE;
  108. GELOGD("[%s] Start to propagate output shapes. shape_type = %d",
  109. node_item.NodeName().c_str(),
  110. node_item.shape_inference_type);
  111. RECORD_SHAPE_INFERENCE_EVENT(execution_context_, node_item.NodeName().c_str(), "[PropagateOutputShapes] Start");
  112. // propagate each output
  113. const auto &guard = node_item.MutexGuard("PropagateOutputShapes");
  114. for (int i = 0; i < node_item.num_outputs; ++i) {
  115. auto output_desc = node_item.MutableOutputDesc(i);
  116. auto &output_nodes = node_item.outputs[i];
  117. // propagate output to all sub-inputs
  118. for (auto &dst_input_index_and_node : output_nodes) {
  119. auto &dst_node_item = dst_input_index_and_node.second;
  120. auto dst_node_state = subgraph_context_->GetOrCreateNodeState(dst_node_item);
  121. GE_CHECK_NOTNULL(dst_node_state);
  122. GELOGI("[%s] Update dst node [%s], input index = %d",
  123. node_item.NodeName().c_str(),
  124. dst_node_item->NodeName().c_str(),
  125. dst_input_index_and_node.first);
  126. // in case type 3 and 4, shape will be valid after computing is done
  127. auto &infer_state = dst_node_state->GetShapeInferenceState();
  128. if (shape_is_future) {
  129. ShapeFuture future(&node_state, i, subgraph_context_);
  130. infer_state.UpdateInputShapeFuture(dst_input_index_and_node.first, std::move(future));
  131. } else {
  132. GE_CHK_STATUS_RET_NOLOG(infer_state.UpdateInputShape(dst_input_index_and_node.first, *output_desc));
  133. }
  134. }
  135. }
  136. (void)guard;
  137. RECORD_SHAPE_INFERENCE_EVENT(execution_context_, node_item.NodeName().c_str(), "[PropagateOutputShapes] End");
  138. GELOGD("[%s] Propagating output shapes finished successfully.", node_item.NodeName().c_str());
  139. return SUCCESS;
  140. }
  141. Status ShapeInferenceEngine::InferShapeForSubgraph(const NodeItem &node_item, const FusedSubgraph &fused_subgraph) {
  142. GELOGD("[%s] Start to infer shape by fused subgraph", node_item.NodeName().c_str());
  143. for (auto &it : fused_subgraph.input_mapping) {
  144. auto parent_tensor_desc = node_item.MutableInputDesc(it.first);
  145. GE_CHECK_NOTNULL(parent_tensor_desc);
  146. GELOGD("Start to update shape by input[%d]", it.first);
  147. GELOGD("Update shape to [%s]", parent_tensor_desc->GetShape().ToString().c_str());
  148. GELOGD("Update original shape to [%s]", parent_tensor_desc->GetOriginShape().ToString().c_str());
  149. for (auto &tensor_desc : it.second) {
  150. tensor_desc->SetShape(parent_tensor_desc->GetShape());
  151. tensor_desc->SetOriginShape(parent_tensor_desc->GetOriginShape());
  152. }
  153. }
  154. for (auto &node : fused_subgraph.nodes) {
  155. GELOGD("[%s] Start to invoke InferShapeAndType", node->GetName().c_str());
  156. GE_CHK_STATUS_RET(ShapeRefiner::InferShapeAndType(node));
  157. GELOGD("[%s] Done invoking InferShapeAndType", node->GetName().c_str());
  158. GE_CHK_STATUS_RET(UpdatePeerNodeShape(*node),
  159. "[Update][PeerNodeShape] failed for [%s].", node->GetName().c_str());
  160. }
  161. for (auto &it : fused_subgraph.output_mapping) {
  162. int parent_output_idx = it.first;
  163. const auto &op_desc = it.second;
  164. GELOGD("Update parent output[%d] by [%s]", parent_output_idx, op_desc->GetName().c_str());
  165. auto input_desc = op_desc->MutableInputDesc(0);
  166. GE_CHECK_NOTNULL(input_desc);
  167. auto parent_output_tensor_desc = node_item.MutableOutputDesc(parent_output_idx);
  168. GE_CHECK_NOTNULL(parent_output_tensor_desc);
  169. GELOGD("Update shape to [%s]", input_desc->GetShape().ToString().c_str());
  170. GELOGD("Update original shape to [%s]", input_desc->GetOriginShape().ToString().c_str());
  171. parent_output_tensor_desc->SetOriginShape(input_desc->GetOriginShape());
  172. parent_output_tensor_desc->SetShape(input_desc->GetShape());
  173. }
  174. GELOGD("[%s] Done shape inference by subgraph successfully.", node_item.NodeName().c_str());
  175. return SUCCESS;
  176. }
  177. Status ShapeInferenceEngine::UpdatePeerNodeShape(const Node &node) {
  178. auto op_desc = node.GetOpDesc();
  179. for (const auto &out_anchor : node.GetAllOutDataAnchors()) {
  180. auto output_tensor = op_desc->MutableOutputDesc(out_anchor->GetIdx());
  181. for (const auto &peer_anchor : out_anchor->GetPeerInDataAnchors()) {
  182. auto peer_node = peer_anchor->GetOwnerNode();
  183. GE_CHECK_NOTNULL(peer_node);
  184. auto peer_op_desc = peer_node->GetOpDesc();
  185. GE_CHECK_NOTNULL(peer_op_desc);
  186. auto peer_input_desc = peer_op_desc->MutableInputDesc(peer_anchor->GetIdx());
  187. if (peer_input_desc == nullptr) {
  188. GELOGE(GRAPH_FAILED, "[Call][MutableInputDesc] for %s return nullptr.", peer_op_desc->GetName().c_str());
  189. REPORT_CALL_ERROR("E19999", "%s call MutableInputDesc return nullptr.", peer_op_desc->GetName().c_str());
  190. continue;
  191. }
  192. GELOGI("Peer input op desc name is %s, need to flush: shape size is %zu, datatype is %d, original datatype is %d",
  193. peer_anchor->GetOwnerNode()->GetOpDesc()->GetName().c_str(),
  194. output_tensor->GetShape().GetDimNum(), output_tensor->GetDataType(),
  195. output_tensor->GetOriginDataType());
  196. peer_input_desc->SetOriginShape(output_tensor->GetOriginShape());
  197. peer_input_desc->SetShape(output_tensor->GetShape());
  198. GELOGI("Peer input op desc name is %s, shape size is %zu, datatype is %d, original datatype is %d",
  199. peer_anchor->GetOwnerNode()->GetOpDesc()->GetName().c_str(),
  200. peer_input_desc->GetShape().GetDimNum(), peer_input_desc->GetDataType(),
  201. peer_input_desc->GetOriginDataType());
  202. }
  203. }
  204. return SUCCESS;
  205. }
  206. Status ShapeInferenceEngine::CanonicalizeShape(GeTensorDesc &tensor_desc,
  207. std::vector<int64_t> &shape,
  208. bool fallback_with_range) {
  209. const auto &tensor_shape = tensor_desc.MutableShape();
  210. if (tensor_shape.IsUnknownShape()) {
  211. if (!fallback_with_range) {
  212. GELOGE(INTERNAL_ERROR,
  213. "[Is][UnknownShape] Output shape is still unknown after shape inference. shape = [%s].",
  214. tensor_shape.ToString().c_str());
  215. REPORT_INNER_ERROR("E19999", "Output shape is still unknown after shape inference. shape = [%s].",
  216. tensor_shape.ToString().c_str());
  217. return INTERNAL_ERROR;
  218. }
  219. GELOGD("Calc output size by range");
  220. std::vector<std::pair<int64_t, int64_t>> shape_range;
  221. GE_CHK_GRAPH_STATUS_RET(tensor_desc.GetShapeRange(shape_range), "Failed to get shape range");
  222. if (shape_range.size() != shape.size()) {
  223. GELOGE(INTERNAL_ERROR, "[Check][Size] Number of shape ranges (%zu) mismatches that of dims (%zu).",
  224. shape_range.size(), shape.size());
  225. REPORT_INNER_ERROR("E19999", "Number of shape ranges (%zu) mismatches that of dims (%zu)",
  226. shape_range.size(), shape.size());
  227. return INTERNAL_ERROR;
  228. }
  229. for (size_t dim_index = 0; dim_index < shape.size(); ++dim_index) {
  230. if (shape[dim_index] == ge::UNKNOWN_DIM) {
  231. shape[dim_index] = shape_range[dim_index].second;
  232. }
  233. }
  234. GELOGD("After canonicalization, shape = [%s], before = [%s]",
  235. GeShape(shape).ToString().c_str(),
  236. tensor_shape.ToString().c_str());
  237. }
  238. return SUCCESS;
  239. }
  240. Status ShapeInferenceEngine::CalcTensorSize(DataType data_type,
  241. const std::vector<int64_t> &shape,
  242. int64_t &tensor_size) {
  243. GELOGD("To calc tensor size by shape = [%s]", GeShape(shape).ToString().c_str());
  244. uint32_t type_size;
  245. if (!TypeUtils::GetDataTypeLength(data_type, type_size)) {
  246. GELOGE(INTERNAL_ERROR, "[Get][DataTypeLength] failed for type:%s.",
  247. TypeUtils::DataTypeToSerialString(data_type).c_str());
  248. REPORT_CALL_ERROR("E19999", "GetDataTypeLength failed for type:%s.",
  249. TypeUtils::DataTypeToSerialString(data_type).c_str());
  250. return INTERNAL_ERROR;
  251. }
  252. tensor_size = type_size;
  253. for (const auto &dim : shape) {
  254. GE_CHECK_GE(dim, 0);
  255. GE_CHK_STATUS_RET(Int64MulCheckOverflow(tensor_size, dim), "[Check][Overflow] Shape size overflow, shape = [%s]",
  256. GeShape(shape).ToString().c_str());
  257. tensor_size *= dim;
  258. }
  259. GE_CHK_STATUS_RET(CheckInt64AddOverflow(tensor_size, kAlignment - 1),
  260. "[Check][Overflow]Tensor size is too large:%ld, shape = [%s]"
  261. "Shape size will overflow when add align.",
  262. tensor_size, GeShape(shape).ToString().c_str());
  263. tensor_size = (tensor_size + kAlignment - 1) / kAlignment * kAlignment;
  264. return SUCCESS;
  265. }
  266. Status ShapeInferenceEngine::CalcOutputTensorSizes(const NodeItem &node_item, bool fallback_with_range) {
  267. auto op_desc = node_item.GetOpDesc();
  268. for (size_t output_index = 0; output_index < op_desc->GetOutputsSize(); ++output_index) {
  269. auto tensor_desc = op_desc->MutableOutputDesc(output_index);
  270. GE_CHECK_NOTNULL(tensor_desc);
  271. const auto &shape = tensor_desc->MutableShape();
  272. // modify on copy
  273. auto dims = shape.GetDims();
  274. auto status_result = CanonicalizeShape(*tensor_desc, dims, fallback_with_range);
  275. if (status_result != SUCCESS) {
  276. REPORT_CALL_ERROR("E19999", "CanonicalizeShape failed, node:%s, output:%zu.",
  277. node_item.NodeName().c_str(), output_index);
  278. GELOGE(ge::FAILED, "[Canonicalize][Shape] failed for [%s], output %zu.",
  279. node_item.NodeName().c_str(), output_index);
  280. return status_result;
  281. }
  282. int64_t tensor_size;
  283. status_result = CalcTensorSize(tensor_desc->GetDataType(), dims, tensor_size);
  284. if (status_result != SUCCESS) {
  285. REPORT_CALL_ERROR("E19999", "Invoke CalcTensorSize failed, node:%s, output:%zu.",
  286. node_item.NodeName().c_str(), output_index);
  287. GELOGE(ge::FAILED, "[Calc][TensorSize] failed for [%s], output %zu.",
  288. node_item.NodeName().c_str(), output_index);
  289. return status_result;
  290. }
  291. GELOGD("[%s] Tensor size of output %zu = %ld", node_item.NodeName().c_str(), output_index, tensor_size);
  292. (void) TensorUtils::SetSize(*tensor_desc, tensor_size);
  293. }
  294. return SUCCESS;
  295. }
  296. } // namespace hybrid
  297. } // namespace ge

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