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

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