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.

node_item.cc 17 kB

4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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/model/node_item.h"
  17. #include "graph/compute_graph.h"
  18. #include "graph/debug/ge_attr_define.h"
  19. #include "hybrid/executor/worker/shape_inference_engine.h"
  20. #include "hybrid/node_executor/node_executor.h"
  21. namespace ge {
  22. namespace hybrid {
  23. namespace {
  24. const char *const kAttrNameOriginalFusionGraph = "_original_fusion_graph";
  25. const char *const kNodeTypeRetVal = "_RetVal";
  26. const std::set<std::string> kControlOpTypes{
  27. IF, STATELESSIF, CASE, WHILE, STATELESSWHILE
  28. };
  29. const std::set<std::string> kControlFlowOpTypes{
  30. STREAMACTIVE, STREAMSWITCH, STREAMSWITCHN, ENTER, REFENTER, NEXTITERATION, REFNEXTITERATION, EXIT, REFEXIT,
  31. LABELGOTO, LABELGOTOEX, LABELSWITCH, LABELSWITCHBYINDEX
  32. };
  33. const std::set<std::string> kMergeOpTypes{
  34. MERGE, REFMERGE, STREAMMERGE
  35. };
  36. Status ParseInputMapping(Node &node, OpDesc &op_desc, FusedSubgraph &fused_subgraph) {
  37. uint32_t parent_index = 0;
  38. if (!AttrUtils::GetInt(op_desc, ATTR_NAME_PARENT_NODE_INDEX, parent_index)) {
  39. GELOGE(FAILED, "[Invoke][GetInt][%s] Failed to get attr [%s]",
  40. op_desc.GetName().c_str(), ATTR_NAME_PARENT_NODE_INDEX.c_str());
  41. REPORT_CALL_ERROR("E19999", "[%s] Failed to get attr [%s]",
  42. op_desc.GetName().c_str(), ATTR_NAME_PARENT_NODE_INDEX.c_str());
  43. return FAILED;
  44. }
  45. for (auto &node_and_anchor : node.GetOutDataNodesAndAnchors()) {
  46. auto dst_op_desc = node_and_anchor.first->GetOpDesc();
  47. GE_CHECK_NOTNULL(dst_op_desc);
  48. auto in_idx = node_and_anchor.second->GetIdx();
  49. auto tensor_desc = dst_op_desc->MutableInputDesc(in_idx);
  50. fused_subgraph.input_mapping[static_cast<int>(parent_index)].emplace_back(tensor_desc);
  51. GELOGD("Input[%u] mapped to [%s:%u]", parent_index, dst_op_desc->GetName().c_str(), in_idx);
  52. }
  53. return SUCCESS;
  54. }
  55. Status ParseOutputMapping(const OpDescPtr &op_desc, FusedSubgraph &fused_subgraph) {
  56. uint32_t parent_index = 0;
  57. if (!AttrUtils::GetInt(op_desc, ATTR_NAME_PARENT_NODE_INDEX, parent_index)) {
  58. GELOGE(FAILED, "[Invoke][GetInt][%s] Failed to get attr [%s]",
  59. op_desc->GetName().c_str(), ATTR_NAME_PARENT_NODE_INDEX.c_str());
  60. REPORT_CALL_ERROR("E19999", "[%s] Failed to get attr [%s].",
  61. op_desc->GetName().c_str(), ATTR_NAME_PARENT_NODE_INDEX.c_str());
  62. return FAILED;
  63. }
  64. fused_subgraph.output_mapping.emplace(static_cast<int>(parent_index), op_desc);
  65. return SUCCESS;
  66. }
  67. Status ParseFusedSubgraph(NodeItem &node_item) {
  68. if (!node_item.op_desc->HasAttr(kAttrNameOriginalFusionGraph)) {
  69. return SUCCESS;
  70. }
  71. GELOGI("[%s] Start to parse fused subgraph.", node_item.node_name.c_str());
  72. auto fused_subgraph = std::unique_ptr<FusedSubgraph>(new(std::nothrow)FusedSubgraph());
  73. GE_CHECK_NOTNULL(fused_subgraph);
  74. ComputeGraphPtr fused_graph;
  75. (void) AttrUtils::GetGraph(*node_item.op_desc, kAttrNameOriginalFusionGraph, fused_graph);
  76. GE_CHECK_NOTNULL(fused_graph);
  77. fused_graph->SetGraphUnknownFlag(true);
  78. fused_subgraph->graph = fused_graph;
  79. GE_CHK_GRAPH_STATUS_RET(fused_graph->TopologicalSorting());
  80. for (auto &node : fused_graph->GetAllNodes()) {
  81. GE_CHECK_NOTNULL(node);
  82. auto op_desc = node->GetOpDesc();
  83. GE_CHECK_NOTNULL(op_desc);
  84. const std::string node_type = NodeUtils::GetNodeType(node);
  85. if (node_type == DATA) {
  86. GE_CHK_GRAPH_STATUS_RET(ParseInputMapping(*node, *op_desc, *fused_subgraph));
  87. } else if (node_type == kNodeTypeRetVal) {
  88. GE_CHK_GRAPH_STATUS_RET(ParseOutputMapping(op_desc, *fused_subgraph));
  89. } else {
  90. fused_subgraph->nodes.emplace_back(node);
  91. }
  92. }
  93. node_item.fused_subgraph = std::move(fused_subgraph);
  94. GELOGI("[%s] Done parsing fused subgraph successfully.", node_item.NodeName().c_str());
  95. return SUCCESS;
  96. }
  97. } // namespace
  98. bool IsControlFlowV2Op(const std::string &op_type) {
  99. return kControlOpTypes.count(op_type) > 0;
  100. }
  101. NodeItem::NodeItem(NodePtr node) : node(std::move(node)) {
  102. this->op_desc = this->node->GetOpDesc().get();
  103. this->node_name = this->node->GetName();
  104. this->node_type = this->node->GetType();
  105. }
  106. Status NodeItem::Create(const NodePtr &node, std::unique_ptr<NodeItem> &node_item) {
  107. GE_CHECK_NOTNULL(node);
  108. GE_CHECK_NOTNULL(node->GetOpDesc());
  109. std::unique_ptr<NodeItem> instance(new(std::nothrow)NodeItem(node));
  110. GE_CHECK_NOTNULL(instance);
  111. GE_CHK_STATUS_RET(instance->Init(), "[Invoke][Init]Failed to init NodeItem [%s] .", node->GetName().c_str());
  112. node_item = std::move(instance);
  113. return SUCCESS;
  114. }
  115. void NodeItem::ResolveOptionalInputs() {
  116. if (op_desc->GetAllInputsSize() != op_desc->GetInputsSize()) {
  117. has_optional_inputs = true;
  118. for (size_t i = 0; i < op_desc->GetAllInputsSize(); ++i) {
  119. const auto &input_desc = op_desc->MutableInputDesc(i);
  120. if (input_desc == nullptr) {
  121. GELOGD("[%s] Input[%zu] is optional and invalid", NodeName().c_str(), i);
  122. } else {
  123. input_desc_indices_.emplace_back(static_cast<uint32_t>(i));
  124. }
  125. }
  126. }
  127. }
  128. Status NodeItem::InitInputsAndOutputs() {
  129. GE_CHECK_LE(op_desc->GetInputsSize(), INT32_MAX);
  130. GE_CHECK_LE(op_desc->GetOutputsSize(), INT32_MAX);
  131. num_inputs = static_cast<int>(op_desc->GetInputsSize());
  132. num_outputs = static_cast<int>(op_desc->GetOutputsSize());
  133. if (AttrUtils::GetInt(op_desc, ::ge::ATTR_STAGE_LEVEL, group)) {
  134. GELOGD("[%s] Got stage level from op_desc = %d", op_desc->GetName().c_str(), group);
  135. } else {
  136. if (node->GetOwnerComputeGraph() != nullptr) {
  137. if (AttrUtils::GetInt(node->GetOwnerComputeGraph(), ::ge::ATTR_STAGE_LEVEL, group)) {
  138. GELOGD("[%s] Got stage level from parent graph = %d", op_desc->GetName().c_str(), group);
  139. } else {
  140. auto parent_node = node->GetOwnerComputeGraph()->GetParentNode();
  141. if ((parent_node != nullptr) && (AttrUtils::GetInt(parent_node->GetOpDesc(), ::ge::ATTR_STAGE_LEVEL, group))) {
  142. GELOGD("[%s] Got stage level from parent node = %d", op_desc->GetName().c_str(), group);
  143. } else {
  144. GELOGD("[%s] Node do not set stage level", op_desc->GetName().c_str());
  145. }
  146. }
  147. }
  148. }
  149. ResolveOptionalInputs();
  150. return SUCCESS;
  151. }
  152. Status NodeItem::ResolveDynamicState() {
  153. (void) AttrUtils::GetBool(op_desc, ATTR_NAME_FORCE_UNKNOWN_SHAPE, is_dynamic);
  154. GELOGD("Node name is %s, dynamic state is %d.", this->node_name.c_str(), is_dynamic);
  155. if (!is_dynamic) {
  156. GE_CHK_STATUS_RET(NodeUtils::GetNodeUnknownShapeStatus(*node, is_dynamic),
  157. "[Invoke][GetNodeUnknownShapeStatus][%s] Failed to get shape status.",
  158. node->GetName().c_str());
  159. }
  160. return SUCCESS;
  161. }
  162. Status NodeItem::ResolveStaticInputsAndOutputs() {
  163. for (int i = 0; i < num_inputs; ++i) {
  164. // Data has unconnected input but set by framework
  165. if (node_type != DATA) {
  166. int origin_index = i;
  167. if (has_optional_inputs) {
  168. origin_index = input_desc_indices_[i];
  169. }
  170. auto in_data_anchor = node->GetInDataAnchor(origin_index);
  171. GE_CHECK_NOTNULL(in_data_anchor);
  172. // If no node was connected to the current input anchor
  173. // increase num_static_input_shapes in case dead wait in ShapeInferenceState::AwaitShapesReady
  174. if (in_data_anchor->GetPeerOutAnchor() == nullptr ||
  175. in_data_anchor->GetPeerOutAnchor()->GetOwnerNode() == nullptr) {
  176. num_static_input_shapes++;
  177. is_input_shape_static_.push_back(true);
  178. GELOGW("[%s] Peer node of input[%d] is empty", NodeName().c_str(), i);
  179. continue;
  180. }
  181. }
  182. const auto &input_desc = MutableInputDesc(i);
  183. GE_CHECK_NOTNULL(input_desc);
  184. if (input_desc->MutableShape().IsUnknownShape()) {
  185. is_input_shape_static_.push_back(false);
  186. } else {
  187. num_static_input_shapes++;
  188. is_input_shape_static_.push_back(true);
  189. GELOGD("[%s] The shape of input[%d] is static. shape = [%s]",
  190. NodeName().c_str(), i, input_desc->MutableShape().ToString().c_str());
  191. }
  192. }
  193. for (int i = 0; i < num_outputs; ++i) {
  194. const auto &output_desc = op_desc->MutableOutputDesc(i);
  195. GE_CHECK_NOTNULL(output_desc);
  196. if (output_desc->MutableShape().IsUnknownShape()) {
  197. is_output_shape_static = false;
  198. break;
  199. }
  200. }
  201. if (is_output_shape_static) {
  202. GE_CHK_STATUS_RET_NOLOG(ShapeInferenceEngine::CalcOutputTensorSizes(*this));
  203. }
  204. return SUCCESS;
  205. }
  206. void NodeItem::ResolveUnknownShapeType() {
  207. if (IsControlFlowV2Op() || (is_dynamic && node_type == PARTITIONEDCALL)) {
  208. shape_inference_type = DEPEND_COMPUTE;
  209. } else {
  210. int32_t unknown_shape_type_val = 0;
  211. (void) AttrUtils::GetInt(op_desc, ::ge::ATTR_NAME_UNKNOWN_SHAPE_TYPE, unknown_shape_type_val);
  212. shape_inference_type = static_cast<UnknowShapeOpType>(unknown_shape_type_val);
  213. }
  214. }
  215. Status NodeItem::Init() {
  216. is_ctrl_flow_v2_op_ = ge::hybrid::IsControlFlowV2Op(node_type);
  217. is_ctrl_flow_op_ = kControlFlowOpTypes.count(node_type) > 0;
  218. is_merge_op_ = kMergeOpTypes.count(node_type) > 0;
  219. is_root_node_ = node->GetInAllNodes().empty();
  220. GE_CHK_STATUS_RET_NOLOG(InitInputsAndOutputs());
  221. GE_CHK_STATUS_RET_NOLOG(ResolveDynamicState());
  222. ResolveUnknownShapeType();
  223. if (is_dynamic) {
  224. GE_CHK_STATUS_RET_NOLOG(ResolveStaticInputsAndOutputs());
  225. GE_CHK_STATUS_RET(ParseFusedSubgraph(*this),
  226. "[Invoke][ParseFusedSubgraph][%s] Failed to parse fused subgraph", node_name.c_str());
  227. }
  228. copy_mu_ = MakeShared<std::mutex>();
  229. GE_CHECK_NOTNULL(copy_mu_);
  230. return SUCCESS;
  231. }
  232. bool NodeItem::IsHcclOp() const {
  233. return NodeExecutorManager::GetInstance().ResolveExecutorType(*node) == NodeExecutorManager::ExecutorType::HCCL;
  234. }
  235. std::string NodeItem::DebugString() const {
  236. std::stringstream ss;
  237. ss << "Node: ";
  238. ss << "id = " << node_id;
  239. ss << ", name = [" << node->GetName();
  240. ss << "], type = " << node->GetType();
  241. ss << ", is_dynamic = " << (is_dynamic ? "True" : "False");
  242. ss << ", is_output_static = " << (is_output_shape_static ? "True" : "False");
  243. ss << ", unknown_shape_op_type = " << shape_inference_type;
  244. ss << ", stage = " << group;
  245. ss << ", input_start = " << input_start;
  246. ss << ", num_inputs = " << num_inputs;
  247. ss << ", output_start = " << output_start;
  248. ss << ", num_outputs = " << num_outputs;
  249. ss << ", dependent_nodes = [";
  250. for (const auto &dep_node : dependents_for_shape_inference) {
  251. ss << dep_node->GetName() << ", ";
  252. }
  253. ss << "]";
  254. int index = 0;
  255. for (auto &items : outputs) {
  256. ss << ", output[" << index++ << "]: ";
  257. for (auto &item : items) {
  258. ss << "(" << item.second->NodeName() << ":" << item.first << "), ";
  259. }
  260. }
  261. return ss.str();
  262. }
  263. void NodeItem::SetToDynamic() {
  264. num_static_input_shapes = 0;
  265. is_dynamic = true;
  266. for (size_t i = 0; i < is_input_shape_static_.size(); ++i) {
  267. is_input_shape_static_[i] = false;
  268. }
  269. if (kernel_task != nullptr && !kernel_task->IsSupportDynamicShape()) {
  270. GELOGD("[%s] Dynamic shape is not supported, clear node task.", node_name.c_str());
  271. kernel_task = nullptr;
  272. }
  273. }
  274. GeTensorDescPtr NodeItem::DoGetInputDesc(int index) const {
  275. if (!has_optional_inputs) {
  276. return op_desc->MutableInputDesc(static_cast<uint32_t>(index));
  277. }
  278. if (index < 0 || index >= num_inputs) {
  279. GELOGE(PARAM_INVALID, "[Check][Param:index][%s] Invalid input index, num inputs = %d, index = %d",
  280. node_name.c_str(), num_inputs, index);
  281. REPORT_INNER_ERROR("E19999", "Invalid input index, node:%s num inputs = %d, index = %d",
  282. node_name.c_str(), num_inputs, index);
  283. return nullptr;
  284. }
  285. return op_desc->MutableInputDesc(input_desc_indices_[index]);
  286. }
  287. GeTensorDescPtr NodeItem::MutableInputDesc(int index) const {
  288. std::lock_guard<std::mutex> lk(mu_);
  289. return DoGetInputDesc(index);
  290. }
  291. Status NodeItem::GetInputDesc(int index, GeTensorDesc &tensor_desc) const {
  292. std::lock_guard<std::mutex> lk(mu_);
  293. auto input_desc = DoGetInputDesc(index);
  294. GE_CHECK_NOTNULL(input_desc);
  295. tensor_desc = *input_desc;
  296. return SUCCESS;
  297. }
  298. Status NodeItem::GetOutputDesc(int index, GeTensorDesc &tensor_desc) const {
  299. std::lock_guard<std::mutex> lk(mu_);
  300. auto output_desc = op_desc->MutableOutputDesc(static_cast<uint32_t>(index));
  301. GE_CHECK_NOTNULL(output_desc);
  302. tensor_desc = *output_desc;
  303. return SUCCESS;
  304. }
  305. GeTensorDescPtr NodeItem::MutableOutputDesc(int index) const {
  306. std::lock_guard<std::mutex> lk(mu_);
  307. return op_desc->MutableOutputDesc(static_cast<uint32_t>(index));
  308. }
  309. Status NodeItem::UpdateInputDesc(int index, const GeTensorDesc &tensor_desc) {
  310. std::lock_guard<std::mutex> lk(mu_);
  311. auto input_desc = DoGetInputDesc(index);
  312. GE_CHECK_NOTNULL(input_desc);
  313. *input_desc = tensor_desc;
  314. return SUCCESS;
  315. }
  316. Status NodeItem::GetCanonicalInputIndex(uint32_t index, int &canonical_index) const {
  317. if (!has_optional_inputs) {
  318. canonical_index = index;
  319. return SUCCESS;
  320. }
  321. auto iter = std::find(input_desc_indices_.begin(), input_desc_indices_.end(), index);
  322. if (iter == input_desc_indices_.end()) {
  323. GELOGE(INTERNAL_ERROR,
  324. "[Check][Param:index]input index:%u not in input_desc_indices_, check Invalid, node:%s",
  325. index, node_name.c_str());
  326. REPORT_INNER_ERROR("E19999", "input index:%u not in input_desc_indices_, check Invalid, node:%s",
  327. index, node_name.c_str());
  328. return INTERNAL_ERROR;
  329. }
  330. canonical_index = static_cast<int>(iter - input_desc_indices_.begin());
  331. GELOGD("[%s] Canonicalize input index from [%u] to [%d]", node_name.c_str(), index, canonical_index);
  332. return SUCCESS;
  333. }
  334. bool NodeItem::IsInputShapeStatic(int index) const {
  335. if (!is_dynamic) {
  336. return true;
  337. }
  338. if (static_cast<size_t>(index) >= is_input_shape_static_.size()) {
  339. GELOGE(PARAM_INVALID, "[Check][Param:index]Input index(%d) out of range: [0, %zu)",
  340. index, is_input_shape_static_.size());
  341. REPORT_INNER_ERROR("E19999", "Input index(%d) out of range: [0, %zu).", index, is_input_shape_static_.size());
  342. return false;
  343. }
  344. return is_input_shape_static_[index];
  345. }
  346. void NodeItem::SetDataSend(NodeItem *node_item, int anchor_index) {
  347. data_send_.emplace(node_item);
  348. node_item->data_recv_[this] = anchor_index;
  349. if (is_root_node_) {
  350. node_item->root_data_[anchor_index] = this;
  351. }
  352. // If Enter feed Not Merge, take as root Node.
  353. if (IsEnterOp() && (node_item->node_type != STREAMMERGE)) {
  354. node_item->enter_data_[anchor_index] = this;
  355. }
  356. GELOGI("Node[%s] will control node[%s]", NodeName().c_str(), node_item->NodeName().c_str());
  357. }
  358. void NodeItem::SetCtrlSend(NodeItem *node_item, uint32_t switch_index) {
  359. if (switch_index < switch_groups_.size()) {
  360. auto &switch_group = switch_groups_[switch_index];
  361. switch_group.emplace(node_item);
  362. } else {
  363. ctrl_send_.insert(node_item);
  364. }
  365. node_item->ctrl_recv_.emplace(this);
  366. if (is_root_node_) {
  367. node_item->root_ctrl_.emplace(this);
  368. }
  369. // If Enter feed control signal, take as root Node.
  370. if (IsEnterOp() && (node_item->node_type != STREAMMERGE && node_item->node_type != STREAMACTIVE)) {
  371. node_item->enter_ctrl_.emplace(this);
  372. }
  373. GELOGI("Node[%s] will control node[%s]", NodeName().c_str(), node_item->NodeName().c_str());
  374. }
  375. void NodeItem::SetMergeCtrl(NodeItem *node_item, uint32_t merge_index) {
  376. if (merge_index >= switch_groups_.size()) {
  377. GELOGE(FAILED, "[%s] group size: %zu, merge index: %u", NodeName().c_str(), switch_groups_.size(), merge_index);
  378. return;
  379. }
  380. // this is StreamMerge node, node_item is StreamActive node.
  381. auto &switch_group = switch_groups_[merge_index];
  382. switch_group.emplace(node_item);
  383. node_item->ctrl_send_.emplace(this);
  384. GELOGI("Node[%s] will control node[%s]", node_item->NodeName().c_str(), NodeName().c_str());
  385. }
  386. size_t NodeItem::GetMergeCtrl(uint32_t merge_index) const {
  387. return ((node_type == STREAMMERGE) && (merge_index < switch_groups_.size())) ? switch_groups_[merge_index].size() : 0;
  388. }
  389. OptionalMutexGuard::OptionalMutexGuard(std::mutex *mutex, const string &name) : mu_(mutex), name_(name) {
  390. if (mu_ != nullptr) {
  391. GELOGD("lock for %s", name_.c_str());
  392. mu_->lock();
  393. }
  394. }
  395. OptionalMutexGuard::~OptionalMutexGuard() {
  396. if (mu_ != nullptr) {
  397. GELOGD("unlock for %s", name_.c_str());
  398. mu_->unlock();
  399. mu_ = nullptr;
  400. }
  401. }
  402. } // namespace hybrid
  403. } // namespace ge

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