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.

dynamic_shape_partition.cc 44 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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  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 "graph/partition/dynamic_shape_partition.h"
  17. #include <algorithm>
  18. #include <iostream>
  19. #include <memory>
  20. #include <queue>
  21. #include <sstream>
  22. #include <string>
  23. #include <unordered_set>
  24. #include <vector>
  25. #include "common/ge/ge_util.h"
  26. #include "framework/common/debug/ge_log.h"
  27. #include "framework/common/debug/log.h"
  28. #include "framework/common/types.h"
  29. #include "graph/debug/ge_attr_define.h"
  30. #include "graph/utils/graph_utils.h"
  31. #include "graph/utils/op_desc_utils.h"
  32. #include "graph/common/omg_util.h"
  33. #define REQUIRE(cond, ...) \
  34. do { \
  35. if (!(cond)) { \
  36. REPORT_INNER_ERROR("E19999", __VA_ARGS__); \
  37. GELOGE(FAILED, "[Dynamic shape partition]" __VA_ARGS__); \
  38. return FAILED; \
  39. } \
  40. } while (0)
  41. #define REQUIRE_NOT_NULL(cond, ...) REQUIRE(((cond) != nullptr), __VA_ARGS__)
  42. #define REQUIRE_SUCCESS(cond, ...) REQUIRE(((cond) == SUCCESS), __VA_ARGS__)
  43. #define REQUIRE_GRAPH_SUCCESS(cond, ...) REQUIRE(((cond) == GRAPH_SUCCESS), __VA_ARGS__)
  44. namespace ge {
  45. using Cluster = DynamicShapePartitioner::Cluster;
  46. using ClusterPtr = std::shared_ptr<Cluster>;
  47. static bool IsSingleOpScene(const ComputeGraphPtr &root_graph) {
  48. for (const auto &node : root_graph->GetAllNodes()) {
  49. GE_CHECK_NOTNULL(node->GetOpDesc());
  50. // not do partition in single op scene.
  51. bool is_singleop = false;
  52. (void)AttrUtils::GetBool(node->GetOpDesc(), ATTR_SINGLE_OP_SCENE, is_singleop);
  53. if (is_singleop) {
  54. return true;
  55. }
  56. }
  57. return false;
  58. }
  59. Status DynamicShapePartitioner::Partition() {
  60. REQUIRE_NOT_NULL(root_graph_, "[Check][Param] Graph is nullptr.");
  61. if (IsSingleOpScene(root_graph_)) {
  62. GELOGD("Skip dynamic shape partition as in single op scene.");
  63. REQUIRE(AttrUtils::SetBool(*root_graph_, ATTR_NAME_DYNAMIC_SHAPE_PARTITIONED, false),
  64. "[Set][Attr] dynamic shape partitioned flag on root graph:%s failed.", root_graph_->GetName().c_str());
  65. return SUCCESS;
  66. }
  67. GELOGD("Start dynamic shape partition graph %s.", root_graph_->GetName().c_str());
  68. REQUIRE_SUCCESS(MarkUnknownShapeNodes(), "[Call][MarkUnknownShapeNodes] failed, root grah name:%s.",
  69. root_graph_->GetName().c_str());
  70. if (unknown_shape_nodes_.empty()) {
  71. GELOGD("Skip dynamic shape partition of graph %s as all nodes are known shape.", root_graph_->GetName().c_str());
  72. REQUIRE(AttrUtils::SetBool(*root_graph_, ATTR_NAME_DYNAMIC_SHAPE_PARTITIONED, false),
  73. "[Set][Attr] dynamic shape partitioned flag on root graph %s failed.", root_graph_->GetName().c_str());
  74. return SUCCESS;
  75. }
  76. REQUIRE(AttrUtils::SetBool(*root_graph_, ATTR_NAME_DYNAMIC_SHAPE_PARTITIONED, true),
  77. "[Set][Attr] dynamic shape partitioned flag on root graph %s failed.", root_graph_->GetName().c_str());
  78. REQUIRE_SUCCESS(CtrlEdgeTransfer(), "[Call][CtrlEdgeTransfer] failed, graph:%s.", root_graph_->GetName().c_str());
  79. DumpGraph("_Before_DSP");
  80. auto status = PartitionImpl();
  81. GELOGD("%s.", DebugString().c_str());
  82. if (status != SUCCESS) {
  83. GELOGE(status, "[Call][PartitionImpl] Failed dynamic shape partition graph:%s, ret:%s",
  84. root_graph_->GetName().c_str(), DebugString().c_str());
  85. }
  86. DumpGraph("_After_DSP");
  87. GELOGD("Finish dynamic shape partition graph %s.", root_graph_->GetName().c_str());
  88. ClearResource();
  89. return status;
  90. }
  91. Status DynamicShapePartitioner::CtrlEdgeTransfer() {
  92. GELOGD("Do ctrl edge transfer start!");
  93. GE_CHECK_NOTNULL(root_graph_);
  94. bool is_dynamic_shape = false;
  95. (void)AttrUtils::GetBool(root_graph_, ATTR_NAME_DYNAMIC_SHAPE_PARTITIONED, is_dynamic_shape);
  96. if (!is_dynamic_shape) {
  97. return SUCCESS;
  98. }
  99. for (auto &subgraph : root_graph_->GetAllSubgraphs()) {
  100. for (ge::NodePtr &n : subgraph->GetDirectNode()) {
  101. auto op_desc = n->GetOpDesc();
  102. if (op_desc == nullptr) {
  103. continue;
  104. }
  105. auto op_type = op_desc->GetType();
  106. if (op_type == CONSTANT || op_type == CONSTANTOP) {
  107. if (n->GetInAllNodes().empty()) {
  108. GELOGD("[CtrlEdgeTransferPass] node [%s] in nodes is empty", n->GetName().c_str());
  109. continue;
  110. }
  111. GELOGD("start to tranfer ctrl edge for const node [%s]", n->GetName().c_str());
  112. for (auto &in_control_node : n->GetInControlNodes()) {
  113. GE_CHECK_NOTNULL(in_control_node);
  114. GE_CHK_STATUS_RET(ge::GraphUtils::RemoveEdge(in_control_node->GetOutControlAnchor(),
  115. n->GetInControlAnchor()),
  116. "[Remove][Edge] between %s and %s failed",
  117. in_control_node->GetOutControlAnchor()->GetOwnerNode()->GetName().c_str(),
  118. n->GetName().c_str());
  119. for (auto &out_node : n->GetOutNodes()) {
  120. if (out_node == nullptr) {
  121. continue;
  122. }
  123. GE_CHK_STATUS_RET(ge::GraphUtils::AddEdge(in_control_node->GetOutControlAnchor(),
  124. out_node->GetInControlAnchor()),
  125. "[Add][Edge] between %s and %s failed.",
  126. in_control_node->GetOutControlAnchor()->GetOwnerNode()->GetName().c_str(),
  127. out_node->GetName().c_str());
  128. }
  129. }
  130. }
  131. }
  132. }
  133. GELOGD("Do ctrl edge transfer end!");
  134. return SUCCESS;
  135. }
  136. Status DynamicShapePartitioner::PartitionImpl() {
  137. REQUIRE_SUCCESS(root_graph_->TopologicalSorting(),
  138. "[Call][TopologicalSorting] failed, graph:%s.", root_graph_->GetName().c_str());
  139. REQUIRE_SUCCESS(InitClusters(), "[Init][Clusters] failed, graph:%s.", root_graph_->GetName().c_str());
  140. REQUIRE_SUCCESS(MergeClusters(), "[Merge][Clusters] failed, graph:%s.", root_graph_->GetName().c_str());
  141. PruneUniqueClusters();
  142. REQUIRE_SUCCESS(BuildPartitionFrame(), "[Build][PartitionFrame] failed, graph:%s.", root_graph_->GetName().c_str());
  143. REQUIRE_SUCCESS(CombinePartitionFrame(),
  144. "[Combine][PartitionFrame] failed, graph:%s.", root_graph_->GetName().c_str());
  145. REQUIRE_SUCCESS(BuildPartitionSubgraph(),
  146. "[Build][PartitionSubgraph] failed, graph:%s.", root_graph_->GetName().c_str());
  147. return SUCCESS;
  148. }
  149. void DynamicShapePartitioner::PruneUniqueClusters() {
  150. for (auto &node : root_graph_->GetDirectNode()) {
  151. auto cluster = node_2_cluster_[node];
  152. if (unique_clusters_.count(cluster) != 0) {
  153. continue;
  154. }
  155. if (unique_clusters_.insert(cluster).second) {
  156. sorted_unique_clusters_.emplace_back(cluster);
  157. }
  158. }
  159. auto comp_func = [](std::shared_ptr<Cluster> clu_a, std::shared_ptr<Cluster> clu_b) -> bool {
  160. return clu_a->Id() < clu_b->Id();
  161. };
  162. std::sort(sorted_unique_clusters_.begin(), sorted_unique_clusters_.end(), comp_func);
  163. }
  164. Status DynamicShapePartitioner::BuildPartitionFrame() {
  165. for (const auto &cluster : sorted_unique_clusters_) {
  166. REQUIRE_SUCCESS(cluster->BuildFrame(), "[Build][Frame] of cluster[%lu] failed.", cluster->Id());
  167. }
  168. return SUCCESS;
  169. }
  170. Status DynamicShapePartitioner::CombinePartitionFrame() {
  171. for (const auto &cluster : sorted_unique_clusters_) {
  172. REQUIRE_SUCCESS(cluster->CombinePartitionFrame(), "[Combine][Frame] of cluster[%lu] failed.", cluster->Id());
  173. }
  174. return SUCCESS;
  175. }
  176. Status DynamicShapePartitioner::BuildPartitionSubgraph() {
  177. for (const auto &cluster : sorted_unique_clusters_) {
  178. REQUIRE_SUCCESS(cluster->BuildPartitionSubgraph(), "[Build][SubGraph] of cluster[%lu] failed.", cluster->Id());
  179. }
  180. return SUCCESS;
  181. }
  182. std::string DynamicShapePartitioner::DebugString() const {
  183. size_t unknown = 0;
  184. size_t known = 0;
  185. size_t data = 0;
  186. size_t netoutput = 0;
  187. size_t is_inputnode = 0;
  188. size_t stage = 0;
  189. std::stringstream ss;
  190. ss << "All unknown shape nodes:" << std::endl;
  191. for (const auto &node : unknown_shape_nodes_) {
  192. ss << " [" << node->GetName() << "](" << node->GetType() << ")" << std::endl;
  193. }
  194. for (const auto &cluster : unique_clusters_) {
  195. if (cluster->IsUnknownShape()) {
  196. unknown++;
  197. } else if (cluster->IsKnownShape()) {
  198. known++;
  199. } else if (cluster->IsData()) {
  200. data++;
  201. } else if (cluster->IsNetOutput()) {
  202. netoutput++;
  203. } else if (cluster->IsInputNode()) {
  204. is_inputnode++;
  205. } else if (cluster->IsIndependent()) {
  206. stage++;
  207. }
  208. }
  209. ss << "All clusters:" << unique_clusters_.size() << ", data:" << data << ", known:" << known
  210. << ", unknown:" << unknown << ", netoutput:" << netoutput << ", is_inputnode:" << is_inputnode
  211. << ", stage:" << stage << std::endl;
  212. for (const auto &cluster : unique_clusters_) {
  213. ss << " " << cluster->DebugString() << std::endl;
  214. }
  215. return ss.str();
  216. }
  217. void DynamicShapePartitioner::DumpGraph(const std::string &suffix) {
  218. GraphUtils::DumpGEGraphToOnnx(*root_graph_, root_graph_->GetName() + suffix);
  219. for (const auto &sub_graph : root_graph_->GetAllSubgraphs()) {
  220. GraphUtils::DumpGEGraphToOnnx(*sub_graph, sub_graph->GetName() + suffix);
  221. }
  222. }
  223. void DynamicShapePartitioner::ClearResource() {
  224. for (const auto &cluster : unique_clusters_) {
  225. cluster->Clear();
  226. }
  227. node_2_cluster_.clear();
  228. ordered_cluster_.clear();
  229. unique_clusters_.clear();
  230. sorted_unique_clusters_.clear();
  231. unknown_shape_nodes_.clear();
  232. root_graph_.reset();
  233. }
  234. Status DynamicShapePartitioner::MarkUnknownShapeNodes() {
  235. for (auto &node : root_graph_->GetDirectNode()) {
  236. REQUIRE_SUCCESS(CollectSpreadUnknownShapeNodes(node),
  237. "[Call][CollectSpreadUnknownShapeNodes] for node:%s failed.", node->GetName().c_str());
  238. }
  239. return SUCCESS;
  240. }
  241. Status DynamicShapePartitioner::InitClusters() {
  242. auto graph = root_graph_;
  243. size_t rank = 0;
  244. for (const auto &node : graph->GetDirectNode()) {
  245. Cluster::Type type = Cluster::DATA;
  246. bool is_input = ((node->GetType() == CONSTANT) || (node->GetType() == CONSTANTOP)) && node->GetInNodes().empty();
  247. REQUIRE_NOT_NULL(node->GetOpDesc(), "[Get][OpDesc] op_desc is null, graph:%s", graph->GetName().c_str());
  248. if (node->GetType() == DATA) {
  249. type = Cluster::DATA;
  250. } else if (is_input) {
  251. type = Cluster::INPUT_NODE;
  252. } else if (node->GetType() == NETOUTPUT) {
  253. type = Cluster::NETOUTPUT;
  254. } else if ((node->GetType() == PARTITIONEDCALL) && (node->GetOpDesc()->HasAttr(ATTR_STAGE_LEVEL))) {
  255. type = Cluster::STAGE;
  256. } else if (unknown_shape_nodes_.count(node) > 0) {
  257. type = Cluster::UNKNOWN_SHAPE;
  258. } else {
  259. type = Cluster::KNOWN_SHAPE;
  260. }
  261. auto cluster = MakeShared<Cluster>(rank++, type, node, this);
  262. REQUIRE_NOT_NULL(cluster, "[New][Memory] for cluster failed.");
  263. node_2_cluster_[node] = cluster;
  264. if (cluster->IsUnknownShape()) {
  265. ordered_cluster_.push_back(cluster);
  266. }
  267. int64_t group_index = -1;
  268. if (AttrUtils::GetInt(node->GetOpDesc(), ATTR_NAME_CONTROL_FLOW_GROUP, group_index)) {
  269. GELOGD("[%s] is rts control flow Op, group index: %ld", node->GetName().c_str(), group_index);
  270. auto &control_cluster = control_clusters_[group_index];
  271. control_cluster.emplace_back(cluster);
  272. }
  273. // Already sorted topologically, so access to the parent cluster is safe
  274. for (const auto &parent : node->GetInAllNodes()) {
  275. cluster->AddInput(node_2_cluster_[parent]);
  276. }
  277. }
  278. for (const auto &node : graph->GetDirectNode()) {
  279. GELOGD("Make cluster for node %s : %s.", node->GetName().c_str(), node_2_cluster_[node]->DebugString().c_str());
  280. }
  281. return SUCCESS;
  282. }
  283. Status DynamicShapePartitioner::TopologicalSortClusters() {
  284. ordered_cluster_.clear();
  285. // BFS topological sort clusters for known shape cluster
  286. std::queue<ClusterPtr> ready_clusters;
  287. std::unordered_map<ClusterPtr, size_t> cluster_pending_count;
  288. std::unordered_set<ClusterPtr> seen_clusters;
  289. for (auto &node : root_graph_->GetDirectNode()) {
  290. auto &cluster = node_2_cluster_[node];
  291. if (seen_clusters.count(cluster) != 0) {
  292. continue;
  293. }
  294. seen_clusters.insert(cluster);
  295. auto pending_count = cluster->Inputs().size();
  296. if (pending_count == 0) {
  297. ready_clusters.push(cluster);
  298. } else {
  299. cluster_pending_count[cluster] = pending_count;
  300. }
  301. }
  302. size_t rank = 0;
  303. while (!ready_clusters.empty()) {
  304. auto cluster = ready_clusters.front();
  305. ready_clusters.pop();
  306. cluster->UpdateRank(rank++);
  307. if (cluster->IsKnownShape() || cluster->IsInputNode()) {
  308. ordered_cluster_.push_back(cluster);
  309. }
  310. for (const auto &out_cluster : cluster->Outputs()) {
  311. if (cluster_pending_count[out_cluster] > 0 && --cluster_pending_count[out_cluster] == 0) {
  312. ready_clusters.push(out_cluster);
  313. }
  314. }
  315. }
  316. if (rank != seen_clusters.size()) {
  317. return FAILED;
  318. }
  319. return SUCCESS;
  320. }
  321. namespace {
  322. static std::string ToString(const std::vector<ClusterPtr> &clusters) {
  323. if (clusters.empty()) {
  324. return "()";
  325. }
  326. std::stringstream ss;
  327. ss << "(";
  328. auto iter = clusters.begin();
  329. for (size_t i = 0; i < clusters.size() - 1; i++) {
  330. ss << (*iter)->Id() << ",";
  331. iter++;
  332. }
  333. ss << (*iter)->Id() << ").";
  334. return ss.str();
  335. }
  336. }
  337. void DynamicShapePartitioner::MergeClustersControlFlow() {
  338. std::unordered_set<ClusterPtr> all_merged_clusters;
  339. for (const auto &item : control_clusters_) {
  340. const auto &control_cluster = item.second;
  341. auto rit = control_cluster.rbegin();
  342. if (rit == control_cluster.rend()) {
  343. GELOGW("Invalid empty control flow cluster.");
  344. continue;
  345. }
  346. const auto &cluster = *rit;
  347. if (all_merged_clusters.count(cluster) > 0) {
  348. continue;
  349. }
  350. bool is_unknown_cluster = cluster->IsUnknownShape();
  351. for (++rit; rit != control_cluster.rend(); ++rit) {
  352. const auto &cluster_from = *rit;
  353. if (all_merged_clusters.count(cluster_from) > 0) {
  354. continue;
  355. }
  356. auto merged_clusters = cluster->MergeAllPathFrom(cluster_from);
  357. GELOGD("Merge all path cluster from %lu to %lu %s.", cluster_from->Id(), cluster->Id(),
  358. ToString(merged_clusters).c_str());
  359. for (const auto &merged_cluster : merged_clusters) {
  360. all_merged_clusters.emplace(merged_cluster);
  361. for (const auto &node : merged_cluster->Nodes()) {
  362. node_2_cluster_[node] = cluster;
  363. }
  364. }
  365. }
  366. if (!is_unknown_cluster && cluster->IsUnknownShape()) {
  367. GELOGD("Add to ordered cluster: %s", cluster->DebugString().c_str());
  368. ordered_cluster_.push_back(cluster);
  369. }
  370. }
  371. }
  372. void DynamicShapePartitioner::MergeClustersUnknownShape() {
  373. // Merge unknown shape clusters
  374. for (const auto &cluster : ordered_cluster_) {
  375. if (cluster->IsIndependent()) {
  376. continue;
  377. }
  378. for (const auto &in_cluster : cluster->Inputs()) {
  379. if (!in_cluster->IsUnknownShape()) {
  380. continue;
  381. }
  382. if (!cluster->IsAdjoinNodes(in_cluster)) {
  383. continue;
  384. }
  385. auto merged_clusters = cluster->MergeAllPathFrom(in_cluster);
  386. GELOGD("Merge all path cluster from %lu to %lu %s.", in_cluster->Id(), cluster->Id(),
  387. ToString(merged_clusters).c_str());
  388. for (const auto &merged_cluster : merged_clusters) {
  389. for (const auto &node : merged_cluster->Nodes()) {
  390. node_2_cluster_[node] = cluster;
  391. }
  392. }
  393. }
  394. }
  395. }
  396. void DynamicShapePartitioner::MergeClustersKnownShape() {
  397. // Merge known shape clusters
  398. for (const auto &cluster : ordered_cluster_) {
  399. if (cluster->IsIndependent()) {
  400. continue;
  401. }
  402. if (cluster->IsRefVariable() && cluster->Inputs().size() == 1) {
  403. auto in_cluster = *(cluster->Inputs().begin());
  404. in_cluster->Merge(cluster);
  405. node_2_cluster_[*(cluster->Nodes().begin())] = in_cluster;
  406. continue;
  407. }
  408. for (const auto &in_cluster : cluster->Inputs()) {
  409. if (!in_cluster->IsKnownShape()) {
  410. continue;
  411. }
  412. if (cluster->TryMerge(in_cluster)) {
  413. GELOGD("Success merge known shape cluster from %lu to %lu.", in_cluster->Id(), cluster->Id());
  414. for (const auto &node : in_cluster->Nodes()) {
  415. node_2_cluster_[node] = cluster;
  416. }
  417. }
  418. }
  419. }
  420. }
  421. void DynamicShapePartitioner::MergeClustersInputData() {
  422. // Merge input clusters
  423. std::shared_ptr<Cluster> cluster_pre = nullptr;
  424. for (const auto &cluster : ordered_cluster_) {
  425. if (!cluster->IsInputNode()) {
  426. continue;
  427. }
  428. if (cluster_pre != nullptr) {
  429. cluster_pre->Merge(cluster);
  430. } else {
  431. cluster_pre = cluster;
  432. }
  433. GELOGD("Success merge input node cluster from %lu to %lu.", cluster->Id(), cluster->Id());
  434. for (const auto &node : cluster->Nodes()) {
  435. node_2_cluster_[node] = cluster_pre;
  436. }
  437. }
  438. }
  439. Status DynamicShapePartitioner::MergeClusters() {
  440. MergeClustersControlFlow();
  441. MergeClustersUnknownShape();
  442. REQUIRE_SUCCESS(TopologicalSortClusters(), "[TopologicalSort][Clusters] after merge unknown shape clusters failed.");
  443. MergeClustersKnownShape();
  444. MergeClustersInputData();
  445. return SUCCESS;
  446. }
  447. bool DynamicShapePartitioner::JudgeUnknowShapeWithAttr(const OpDescPtr &opdesc) {
  448. bool is_forced_unknown = false;
  449. if (AttrUtils::GetBool(opdesc, ATTR_NAME_IS_UNKNOWN_SHAPE, is_forced_unknown) && is_forced_unknown) {
  450. GELOGD("Collect node %s as unknown as it was marked unknown forcibly.", opdesc->GetName().c_str());
  451. return true;
  452. }
  453. bool forced_unknown = false;
  454. if (AttrUtils::GetBool(opdesc, ATTR_NAME_FORCE_UNKNOWN_SHAPE, forced_unknown) && forced_unknown) {
  455. GELOGD("Collect node %s as unknown as it was marked force unknown node forcibly.", opdesc->GetName().c_str());
  456. return true;
  457. }
  458. return false;
  459. }
  460. Status DynamicShapePartitioner::CollectSpreadUnknownShapeNodes(NodePtr node) {
  461. if (unknown_shape_nodes_.count(node) > 0) {
  462. return SUCCESS;
  463. }
  464. auto opdesc = node->GetOpDesc();
  465. REQUIRE_NOT_NULL(opdesc, "[Get][OpDesc] Opdesc is nullptr.");
  466. // One can set 'ATTR_NAME_IS_UNKNOWN_SHAPE=true' on node so as to forcing the node flow into the unknown subgraph,
  467. // ignore the actual shape.
  468. if (JudgeUnknowShapeWithAttr(opdesc)) {
  469. unknown_shape_nodes_.insert(node);
  470. return SUCCESS;
  471. }
  472. size_t anchor_index = 0;
  473. bool is_unknown = false;
  474. for (auto &out_tensor : opdesc->GetAllOutputsDesc()) {
  475. if (IsUnknownShapeTensor(out_tensor)) {
  476. GELOGD("Collect node %s as unknown as output %lu is unknown.", node->GetName().c_str(), anchor_index);
  477. is_unknown = true;
  478. auto anchor = node->GetOutDataAnchor(static_cast<int>(anchor_index));
  479. for (const auto peer_anchor : anchor->GetPeerInDataAnchors()) {
  480. if (peer_anchor != nullptr) {
  481. GELOGD("Collect node %s as has unknown input from %s:%lu.", peer_anchor->GetOwnerNode()->GetName().c_str(),
  482. node->GetName().c_str(), anchor_index);
  483. unknown_shape_nodes_.insert(peer_anchor->GetOwnerNode());
  484. }
  485. }
  486. }
  487. anchor_index++;
  488. }
  489. anchor_index = 0;
  490. for (auto &in_tensor : opdesc->GetAllInputsDesc()) {
  491. if (IsUnknownShapeTensor(in_tensor)) {
  492. GELOGD("Collect node %s as unknown as input %lu is unknown.", node->GetName().c_str(), anchor_index);
  493. is_unknown = true;
  494. auto anchor = node->GetInDataAnchor(static_cast<int>(anchor_index));
  495. const auto peer_anchor = anchor->GetPeerOutAnchor();
  496. if (peer_anchor != nullptr) {
  497. GELOGD("Collect node %s as has unknown output to %s:%lu.", peer_anchor->GetOwnerNode()->GetName().c_str(),
  498. node->GetName().c_str(), anchor_index);
  499. unknown_shape_nodes_.insert(peer_anchor->GetOwnerNode());
  500. }
  501. }
  502. anchor_index++;
  503. }
  504. if (is_unknown) {
  505. unknown_shape_nodes_.insert(node);
  506. } else {
  507. auto graph = root_graph_;
  508. for (const auto &subgraph_name : opdesc->GetSubgraphInstanceNames()) {
  509. auto subgraph = graph->GetSubgraph(subgraph_name);
  510. REQUIRE_NOT_NULL(subgraph, "[Get][Subgraph] %s of node %s on root graph failed.", subgraph_name.c_str(),
  511. node->GetName().c_str());
  512. bool is_graph_unknow = false;
  513. REQUIRE_SUCCESS(IsUnknownShapeGraph(subgraph, is_graph_unknow),
  514. "[Call][IsUnknownShapeGraph] Failed check subgraph %s shape of node %s.",
  515. subgraph_name.c_str(), node->GetName().c_str());
  516. if (is_graph_unknow) {
  517. GELOGD("Collect node %s as its subgraph %s is unknown.", node->GetName().c_str(), subgraph->GetName().c_str());
  518. unknown_shape_nodes_.insert(node);
  519. break;
  520. }
  521. }
  522. }
  523. return SUCCESS;
  524. }
  525. Status DynamicShapePartitioner::IsUnknownShapeNode(NodePtr node, bool &is_unknown) {
  526. auto opdesc = node->GetOpDesc();
  527. auto graph = root_graph_;
  528. for (auto &out_tensor : opdesc->GetAllOutputsDesc()) {
  529. if (IsUnknownShapeTensor(out_tensor)) {
  530. GELOGD("Mark node %s unknown as unknown output.", node->GetName().c_str());
  531. is_unknown = true;
  532. return SUCCESS;
  533. }
  534. }
  535. for (auto &in_tensor : opdesc->GetAllInputsDesc()) {
  536. if (IsUnknownShapeTensor(in_tensor)) {
  537. GELOGD("Mark node %s unknown as unknown intput.", node->GetName().c_str());
  538. is_unknown = true;
  539. return SUCCESS;
  540. }
  541. }
  542. for (auto &subgraph_name : opdesc->GetSubgraphInstanceNames()) {
  543. auto subgraph = graph->GetSubgraph(subgraph_name);
  544. REQUIRE_NOT_NULL(subgraph, "[Get][Subgraph] %s of node %s on root graph failed.", subgraph_name.c_str(),
  545. node->GetName().c_str());
  546. REQUIRE_SUCCESS(IsUnknownShapeGraph(subgraph, is_unknown),
  547. "[Call][IsUnknownShapeGraph] Failed check subgraph %s shape of node %s.",
  548. subgraph_name.c_str(), node->GetName().c_str());
  549. if (is_unknown) {
  550. GELOGD("Mark node %s unknown as unknown subgraph.", node->GetName().c_str());
  551. return SUCCESS;
  552. }
  553. }
  554. is_unknown = false;
  555. return SUCCESS;
  556. }
  557. Status DynamicShapePartitioner::IsUnknownShapeGraph(ComputeGraphPtr graph, bool &is_unknown) {
  558. for (auto &node : graph->GetDirectNode()) {
  559. REQUIRE_SUCCESS(IsUnknownShapeNode(node, is_unknown),
  560. "[Call][IsUnknownShapeNode]Failed check node %s shape on graph %s.",
  561. node->GetName().c_str(), graph->GetName().c_str());
  562. if (is_unknown) {
  563. GELOGD("Mark graph %s unknown as contains unknown node %s.", graph->GetName().c_str(), node->GetName().c_str());
  564. return SUCCESS;
  565. }
  566. }
  567. return SUCCESS;
  568. }
  569. std::string Cluster::DebugString() const {
  570. std::stringstream ss;
  571. switch (type_) {
  572. case DATA:
  573. ss << "DATA";
  574. break;
  575. case INPUT_NODE:
  576. ss << "INPUT_NODE";
  577. break;
  578. case NETOUTPUT:
  579. ss << "NETOUTPUT";
  580. break;
  581. case UNKNOWN_SHAPE:
  582. ss << "UNKNOW";
  583. break;
  584. case KNOWN_SHAPE:
  585. ss << "KNOW";
  586. break;
  587. default:
  588. break;
  589. }
  590. ss << "[" << id_ << "](size:" << nodes_.size() << ")";
  591. ss << "(" << min_ << "," << max_ << ")(";
  592. for (const auto &cluster : in_clusters_) {
  593. ss << cluster->id_ << ",";
  594. }
  595. ss << ")->(";
  596. for (const auto &cluster : out_clusters_) {
  597. ss << cluster->id_ << ",";
  598. }
  599. ss << ")|";
  600. for (const auto &node : nodes_) {
  601. ss << (node->GetName() + "|");
  602. }
  603. return ss.str();
  604. }
  605. size_t Cluster::Id() const { return id_; }
  606. void Cluster::UpdateRank(size_t rank) {
  607. max_ = rank;
  608. min_ = rank;
  609. };
  610. bool Cluster::IsData() const { return type_ == DATA; };
  611. bool Cluster::IsKnownShape() const { return type_ == KNOWN_SHAPE; };
  612. bool Cluster::IsUnknownShape() const { return type_ == UNKNOWN_SHAPE; };
  613. bool Cluster::IsIndependent() const { return type_ == STAGE; };
  614. bool Cluster::IsNetOutput() const { return type_ == NETOUTPUT; };
  615. bool Cluster::IsInputNode() const { return type_ == INPUT_NODE; };
  616. bool Cluster::IsRefVariable() const {
  617. if ((nodes_.size() == 1) && ((nodes_[0]->GetType() == VARIABLE) || (nodes_[0]->GetType() == VARIABLEV2))) {
  618. std::string ref_variable_name;
  619. return (AttrUtils::GetStr(nodes_[0]->GetOpDesc(), REF_VAR_SRC_VAR_NAME, ref_variable_name) &&
  620. !ref_variable_name.empty());
  621. }
  622. return false;
  623. }
  624. void Cluster::AddInput(ClusterPtr in) {
  625. if (std::find(in_clusters_.begin(), in_clusters_.end(), in) != in_clusters_.end()) return;
  626. in_clusters_.insert(in_clusters_.end(), in);
  627. if (std::find(in->out_clusters_.begin(), in->out_clusters_.end(), shared_from_this()) != in->out_clusters_.end())
  628. return;
  629. in->out_clusters_.insert(in->out_clusters_.end(), shared_from_this());
  630. };
  631. void Cluster::RemoveInput(ClusterPtr in) {
  632. in_clusters_.erase(std::remove(in_clusters_.begin(), in_clusters_.end(), in), in_clusters_.end());
  633. in->out_clusters_.erase(std::remove(in->out_clusters_.begin(), in->out_clusters_.end(), shared_from_this()),
  634. in->out_clusters_.end());
  635. };
  636. void Cluster::AddOutput(ClusterPtr out) {
  637. if (std::find(out_clusters_.begin(), out_clusters_.end(), out) != out_clusters_.end()) return;
  638. out_clusters_.insert(out_clusters_.end(), out);
  639. if (std::find(out->in_clusters_.begin(), out->in_clusters_.end(), shared_from_this()) != out->in_clusters_.end())
  640. return;
  641. out->in_clusters_.insert(out->in_clusters_.end(), shared_from_this());
  642. };
  643. void Cluster::RemoveOutput(ClusterPtr out) {
  644. out_clusters_.erase(std::remove(out_clusters_.begin(), out_clusters_.end(), out), out_clusters_.end());
  645. out->in_clusters_.erase(std::remove(out->in_clusters_.begin(), out->in_clusters_.end(), shared_from_this()),
  646. out->in_clusters_.end());
  647. };
  648. void Cluster::Merge(ClusterPtr other) {
  649. if (other->IsIndependent()) {
  650. return;
  651. }
  652. nodes_.insert(nodes_.end(), other->nodes_.begin(), other->nodes_.end());
  653. other->in_clusters_.erase(std::remove(other->in_clusters_.begin(), other->in_clusters_.end(), shared_from_this()),
  654. other->in_clusters_.end());
  655. other->out_clusters_.erase(std::remove(other->out_clusters_.begin(), other->out_clusters_.end(), shared_from_this()),
  656. other->out_clusters_.end());
  657. in_clusters_.erase(std::remove(in_clusters_.begin(), in_clusters_.end(), other), in_clusters_.end());
  658. out_clusters_.erase(std::remove(out_clusters_.begin(), out_clusters_.end(), other), out_clusters_.end());
  659. auto in_clusters = other->in_clusters_;
  660. for (const auto &cluster : in_clusters) {
  661. cluster->RemoveOutput(other);
  662. cluster->AddOutput(shared_from_this());
  663. }
  664. auto out_clusters = other->out_clusters_;
  665. for (const auto &cluster : out_clusters) {
  666. cluster->RemoveInput(other);
  667. cluster->AddInput(shared_from_this());
  668. }
  669. if (other->max_ > max_) {
  670. max_ = other->max_;
  671. }
  672. if (other->min_ < min_) {
  673. min_ = other->min_;
  674. }
  675. if (!IsUnknownShape() && other->IsUnknownShape()) {
  676. type_ = UNKNOWN_SHAPE;
  677. }
  678. }
  679. bool Cluster::TryMerge(ClusterPtr other) {
  680. std::queue<ClusterPtr> forward_reached;
  681. forward_reached.push(other);
  682. while (!forward_reached.empty()) {
  683. auto current_cluster = forward_reached.front();
  684. forward_reached.pop();
  685. for (const auto &cluster : current_cluster->out_clusters_) {
  686. if (cluster->max_ == max_ && current_cluster != other) {
  687. return false;
  688. } else if (cluster->min_ < max_) {
  689. forward_reached.push(cluster);
  690. }
  691. }
  692. }
  693. Merge(other);
  694. return true;
  695. };
  696. std::vector<ClusterPtr> Cluster::MergeAllPathFrom(ClusterPtr other) {
  697. std::queue<ClusterPtr> forward_reached_queue;
  698. std::queue<ClusterPtr> backward_reached_queue;
  699. std::unordered_set<ClusterPtr> forward_reached_clusters;
  700. std::unordered_set<ClusterPtr> backward_reached_clusters;
  701. std::vector<ClusterPtr> path_clusters;
  702. if (other->IsIndependent()) {
  703. return path_clusters;
  704. }
  705. path_clusters.push_back(other);
  706. forward_reached_queue.push(other);
  707. backward_reached_queue.push(shared_from_this());
  708. while (!forward_reached_queue.empty()) {
  709. auto current_cluster = forward_reached_queue.front();
  710. forward_reached_queue.pop();
  711. for (const auto &cluster : current_cluster->out_clusters_) {
  712. if (cluster->min_ < max_ && cluster->max_ != max_ && forward_reached_clusters.count(cluster) == 0) {
  713. forward_reached_clusters.insert(cluster);
  714. forward_reached_queue.push(cluster);
  715. }
  716. }
  717. }
  718. while (!backward_reached_queue.empty()) {
  719. auto current_cluster = backward_reached_queue.front();
  720. backward_reached_queue.pop();
  721. for (const auto &cluster : current_cluster->in_clusters_) {
  722. if (cluster->max_ > other->min_ && cluster->max_ != other->max_ &&
  723. backward_reached_clusters.count(cluster) == 0) {
  724. backward_reached_clusters.insert(cluster);
  725. backward_reached_queue.push(cluster);
  726. if (forward_reached_clusters.count(cluster) != 0) {
  727. path_clusters.push_back(cluster);
  728. }
  729. }
  730. }
  731. }
  732. for (const auto &cluster : path_clusters) {
  733. Merge(cluster);
  734. }
  735. return path_clusters;
  736. }
  737. std::vector<ClusterPtr> Cluster::Inputs() const { return in_clusters_; };
  738. std::vector<ClusterPtr> Cluster::Outputs() const { return out_clusters_; };
  739. std::vector<NodePtr> Cluster::Nodes() const { return nodes_; };
  740. void Cluster::AddFrameInput(InDataAnchorPtr anchor) {
  741. if (anchor != nullptr && anchor->GetPeerOutAnchor() != nullptr) {
  742. inputs_index_[anchor] = inputs_.size();
  743. inputs_.push_back(anchor);
  744. }
  745. }
  746. void Cluster::AddFrameOutput(OutDataAnchorPtr anchor) {
  747. if (anchor != nullptr) {
  748. outputs_index_[anchor] = outputs_.size();
  749. outputs_.push_back(anchor);
  750. }
  751. }
  752. InDataAnchorPtr Cluster::GetFrameInDataAnchor(InDataAnchorPtr anchor) {
  753. return partition_node_->GetInDataAnchor(static_cast<int>(inputs_index_[anchor]));
  754. }
  755. OutDataAnchorPtr Cluster::GetFrameOutDataAnchor(OutDataAnchorPtr anchor) {
  756. return partition_node_->GetOutDataAnchor(static_cast<int>(outputs_index_[anchor]));
  757. }
  758. InControlAnchorPtr Cluster::GetFrameInControlAnchor() { return partition_node_->GetInControlAnchor(); };
  759. OutControlAnchorPtr Cluster::GetFrameOutControlAnchor() { return partition_node_->GetOutControlAnchor(); };
  760. Status Cluster::BuildFrame() {
  761. if (IsUnknownShape() || IsKnownShape() || IsInputNode()) {
  762. return BuildPartitionFrame();
  763. } else {
  764. auto node = nodes_.front();
  765. auto in_control_anchor = node->GetInControlAnchor();
  766. if (in_control_anchor != nullptr) {
  767. for (const auto &peer_out_control_anchor : in_control_anchor->GetPeerOutControlAnchors()) {
  768. auto src_cluster = partitioner_->node_2_cluster_[peer_out_control_anchor->GetOwnerNode()];
  769. if (src_cluster->id_ != id_) {
  770. REQUIRE_GRAPH_SUCCESS(
  771. GraphUtils::RemoveEdge(peer_out_control_anchor, in_control_anchor),
  772. "[Remove][Edge] from node %s index %d to node %s failed, index %d.",
  773. peer_out_control_anchor->GetOwnerNode()->GetName().c_str(), AnchorUtils::GetIdx(peer_out_control_anchor),
  774. in_control_anchor->GetOwnerNode()->GetName().c_str(), AnchorUtils::GetIdx(in_control_anchor));
  775. control_inputs_.insert(src_cluster);
  776. src_cluster->control_outputs_.insert(peer_out_control_anchor);
  777. }
  778. }
  779. }
  780. if (IsData() || IsIndependent()) {
  781. for (const auto &anchor : node->GetAllOutDataAnchors()) {
  782. AddFrameOutput(anchor);
  783. }
  784. } else {
  785. for (const auto &anchor : node->GetAllInDataAnchors()) {
  786. AddFrameInput(anchor);
  787. }
  788. }
  789. partition_node_ = node;
  790. }
  791. return SUCCESS;
  792. }
  793. Status Cluster::BuildPartitionFrame() {
  794. auto graph = partitioner_->root_graph_;
  795. bool is_unknown_shape = IsUnknownShape();
  796. bool is_input = IsInputNode();
  797. string known_name = (is_unknown_shape ? "_unknow" : "_know");
  798. string sub_graph_name_patten = (is_input ? "_input" : known_name);
  799. std::string sub_graph_name = graph->GetName() + "_sub_" + std::to_string(unique_id_) + sub_graph_name_patten;
  800. subgraph_ = MakeShared<ComputeGraph>(sub_graph_name);
  801. REQUIRE_NOT_NULL(subgraph_, "[New][Memory] for subgraph failed, name:%s.", sub_graph_name.c_str());
  802. auto partition_op = MakeShared<OpDesc>("PartitionedCall_" + std::to_string(unique_id_++), "PartitionedCall");
  803. REQUIRE_NOT_NULL(partition_op, "[New][Memory] for partition op failed.");
  804. REQUIRE(AttrUtils::SetBool(partition_op, ATTR_NAME_IS_UNKNOWN_SHAPE, is_unknown_shape),
  805. "[Set][Attr] _is_unknown_shape flag on partitioned op %s failed.", partition_op->GetName().c_str());
  806. REQUIRE_GRAPH_SUCCESS(partition_op->AddSubgraphName(subgraph_->GetName()),
  807. "[Add][SubgraphName] %s for op:%s.",
  808. subgraph_->GetName().c_str(), partition_op->GetName().c_str());
  809. REQUIRE_GRAPH_SUCCESS(partition_op->SetSubgraphInstanceName(0, subgraph_->GetName()),
  810. "[Call][SetSubgraphInstanceName] for op:%s failed, index:0, name:%s.",
  811. partition_op->GetName().c_str(), subgraph_->GetName().c_str());
  812. for (auto &node : nodes_) {
  813. REQUIRE_NOT_NULL(subgraph_->AddNode(node),
  814. "[Add][Node] %s to subgraph:%s failed.", node->GetName().c_str(), subgraph_->GetName().c_str());
  815. REQUIRE(AttrUtils::SetBool(node->GetOpDesc(), ATTR_NAME_IS_UNKNOWN_SHAPE, is_unknown_shape),
  816. "[Set][Attr] %s to op:%s failed.", ATTR_NAME_IS_UNKNOWN_SHAPE.c_str(), node->GetName().c_str());
  817. REQUIRE_GRAPH_SUCCESS(GraphUtils::RemoveJustNode(graph, node),
  818. "[Remove][JustNode] failed, graph:%s, node:%s.",
  819. graph->GetName().c_str(), node->GetName().c_str());
  820. REQUIRE_GRAPH_SUCCESS(node->SetOwnerComputeGraph(subgraph_),
  821. "[Set][OwnerComputeGraph] %s for node:%s failed.",
  822. subgraph_->GetName().c_str(), node->GetName().c_str());
  823. for (const auto &anchor : node->GetAllInDataAnchors()) {
  824. auto peer_out_anchor = anchor->GetPeerOutAnchor();
  825. if (peer_out_anchor == nullptr) {
  826. continue; // Skip overhang input.
  827. }
  828. auto src_cluster = partitioner_->node_2_cluster_[peer_out_anchor->GetOwnerNode()];
  829. if (src_cluster->id_ != id_) {
  830. AddFrameInput(anchor);
  831. REQUIRE_GRAPH_SUCCESS(partition_op->AddInputDesc(node->GetOpDesc()->GetInputDesc(anchor->GetIdx())),
  832. "[Add][InputDesc] to op:%s failed.", partition_op->GetName().c_str());
  833. }
  834. }
  835. auto in_control_anchor = node->GetInControlAnchor();
  836. if (in_control_anchor != nullptr) {
  837. for (const auto &peer_out_control_anchor : in_control_anchor->GetPeerOutControlAnchors()) {
  838. if (peer_out_control_anchor == nullptr) {
  839. continue;
  840. }
  841. auto src_cluster = partitioner_->node_2_cluster_[peer_out_control_anchor->GetOwnerNode()];
  842. if (src_cluster->id_ != id_) {
  843. REQUIRE_GRAPH_SUCCESS(
  844. GraphUtils::RemoveEdge(peer_out_control_anchor, in_control_anchor),
  845. "[Remove][Edge] from %s:%d to %s:%d failed.", peer_out_control_anchor->GetOwnerNode()->GetName().c_str(),
  846. peer_out_control_anchor->GetIdx(), node->GetName().c_str(), in_control_anchor->GetIdx());
  847. control_inputs_.insert(src_cluster);
  848. src_cluster->control_outputs_.insert(peer_out_control_anchor);
  849. }
  850. }
  851. }
  852. for (const auto &anchor : node->GetAllOutDataAnchors()) {
  853. auto peer_in_anchors = anchor->GetPeerInDataAnchors();
  854. for (const auto &peer_in_anchor : peer_in_anchors) {
  855. auto src_cluster = partitioner_->node_2_cluster_[peer_in_anchor->GetOwnerNode()];
  856. if (src_cluster->id_ != id_) {
  857. AddFrameOutput(anchor);
  858. REQUIRE_GRAPH_SUCCESS(partition_op->AddOutputDesc(node->GetOpDesc()->GetOutputDesc(anchor->GetIdx())),
  859. "[Add][OutputDesc] to op:%s failed.", partition_op->GetName().c_str());
  860. break;
  861. }
  862. }
  863. }
  864. }
  865. partition_node_ = graph->AddNode(partition_op);
  866. REQUIRE_NOT_NULL(partition_node_,
  867. "[Add][Node] %s to graph:%s failed.", partition_op->GetName().c_str(), graph->GetName().c_str());
  868. REQUIRE_GRAPH_SUCCESS(partition_node_->SetOwnerComputeGraph(graph),
  869. "[Set][OwnerComputeGraph] %s for node:%s failed.",
  870. graph->GetName().c_str(), partition_op->GetName().c_str());
  871. subgraph_->SetParentNode(partition_node_);
  872. subgraph_->SetParentGraph(graph);
  873. REQUIRE_GRAPH_SUCCESS(graph->AddSubgraph(subgraph_),
  874. "[Add][Subgraph] %s to root graph:%s failed.",
  875. subgraph_->GetName().c_str(), graph->GetName().c_str());
  876. std::string session_graph_id;
  877. REQUIRE(AttrUtils::GetStr(*graph, ATTR_NAME_SESSION_GRAPH_ID, session_graph_id),
  878. "[Get][Attr] %s on root graph:%s failed.", ATTR_NAME_SESSION_GRAPH_ID.c_str(), graph->GetName().c_str());
  879. REQUIRE(AttrUtils::SetStr(*subgraph_, ATTR_NAME_SESSION_GRAPH_ID, session_graph_id),
  880. "[Set][Attr] %s on subgraph:%s failed.", ATTR_NAME_SESSION_GRAPH_ID.c_str(), subgraph_->GetName().c_str());
  881. return SUCCESS;
  882. }
  883. Status Cluster::CombinePartitionFrame() {
  884. for (const auto &anchor : inputs_) {
  885. auto peer_out_anchor = anchor->GetPeerOutAnchor();
  886. auto src_cluster = partitioner_->node_2_cluster_[peer_out_anchor->GetOwnerNode()];
  887. auto src_anchor = src_cluster->GetFrameOutDataAnchor(peer_out_anchor);
  888. auto dst_anchor = GetFrameInDataAnchor(anchor);
  889. REQUIRE_GRAPH_SUCCESS(GraphUtils::RemoveEdge(peer_out_anchor, anchor), "[Remove][Edge] from %s:%d to %s:%d fail.",
  890. peer_out_anchor->GetOwnerNode()->GetName().c_str(), peer_out_anchor->GetIdx(),
  891. anchor->GetOwnerNode()->GetName().c_str(), anchor->GetIdx());
  892. REQUIRE_GRAPH_SUCCESS(GraphUtils::AddEdge(src_anchor, dst_anchor), "[Add][Edge] from %s:%d to %s:%d failed.",
  893. src_anchor->GetOwnerNode()->GetName().c_str(), src_anchor->GetIdx(),
  894. dst_anchor->GetOwnerNode()->GetName().c_str(), dst_anchor->GetIdx());
  895. }
  896. for (const auto &src_cluster : control_inputs_) {
  897. auto src_anchor = src_cluster->GetFrameOutControlAnchor();
  898. auto dst_anchor = GetFrameInControlAnchor();
  899. REQUIRE_GRAPH_SUCCESS(GraphUtils::AddEdge(src_anchor, dst_anchor), "[Add][Edge] from %s:%d to %s:%d failed.",
  900. src_anchor->GetOwnerNode()->GetName().c_str(), src_anchor->GetIdx(),
  901. dst_anchor->GetOwnerNode()->GetName().c_str(), dst_anchor->GetIdx());
  902. }
  903. return SUCCESS;
  904. }
  905. Status Cluster::BuildPartitionSubgraph() {
  906. if (IsData() || IsNetOutput() || IsIndependent()) {
  907. return SUCCESS;
  908. }
  909. int64_t parent_node_index = 0;
  910. for (auto anchor : inputs_) {
  911. auto data_op =
  912. MakeShared<OpDesc>(subgraph_->GetName() + std::string("Data_") + std::to_string(parent_node_index), ge::DATA);
  913. REQUIRE_NOT_NULL(data_op, "[New][Memory] for data op failed.");
  914. auto input_desc = anchor->GetOwnerNode()->GetOpDesc()->GetInputDesc(anchor->GetIdx());
  915. REQUIRE_GRAPH_SUCCESS(data_op->AddInputDesc(input_desc),
  916. "[Add][InputDesc] to op:%s failed.", data_op->GetName().c_str());
  917. REQUIRE_GRAPH_SUCCESS(data_op->AddOutputDesc(input_desc),
  918. "[Add][OutputDesc] to op:%s failed.", data_op->GetName().c_str());
  919. REQUIRE(AttrUtils::SetInt(data_op, ATTR_NAME_PARENT_NODE_INDEX, parent_node_index),
  920. "[Set][Attr] %s on subgraph data node:%s failed.",
  921. ATTR_NAME_PARENT_NODE_INDEX.c_str(), data_op->GetName().c_str());
  922. bool is_unknown_shape = IsUnknownShape();
  923. REQUIRE(AttrUtils::SetBool(data_op, ATTR_NAME_IS_UNKNOWN_SHAPE, is_unknown_shape),
  924. "[Set][Attr] %s on data op %s failed.", ATTR_NAME_IS_UNKNOWN_SHAPE.c_str(), data_op->GetName().c_str());
  925. auto data_node = subgraph_->AddNode(data_op);
  926. REQUIRE_NOT_NULL(data_node,
  927. "[Add][Node] %s to subgraph:%s failed.", data_op->GetName().c_str(), subgraph_->GetName().c_str());
  928. REQUIRE_GRAPH_SUCCESS(data_node->SetOwnerComputeGraph(subgraph_),
  929. "[Set][OwnerGraph] %s of data node:%s failed.",
  930. subgraph_->GetName().c_str(), data_op->GetName().c_str());
  931. REQUIRE_GRAPH_SUCCESS(GraphUtils::AddEdge(data_node->GetOutDataAnchor(0), anchor),
  932. "[Call][AddEdge] Failed add data input edge to %s:%d",
  933. anchor->GetOwnerNode()->GetName().c_str(), anchor->GetIdx());
  934. parent_node_index++;
  935. }
  936. if (outputs_.empty() && control_outputs_.empty()) {
  937. return SUCCESS;
  938. }
  939. auto net_output_op = MakeShared<OpDesc>(subgraph_->GetName() + "_" + NODE_NAME_NET_OUTPUT, ge::NETOUTPUT);
  940. REQUIRE_NOT_NULL(net_output_op, "[New][Memory] for netoutput op failed.");
  941. bool is_unknown_shape = IsUnknownShape();
  942. REQUIRE(AttrUtils::SetBool(net_output_op, ATTR_NAME_IS_UNKNOWN_SHAPE, is_unknown_shape),
  943. "[Set][Attr] %s on op:%s failed.", ATTR_NAME_IS_UNKNOWN_SHAPE.c_str(), net_output_op->GetName().c_str());
  944. for (size_t i = 0; i < outputs_.size(); ++i) {
  945. GeTensorDesc input_desc;
  946. REQUIRE_GRAPH_SUCCESS(net_output_op->AddInputDesc(input_desc),
  947. "[Add][InputDesc] to op:%s failed.", net_output_op->GetName().c_str());
  948. }
  949. auto net_output_node = subgraph_->AddNode(net_output_op);
  950. REQUIRE_NOT_NULL(net_output_node,
  951. "[Call][AddNode] Failed add netoutput node:%s to subgraph:%s.",
  952. net_output_op->GetName().c_str(), subgraph_->GetName().c_str());
  953. REQUIRE_GRAPH_SUCCESS(net_output_node->SetOwnerComputeGraph(subgraph_),
  954. "[Set][OwnerGraph] %s of netoutput node:%s failed.",
  955. subgraph_->GetName().c_str(), net_output_node->GetName().c_str());
  956. parent_node_index = 0;
  957. for (const auto &anchor : outputs_) {
  958. auto output_desc = anchor->GetOwnerNode()->GetOpDesc()->GetOutputDesc(static_cast<uint32_t>(anchor->GetIdx()));
  959. REQUIRE(AttrUtils::SetInt(output_desc, ATTR_NAME_PARENT_NODE_INDEX, parent_node_index),
  960. "[Set][Attr] parent_node_index on subgraph node:%s netoutput's input failed.",
  961. anchor->GetOwnerNode()->GetName().c_str());
  962. REQUIRE_GRAPH_SUCCESS(net_output_op->UpdateInputDesc(parent_node_index, output_desc),
  963. "[Update][InputDesc] of netoutput node:%s failed.", net_output_op->GetName().c_str());
  964. REQUIRE_GRAPH_SUCCESS(GraphUtils::AddEdge(anchor, net_output_node->GetInDataAnchor(parent_node_index)),
  965. "[Add][Edge] from %s:%d to netoutput node:%s failed.",
  966. anchor->GetOwnerNode()->GetName().c_str(), anchor->GetIdx(),
  967. net_output_op->GetName().c_str());
  968. parent_node_index++;
  969. }
  970. for (const auto &anchor : control_outputs_) {
  971. REQUIRE_GRAPH_SUCCESS(GraphUtils::AddEdge(anchor, net_output_node->GetInControlAnchor()),
  972. "[Add][ControlEdge] from %s:%d to netoutput node:%s failed.",
  973. anchor->GetOwnerNode()->GetName().c_str(), anchor->GetIdx(),
  974. net_output_op->GetName().c_str());
  975. }
  976. return SUCCESS;
  977. }
  978. void Cluster::Clear() {
  979. in_clusters_.clear();
  980. out_clusters_.clear();
  981. nodes_.clear();
  982. partitioner_ = nullptr;
  983. inputs_index_.clear();
  984. outputs_index_.clear();
  985. inputs_.clear();
  986. outputs_.clear();
  987. control_inputs_.clear();
  988. control_outputs_.clear();
  989. partition_node_.reset();
  990. subgraph_.reset();
  991. unique_id_ = 0;
  992. }
  993. thread_local size_t Cluster::unique_id_ = 0;
  994. } // namespace ge

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