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
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  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. auto merged_clusters = cluster->MergeAllPathFrom(cluster_from);
  354. GELOGD("Merge all path cluster from %lu to %lu %s.", cluster_from->Id(), cluster->Id(),
  355. ToString(merged_clusters).c_str());
  356. for (const auto &merged_cluster : merged_clusters) {
  357. all_merged_clusters.emplace(merged_cluster);
  358. for (const auto &node : merged_cluster->Nodes()) {
  359. node_2_cluster_[node] = cluster;
  360. }
  361. }
  362. }
  363. if (!is_unknown_cluster && cluster->IsUnknownShape()) {
  364. ordered_cluster_.push_back(cluster);
  365. }
  366. }
  367. }
  368. void DynamicShapePartitioner::MergeClustersUnknownShape() {
  369. // Merge unknown shape clusters
  370. for (const auto &cluster : ordered_cluster_) {
  371. if (cluster->IsIndependent()) {
  372. continue;
  373. }
  374. for (const auto &in_cluster : cluster->Inputs()) {
  375. if (!in_cluster->IsUnknownShape()) {
  376. continue;
  377. }
  378. if (!cluster->IsAdjoinNodes(in_cluster)) {
  379. continue;
  380. }
  381. auto merged_clusters = cluster->MergeAllPathFrom(in_cluster);
  382. GELOGD("Merge all path cluster from %lu to %lu %s.", in_cluster->Id(), cluster->Id(),
  383. ToString(merged_clusters).c_str());
  384. for (const auto &merged_cluster : merged_clusters) {
  385. for (const auto &node : merged_cluster->Nodes()) {
  386. node_2_cluster_[node] = cluster;
  387. }
  388. }
  389. }
  390. }
  391. }
  392. void DynamicShapePartitioner::MergeClustersKnownShape() {
  393. // Merge known shape clusters
  394. for (const auto &cluster : ordered_cluster_) {
  395. if (cluster->IsIndependent()) {
  396. continue;
  397. }
  398. if (cluster->IsRefVariable() && cluster->Inputs().size() == 1) {
  399. auto in_cluster = *(cluster->Inputs().begin());
  400. in_cluster->Merge(cluster);
  401. node_2_cluster_[*(cluster->Nodes().begin())] = in_cluster;
  402. continue;
  403. }
  404. for (const auto &in_cluster : cluster->Inputs()) {
  405. if (!in_cluster->IsKnownShape()) {
  406. continue;
  407. }
  408. if (cluster->TryMerge(in_cluster)) {
  409. GELOGD("Success merge known shape cluster from %lu to %lu.", in_cluster->Id(), cluster->Id());
  410. for (const auto &node : in_cluster->Nodes()) {
  411. node_2_cluster_[node] = cluster;
  412. }
  413. }
  414. }
  415. }
  416. }
  417. void DynamicShapePartitioner::MergeClustersInputData() {
  418. // Merge input clusters
  419. std::shared_ptr<Cluster> cluster_pre = nullptr;
  420. for (const auto &cluster : ordered_cluster_) {
  421. if (!cluster->IsInputNode()) {
  422. continue;
  423. }
  424. if (cluster_pre != nullptr) {
  425. cluster_pre->Merge(cluster);
  426. } else {
  427. cluster_pre = cluster;
  428. }
  429. GELOGD("Success merge input node cluster from %lu to %lu.", cluster->Id(), cluster->Id());
  430. for (const auto &node : cluster->Nodes()) {
  431. node_2_cluster_[node] = cluster_pre;
  432. }
  433. }
  434. }
  435. Status DynamicShapePartitioner::MergeClusters() {
  436. MergeClustersControlFlow();
  437. MergeClustersUnknownShape();
  438. REQUIRE_SUCCESS(TopologicalSortClusters(), "[TopologicalSort][Clusters] after merge unknown shape clusters failed.");
  439. MergeClustersKnownShape();
  440. MergeClustersInputData();
  441. return SUCCESS;
  442. }
  443. bool DynamicShapePartitioner::JudgeUnknowShapeWithAttr(const OpDescPtr &opdesc) {
  444. bool is_forced_unknown = false;
  445. if (AttrUtils::GetBool(opdesc, ATTR_NAME_IS_UNKNOWN_SHAPE, is_forced_unknown) && is_forced_unknown) {
  446. GELOGD("Collect node %s as unknown as it was marked unknown forcibly.", opdesc->GetName().c_str());
  447. return true;
  448. }
  449. bool forced_unknown = false;
  450. if (AttrUtils::GetBool(opdesc, ATTR_NAME_FORCE_UNKNOWN_SHAPE, forced_unknown) && forced_unknown) {
  451. GELOGD("Collect node %s as unknown as it was marked force unknown node forcibly.", opdesc->GetName().c_str());
  452. return true;
  453. }
  454. return false;
  455. }
  456. Status DynamicShapePartitioner::CollectSpreadUnknownShapeNodes(NodePtr node) {
  457. if (unknown_shape_nodes_.count(node) > 0) {
  458. return SUCCESS;
  459. }
  460. auto opdesc = node->GetOpDesc();
  461. REQUIRE_NOT_NULL(opdesc, "[Get][OpDesc] Opdesc is nullptr.");
  462. // One can set 'ATTR_NAME_IS_UNKNOWN_SHAPE=true' on node so as to forcing the node flow into the unknown subgraph,
  463. // ignore the actual shape.
  464. if (JudgeUnknowShapeWithAttr(opdesc)) {
  465. unknown_shape_nodes_.insert(node);
  466. return SUCCESS;
  467. }
  468. size_t anchor_index = 0;
  469. bool is_unknown = false;
  470. for (auto &out_tensor : opdesc->GetAllOutputsDesc()) {
  471. if (IsUnknownShapeTensor(out_tensor)) {
  472. GELOGD("Collect node %s as unknown as output %lu is unknown.", node->GetName().c_str(), anchor_index);
  473. is_unknown = true;
  474. auto anchor = node->GetOutDataAnchor(static_cast<int>(anchor_index));
  475. for (const auto peer_anchor : anchor->GetPeerInDataAnchors()) {
  476. if (peer_anchor != nullptr) {
  477. GELOGD("Collect node %s as has unknown input from %s:%lu.", peer_anchor->GetOwnerNode()->GetName().c_str(),
  478. node->GetName().c_str(), anchor_index);
  479. unknown_shape_nodes_.insert(peer_anchor->GetOwnerNode());
  480. }
  481. }
  482. }
  483. anchor_index++;
  484. }
  485. anchor_index = 0;
  486. for (auto &in_tensor : opdesc->GetAllInputsDesc()) {
  487. if (IsUnknownShapeTensor(in_tensor)) {
  488. GELOGD("Collect node %s as unknown as input %lu is unknown.", node->GetName().c_str(), anchor_index);
  489. is_unknown = true;
  490. auto anchor = node->GetInDataAnchor(static_cast<int>(anchor_index));
  491. const auto peer_anchor = anchor->GetPeerOutAnchor();
  492. if (peer_anchor != nullptr) {
  493. GELOGD("Collect node %s as has unknown output to %s:%lu.", peer_anchor->GetOwnerNode()->GetName().c_str(),
  494. node->GetName().c_str(), anchor_index);
  495. unknown_shape_nodes_.insert(peer_anchor->GetOwnerNode());
  496. }
  497. }
  498. anchor_index++;
  499. }
  500. if (is_unknown) {
  501. unknown_shape_nodes_.insert(node);
  502. } else {
  503. auto graph = root_graph_;
  504. for (const auto &subgraph_name : opdesc->GetSubgraphInstanceNames()) {
  505. auto subgraph = graph->GetSubgraph(subgraph_name);
  506. REQUIRE_NOT_NULL(subgraph, "[Get][Subgraph] %s of node %s on root graph failed.", subgraph_name.c_str(),
  507. node->GetName().c_str());
  508. bool is_graph_unknow = false;
  509. REQUIRE_SUCCESS(IsUnknownShapeGraph(subgraph, is_graph_unknow),
  510. "[Call][IsUnknownShapeGraph] Failed check subgraph %s shape of node %s.",
  511. subgraph_name.c_str(), node->GetName().c_str());
  512. if (is_graph_unknow) {
  513. GELOGD("Collect node %s as its subgraph %s is unknown.", node->GetName().c_str(), subgraph->GetName().c_str());
  514. unknown_shape_nodes_.insert(node);
  515. break;
  516. }
  517. }
  518. }
  519. return SUCCESS;
  520. }
  521. Status DynamicShapePartitioner::IsUnknownShapeNode(NodePtr node, bool &is_unknown) {
  522. auto opdesc = node->GetOpDesc();
  523. auto graph = root_graph_;
  524. for (auto &out_tensor : opdesc->GetAllOutputsDesc()) {
  525. if (IsUnknownShapeTensor(out_tensor)) {
  526. GELOGD("Mark node %s unknown as unknown output.", node->GetName().c_str());
  527. is_unknown = true;
  528. return SUCCESS;
  529. }
  530. }
  531. for (auto &in_tensor : opdesc->GetAllInputsDesc()) {
  532. if (IsUnknownShapeTensor(in_tensor)) {
  533. GELOGD("Mark node %s unknown as unknown intput.", node->GetName().c_str());
  534. is_unknown = true;
  535. return SUCCESS;
  536. }
  537. }
  538. for (auto &subgraph_name : opdesc->GetSubgraphInstanceNames()) {
  539. auto subgraph = graph->GetSubgraph(subgraph_name);
  540. REQUIRE_NOT_NULL(subgraph, "[Get][Subgraph] %s of node %s on root graph failed.", subgraph_name.c_str(),
  541. node->GetName().c_str());
  542. REQUIRE_SUCCESS(IsUnknownShapeGraph(subgraph, is_unknown),
  543. "[Call][IsUnknownShapeGraph] Failed check subgraph %s shape of node %s.",
  544. subgraph_name.c_str(), node->GetName().c_str());
  545. if (is_unknown) {
  546. GELOGD("Mark node %s unknown as unknown subgraph.", node->GetName().c_str());
  547. return SUCCESS;
  548. }
  549. }
  550. is_unknown = false;
  551. return SUCCESS;
  552. }
  553. Status DynamicShapePartitioner::IsUnknownShapeGraph(ComputeGraphPtr graph, bool &is_unknown) {
  554. for (auto &node : graph->GetDirectNode()) {
  555. REQUIRE_SUCCESS(IsUnknownShapeNode(node, is_unknown),
  556. "[Call][IsUnknownShapeNode]Failed check node %s shape on graph %s.",
  557. node->GetName().c_str(), graph->GetName().c_str());
  558. if (is_unknown) {
  559. GELOGD("Mark graph %s unknown as contains unknown node %s.", graph->GetName().c_str(), node->GetName().c_str());
  560. return SUCCESS;
  561. }
  562. }
  563. return SUCCESS;
  564. }
  565. std::string Cluster::DebugString() const {
  566. std::stringstream ss;
  567. switch (type_) {
  568. case DATA:
  569. ss << "DATA";
  570. break;
  571. case INPUT_NODE:
  572. ss << "INPUT_NODE";
  573. break;
  574. case NETOUTPUT:
  575. ss << "NETOUTPUT";
  576. break;
  577. case UNKNOWN_SHAPE:
  578. ss << "UNKNOW";
  579. break;
  580. case KNOWN_SHAPE:
  581. ss << "KNOW";
  582. break;
  583. default:
  584. break;
  585. }
  586. ss << "[" << id_ << "](size:" << nodes_.size() << ")";
  587. ss << "(" << min_ << "," << max_ << ")(";
  588. for (const auto &cluster : in_clusters_) {
  589. ss << cluster->id_ << ",";
  590. }
  591. ss << ")->(";
  592. for (const auto &cluster : out_clusters_) {
  593. ss << cluster->id_ << ",";
  594. }
  595. ss << ")|";
  596. for (const auto &node : nodes_) {
  597. ss << (node->GetName() + "|");
  598. }
  599. return ss.str();
  600. }
  601. size_t Cluster::Id() const { return id_; }
  602. void Cluster::UpdateRank(size_t rank) {
  603. max_ = rank;
  604. min_ = rank;
  605. };
  606. bool Cluster::IsData() const { return type_ == DATA; };
  607. bool Cluster::IsKnownShape() const { return type_ == KNOWN_SHAPE; };
  608. bool Cluster::IsUnknownShape() const { return type_ == UNKNOWN_SHAPE; };
  609. bool Cluster::IsIndependent() const { return type_ == STAGE; };
  610. bool Cluster::IsNetOutput() const { return type_ == NETOUTPUT; };
  611. bool Cluster::IsInputNode() const { return type_ == INPUT_NODE; };
  612. bool Cluster::IsRefVariable() const {
  613. if ((nodes_.size() == 1) && ((nodes_[0]->GetType() == VARIABLE) || (nodes_[0]->GetType() == VARIABLEV2))) {
  614. std::string ref_variable_name;
  615. return (AttrUtils::GetStr(nodes_[0]->GetOpDesc(), REF_VAR_SRC_VAR_NAME, ref_variable_name) &&
  616. !ref_variable_name.empty());
  617. }
  618. return false;
  619. }
  620. void Cluster::AddInput(ClusterPtr in) {
  621. if (std::find(in_clusters_.begin(), in_clusters_.end(), in) != in_clusters_.end()) return;
  622. in_clusters_.insert(in_clusters_.end(), in);
  623. if (std::find(in->out_clusters_.begin(), in->out_clusters_.end(), shared_from_this()) != in->out_clusters_.end())
  624. return;
  625. in->out_clusters_.insert(in->out_clusters_.end(), shared_from_this());
  626. };
  627. void Cluster::RemoveInput(ClusterPtr in) {
  628. in_clusters_.erase(std::remove(in_clusters_.begin(), in_clusters_.end(), in), in_clusters_.end());
  629. in->out_clusters_.erase(std::remove(in->out_clusters_.begin(), in->out_clusters_.end(), shared_from_this()),
  630. in->out_clusters_.end());
  631. };
  632. void Cluster::AddOutput(ClusterPtr out) {
  633. if (std::find(out_clusters_.begin(), out_clusters_.end(), out) != out_clusters_.end()) return;
  634. out_clusters_.insert(out_clusters_.end(), out);
  635. if (std::find(out->in_clusters_.begin(), out->in_clusters_.end(), shared_from_this()) != out->in_clusters_.end())
  636. return;
  637. out->in_clusters_.insert(out->in_clusters_.end(), shared_from_this());
  638. };
  639. void Cluster::RemoveOutput(ClusterPtr out) {
  640. out_clusters_.erase(std::remove(out_clusters_.begin(), out_clusters_.end(), out), out_clusters_.end());
  641. out->in_clusters_.erase(std::remove(out->in_clusters_.begin(), out->in_clusters_.end(), shared_from_this()),
  642. out->in_clusters_.end());
  643. };
  644. void Cluster::Merge(ClusterPtr other) {
  645. if (other->IsIndependent()) {
  646. return;
  647. }
  648. nodes_.insert(nodes_.end(), other->nodes_.begin(), other->nodes_.end());
  649. other->in_clusters_.erase(std::remove(other->in_clusters_.begin(), other->in_clusters_.end(), shared_from_this()),
  650. other->in_clusters_.end());
  651. other->out_clusters_.erase(std::remove(other->out_clusters_.begin(), other->out_clusters_.end(), shared_from_this()),
  652. other->out_clusters_.end());
  653. in_clusters_.erase(std::remove(in_clusters_.begin(), in_clusters_.end(), other), in_clusters_.end());
  654. out_clusters_.erase(std::remove(out_clusters_.begin(), out_clusters_.end(), other), out_clusters_.end());
  655. auto in_clusters = other->in_clusters_;
  656. for (const auto &cluster : in_clusters) {
  657. cluster->RemoveOutput(other);
  658. cluster->AddOutput(shared_from_this());
  659. }
  660. auto out_clusters = other->out_clusters_;
  661. for (const auto &cluster : out_clusters) {
  662. cluster->RemoveInput(other);
  663. cluster->AddInput(shared_from_this());
  664. }
  665. if (other->max_ > max_) {
  666. max_ = other->max_;
  667. }
  668. if (other->min_ < min_) {
  669. min_ = other->min_;
  670. }
  671. if (!IsUnknownShape() && other->IsUnknownShape()) {
  672. type_ = UNKNOWN_SHAPE;
  673. }
  674. }
  675. bool Cluster::TryMerge(ClusterPtr other) {
  676. std::queue<ClusterPtr> forward_reached;
  677. forward_reached.push(other);
  678. while (!forward_reached.empty()) {
  679. auto current_cluster = forward_reached.front();
  680. forward_reached.pop();
  681. for (const auto &cluster : current_cluster->out_clusters_) {
  682. if (cluster->max_ == max_ && current_cluster != other) {
  683. return false;
  684. } else if (cluster->min_ < max_) {
  685. forward_reached.push(cluster);
  686. }
  687. }
  688. }
  689. Merge(other);
  690. return true;
  691. };
  692. std::vector<ClusterPtr> Cluster::MergeAllPathFrom(ClusterPtr other) {
  693. std::queue<ClusterPtr> forward_reached_queue;
  694. std::queue<ClusterPtr> backward_reached_queue;
  695. std::unordered_set<ClusterPtr> forward_reached_clusters;
  696. std::unordered_set<ClusterPtr> backward_reached_clusters;
  697. std::vector<ClusterPtr> path_clusters;
  698. if (other->IsIndependent()) {
  699. return path_clusters;
  700. }
  701. path_clusters.push_back(other);
  702. forward_reached_queue.push(other);
  703. backward_reached_queue.push(shared_from_this());
  704. while (!forward_reached_queue.empty()) {
  705. auto current_cluster = forward_reached_queue.front();
  706. forward_reached_queue.pop();
  707. for (const auto &cluster : current_cluster->out_clusters_) {
  708. if (cluster->min_ < max_ && cluster->max_ != max_ && forward_reached_clusters.count(cluster) == 0) {
  709. forward_reached_clusters.insert(cluster);
  710. forward_reached_queue.push(cluster);
  711. }
  712. }
  713. }
  714. while (!backward_reached_queue.empty()) {
  715. auto current_cluster = backward_reached_queue.front();
  716. backward_reached_queue.pop();
  717. for (const auto &cluster : current_cluster->in_clusters_) {
  718. if (cluster->max_ > other->min_ && cluster->max_ != other->max_ &&
  719. backward_reached_clusters.count(cluster) == 0) {
  720. backward_reached_clusters.insert(cluster);
  721. backward_reached_queue.push(cluster);
  722. if (forward_reached_clusters.count(cluster) != 0) {
  723. path_clusters.push_back(cluster);
  724. }
  725. }
  726. }
  727. }
  728. for (const auto &cluster : path_clusters) {
  729. Merge(cluster);
  730. }
  731. return path_clusters;
  732. }
  733. std::vector<ClusterPtr> Cluster::Inputs() const { return in_clusters_; };
  734. std::vector<ClusterPtr> Cluster::Outputs() const { return out_clusters_; };
  735. std::vector<NodePtr> Cluster::Nodes() const { return nodes_; };
  736. void Cluster::AddFrameInput(InDataAnchorPtr anchor) {
  737. if (anchor != nullptr && anchor->GetPeerOutAnchor() != nullptr) {
  738. inputs_index_[anchor] = inputs_.size();
  739. inputs_.push_back(anchor);
  740. }
  741. }
  742. void Cluster::AddFrameOutput(OutDataAnchorPtr anchor) {
  743. if (anchor != nullptr) {
  744. outputs_index_[anchor] = outputs_.size();
  745. outputs_.push_back(anchor);
  746. }
  747. }
  748. InDataAnchorPtr Cluster::GetFrameInDataAnchor(InDataAnchorPtr anchor) {
  749. return partition_node_->GetInDataAnchor(static_cast<int>(inputs_index_[anchor]));
  750. }
  751. OutDataAnchorPtr Cluster::GetFrameOutDataAnchor(OutDataAnchorPtr anchor) {
  752. return partition_node_->GetOutDataAnchor(static_cast<int>(outputs_index_[anchor]));
  753. }
  754. InControlAnchorPtr Cluster::GetFrameInControlAnchor() { return partition_node_->GetInControlAnchor(); };
  755. OutControlAnchorPtr Cluster::GetFrameOutControlAnchor() { return partition_node_->GetOutControlAnchor(); };
  756. Status Cluster::BuildFrame() {
  757. if (IsUnknownShape() || IsKnownShape() || IsInputNode()) {
  758. return BuildPartitionFrame();
  759. } else {
  760. auto node = nodes_.front();
  761. auto in_control_anchor = node->GetInControlAnchor();
  762. if (in_control_anchor != nullptr) {
  763. for (const auto &peer_out_control_anchor : in_control_anchor->GetPeerOutControlAnchors()) {
  764. auto src_cluster = partitioner_->node_2_cluster_[peer_out_control_anchor->GetOwnerNode()];
  765. if (src_cluster->id_ != id_) {
  766. REQUIRE_GRAPH_SUCCESS(
  767. GraphUtils::RemoveEdge(peer_out_control_anchor, in_control_anchor),
  768. "[Remove][Edge] from node %s index %d to node %s failed, index %d.",
  769. peer_out_control_anchor->GetOwnerNode()->GetName().c_str(), AnchorUtils::GetIdx(peer_out_control_anchor),
  770. in_control_anchor->GetOwnerNode()->GetName().c_str(), AnchorUtils::GetIdx(in_control_anchor));
  771. control_inputs_.insert(src_cluster);
  772. src_cluster->control_outputs_.insert(peer_out_control_anchor);
  773. }
  774. }
  775. }
  776. if (IsData() || IsIndependent()) {
  777. for (const auto &anchor : node->GetAllOutDataAnchors()) {
  778. AddFrameOutput(anchor);
  779. }
  780. } else {
  781. for (const auto &anchor : node->GetAllInDataAnchors()) {
  782. AddFrameInput(anchor);
  783. }
  784. }
  785. partition_node_ = node;
  786. }
  787. return SUCCESS;
  788. }
  789. Status Cluster::BuildPartitionFrame() {
  790. auto graph = partitioner_->root_graph_;
  791. bool is_unknown_shape = IsUnknownShape();
  792. bool is_input = IsInputNode();
  793. string known_name = (is_unknown_shape ? "_unknow" : "_know");
  794. string sub_graph_name_patten = (is_input ? "_input" : known_name);
  795. std::string sub_graph_name = graph->GetName() + "_sub_" + std::to_string(unique_id_) + sub_graph_name_patten;
  796. subgraph_ = MakeShared<ComputeGraph>(sub_graph_name);
  797. REQUIRE_NOT_NULL(subgraph_, "[New][Memory] for subgraph failed, name:%s.", sub_graph_name.c_str());
  798. auto partition_op = MakeShared<OpDesc>("PartitionedCall_" + std::to_string(unique_id_++), "PartitionedCall");
  799. REQUIRE_NOT_NULL(partition_op, "[New][Memory] for partition op failed.");
  800. REQUIRE(AttrUtils::SetBool(partition_op, ATTR_NAME_IS_UNKNOWN_SHAPE, is_unknown_shape),
  801. "[Set][Attr] _is_unknown_shape flag on partitioned op %s failed.", partition_op->GetName().c_str());
  802. REQUIRE_GRAPH_SUCCESS(partition_op->AddSubgraphName(subgraph_->GetName()),
  803. "[Add][SubgraphName] %s for op:%s.",
  804. subgraph_->GetName().c_str(), partition_op->GetName().c_str());
  805. REQUIRE_GRAPH_SUCCESS(partition_op->SetSubgraphInstanceName(0, subgraph_->GetName()),
  806. "[Call][SetSubgraphInstanceName] for op:%s failed, index:0, name:%s.",
  807. partition_op->GetName().c_str(), subgraph_->GetName().c_str());
  808. for (auto &node : nodes_) {
  809. REQUIRE_NOT_NULL(subgraph_->AddNode(node),
  810. "[Add][Node] %s to subgraph:%s failed.", node->GetName().c_str(), subgraph_->GetName().c_str());
  811. REQUIRE(AttrUtils::SetBool(node->GetOpDesc(), ATTR_NAME_IS_UNKNOWN_SHAPE, is_unknown_shape),
  812. "[Set][Attr] %s to op:%s failed.", ATTR_NAME_IS_UNKNOWN_SHAPE.c_str(), node->GetName().c_str());
  813. REQUIRE_GRAPH_SUCCESS(GraphUtils::RemoveJustNode(graph, node),
  814. "[Remove][JustNode] failed, graph:%s, node:%s.",
  815. graph->GetName().c_str(), node->GetName().c_str());
  816. REQUIRE_GRAPH_SUCCESS(node->SetOwnerComputeGraph(subgraph_),
  817. "[Set][OwnerComputeGraph] %s for node:%s failed.",
  818. subgraph_->GetName().c_str(), node->GetName().c_str());
  819. for (const auto &anchor : node->GetAllInDataAnchors()) {
  820. auto peer_out_anchor = anchor->GetPeerOutAnchor();
  821. if (peer_out_anchor == nullptr) {
  822. continue; // Skip overhang input.
  823. }
  824. auto src_cluster = partitioner_->node_2_cluster_[peer_out_anchor->GetOwnerNode()];
  825. if (src_cluster->id_ != id_) {
  826. AddFrameInput(anchor);
  827. REQUIRE_GRAPH_SUCCESS(partition_op->AddInputDesc(node->GetOpDesc()->GetInputDesc(anchor->GetIdx())),
  828. "[Add][InputDesc] to op:%s failed.", partition_op->GetName().c_str());
  829. }
  830. }
  831. auto in_control_anchor = node->GetInControlAnchor();
  832. if (in_control_anchor != nullptr) {
  833. for (const auto &peer_out_control_anchor : in_control_anchor->GetPeerOutControlAnchors()) {
  834. if (peer_out_control_anchor == nullptr) {
  835. continue;
  836. }
  837. auto src_cluster = partitioner_->node_2_cluster_[peer_out_control_anchor->GetOwnerNode()];
  838. if (src_cluster->id_ != id_) {
  839. REQUIRE_GRAPH_SUCCESS(
  840. GraphUtils::RemoveEdge(peer_out_control_anchor, in_control_anchor),
  841. "[Remove][Edge] from %s:%d to %s:%d failed.", peer_out_control_anchor->GetOwnerNode()->GetName().c_str(),
  842. peer_out_control_anchor->GetIdx(), node->GetName().c_str(), in_control_anchor->GetIdx());
  843. control_inputs_.insert(src_cluster);
  844. src_cluster->control_outputs_.insert(peer_out_control_anchor);
  845. }
  846. }
  847. }
  848. for (const auto &anchor : node->GetAllOutDataAnchors()) {
  849. auto peer_in_anchors = anchor->GetPeerInDataAnchors();
  850. for (const auto &peer_in_anchor : peer_in_anchors) {
  851. auto src_cluster = partitioner_->node_2_cluster_[peer_in_anchor->GetOwnerNode()];
  852. if (src_cluster->id_ != id_) {
  853. AddFrameOutput(anchor);
  854. REQUIRE_GRAPH_SUCCESS(partition_op->AddOutputDesc(node->GetOpDesc()->GetOutputDesc(anchor->GetIdx())),
  855. "[Add][OutputDesc] to op:%s failed.", partition_op->GetName().c_str());
  856. break;
  857. }
  858. }
  859. }
  860. }
  861. partition_node_ = graph->AddNode(partition_op);
  862. REQUIRE_NOT_NULL(partition_node_,
  863. "[Add][Node] %s to graph:%s failed.", partition_op->GetName().c_str(), graph->GetName().c_str());
  864. REQUIRE_GRAPH_SUCCESS(partition_node_->SetOwnerComputeGraph(graph),
  865. "[Set][OwnerComputeGraph] %s for node:%s failed.",
  866. graph->GetName().c_str(), partition_op->GetName().c_str());
  867. subgraph_->SetParentNode(partition_node_);
  868. subgraph_->SetParentGraph(graph);
  869. REQUIRE_GRAPH_SUCCESS(graph->AddSubgraph(subgraph_),
  870. "[Add][Subgraph] %s to root graph:%s failed.",
  871. subgraph_->GetName().c_str(), graph->GetName().c_str());
  872. std::string session_graph_id;
  873. REQUIRE(AttrUtils::GetStr(*graph, ATTR_NAME_SESSION_GRAPH_ID, session_graph_id),
  874. "[Get][Attr] %s on root graph:%s failed.", ATTR_NAME_SESSION_GRAPH_ID.c_str(), graph->GetName().c_str());
  875. REQUIRE(AttrUtils::SetStr(*subgraph_, ATTR_NAME_SESSION_GRAPH_ID, session_graph_id),
  876. "[Set][Attr] %s on subgraph:%s failed.", ATTR_NAME_SESSION_GRAPH_ID.c_str(), subgraph_->GetName().c_str());
  877. return SUCCESS;
  878. }
  879. Status Cluster::CombinePartitionFrame() {
  880. for (const auto &anchor : inputs_) {
  881. auto peer_out_anchor = anchor->GetPeerOutAnchor();
  882. auto src_cluster = partitioner_->node_2_cluster_[peer_out_anchor->GetOwnerNode()];
  883. auto src_anchor = src_cluster->GetFrameOutDataAnchor(peer_out_anchor);
  884. auto dst_anchor = GetFrameInDataAnchor(anchor);
  885. REQUIRE_GRAPH_SUCCESS(GraphUtils::RemoveEdge(peer_out_anchor, anchor), "[Remove][Edge] from %s:%d to %s:%d fail.",
  886. peer_out_anchor->GetOwnerNode()->GetName().c_str(), peer_out_anchor->GetIdx(),
  887. anchor->GetOwnerNode()->GetName().c_str(), anchor->GetIdx());
  888. REQUIRE_GRAPH_SUCCESS(GraphUtils::AddEdge(src_anchor, dst_anchor), "[Add][Edge] from %s:%d to %s:%d failed.",
  889. src_anchor->GetOwnerNode()->GetName().c_str(), src_anchor->GetIdx(),
  890. dst_anchor->GetOwnerNode()->GetName().c_str(), dst_anchor->GetIdx());
  891. }
  892. for (const auto &src_cluster : control_inputs_) {
  893. auto src_anchor = src_cluster->GetFrameOutControlAnchor();
  894. auto dst_anchor = GetFrameInControlAnchor();
  895. REQUIRE_GRAPH_SUCCESS(GraphUtils::AddEdge(src_anchor, dst_anchor), "[Add][Edge] from %s:%d to %s:%d failed.",
  896. src_anchor->GetOwnerNode()->GetName().c_str(), src_anchor->GetIdx(),
  897. dst_anchor->GetOwnerNode()->GetName().c_str(), dst_anchor->GetIdx());
  898. }
  899. return SUCCESS;
  900. }
  901. Status Cluster::BuildPartitionSubgraph() {
  902. if (IsData() || IsNetOutput() || IsIndependent()) {
  903. return SUCCESS;
  904. }
  905. int64_t parent_node_index = 0;
  906. for (auto anchor : inputs_) {
  907. auto data_op =
  908. MakeShared<OpDesc>(subgraph_->GetName() + std::string("Data_") + std::to_string(parent_node_index), ge::DATA);
  909. REQUIRE_NOT_NULL(data_op, "[New][Memory] for data op failed.");
  910. auto input_desc = anchor->GetOwnerNode()->GetOpDesc()->GetInputDesc(anchor->GetIdx());
  911. REQUIRE_GRAPH_SUCCESS(data_op->AddInputDesc(input_desc),
  912. "[Add][InputDesc] to op:%s failed.", data_op->GetName().c_str());
  913. REQUIRE_GRAPH_SUCCESS(data_op->AddOutputDesc(input_desc),
  914. "[Add][OutputDesc] to op:%s failed.", data_op->GetName().c_str());
  915. REQUIRE(AttrUtils::SetInt(data_op, ATTR_NAME_PARENT_NODE_INDEX, parent_node_index),
  916. "[Set][Attr] %s on subgraph data node:%s failed.",
  917. ATTR_NAME_PARENT_NODE_INDEX.c_str(), data_op->GetName().c_str());
  918. bool is_unknown_shape = IsUnknownShape();
  919. REQUIRE(AttrUtils::SetBool(data_op, ATTR_NAME_IS_UNKNOWN_SHAPE, is_unknown_shape),
  920. "[Set][Attr] %s on data op %s failed.", ATTR_NAME_IS_UNKNOWN_SHAPE.c_str(), data_op->GetName().c_str());
  921. auto data_node = subgraph_->AddNode(data_op);
  922. REQUIRE_NOT_NULL(data_node,
  923. "[Add][Node] %s to subgraph:%s failed.", data_op->GetName().c_str(), subgraph_->GetName().c_str());
  924. REQUIRE_GRAPH_SUCCESS(data_node->SetOwnerComputeGraph(subgraph_),
  925. "[Set][OwnerGraph] %s of data node:%s failed.",
  926. subgraph_->GetName().c_str(), data_op->GetName().c_str());
  927. REQUIRE_GRAPH_SUCCESS(GraphUtils::AddEdge(data_node->GetOutDataAnchor(0), anchor),
  928. "[Call][AddEdge] Failed add data input edge to %s:%d",
  929. anchor->GetOwnerNode()->GetName().c_str(), anchor->GetIdx());
  930. parent_node_index++;
  931. }
  932. if (outputs_.empty() && control_outputs_.empty()) {
  933. return SUCCESS;
  934. }
  935. auto net_output_op = MakeShared<OpDesc>(subgraph_->GetName() + "_" + NODE_NAME_NET_OUTPUT, ge::NETOUTPUT);
  936. REQUIRE_NOT_NULL(net_output_op, "[New][Memory] for netoutput op failed.");
  937. bool is_unknown_shape = IsUnknownShape();
  938. REQUIRE(AttrUtils::SetBool(net_output_op, ATTR_NAME_IS_UNKNOWN_SHAPE, is_unknown_shape),
  939. "[Set][Attr] %s on op:%s failed.", ATTR_NAME_IS_UNKNOWN_SHAPE.c_str(), net_output_op->GetName().c_str());
  940. for (size_t i = 0; i < outputs_.size(); ++i) {
  941. GeTensorDesc input_desc;
  942. REQUIRE_GRAPH_SUCCESS(net_output_op->AddInputDesc(input_desc),
  943. "[Add][InputDesc] to op:%s failed.", net_output_op->GetName().c_str());
  944. }
  945. auto net_output_node = subgraph_->AddNode(net_output_op);
  946. REQUIRE_NOT_NULL(net_output_node,
  947. "[Call][AddNode] Failed add netoutput node:%s to subgraph:%s.",
  948. net_output_op->GetName().c_str(), subgraph_->GetName().c_str());
  949. REQUIRE_GRAPH_SUCCESS(net_output_node->SetOwnerComputeGraph(subgraph_),
  950. "[Set][OwnerGraph] %s of netoutput node:%s failed.",
  951. subgraph_->GetName().c_str(), net_output_node->GetName().c_str());
  952. parent_node_index = 0;
  953. for (const auto &anchor : outputs_) {
  954. auto output_desc = anchor->GetOwnerNode()->GetOpDesc()->GetOutputDesc(static_cast<uint32_t>(anchor->GetIdx()));
  955. REQUIRE(AttrUtils::SetInt(output_desc, ATTR_NAME_PARENT_NODE_INDEX, parent_node_index),
  956. "[Set][Attr] parent_node_index on subgraph node:%s netoutput's input failed.",
  957. anchor->GetOwnerNode()->GetName().c_str());
  958. REQUIRE_GRAPH_SUCCESS(net_output_op->UpdateInputDesc(parent_node_index, output_desc),
  959. "[Update][InputDesc] of netoutput node:%s failed.", net_output_op->GetName().c_str());
  960. REQUIRE_GRAPH_SUCCESS(GraphUtils::AddEdge(anchor, net_output_node->GetInDataAnchor(parent_node_index)),
  961. "[Add][Edge] from %s:%d to netoutput node:%s failed.",
  962. anchor->GetOwnerNode()->GetName().c_str(), anchor->GetIdx(),
  963. net_output_op->GetName().c_str());
  964. parent_node_index++;
  965. }
  966. for (const auto &anchor : control_outputs_) {
  967. REQUIRE_GRAPH_SUCCESS(GraphUtils::AddEdge(anchor, net_output_node->GetInControlAnchor()),
  968. "[Add][ControlEdge] from %s:%d to netoutput node:%s failed.",
  969. anchor->GetOwnerNode()->GetName().c_str(), anchor->GetIdx(),
  970. net_output_op->GetName().c_str());
  971. }
  972. return SUCCESS;
  973. }
  974. void Cluster::Clear() {
  975. in_clusters_.clear();
  976. out_clusters_.clear();
  977. nodes_.clear();
  978. partitioner_ = nullptr;
  979. inputs_index_.clear();
  980. outputs_index_.clear();
  981. inputs_.clear();
  982. outputs_.clear();
  983. control_inputs_.clear();
  984. control_outputs_.clear();
  985. partition_node_.reset();
  986. subgraph_.reset();
  987. unique_id_ = 0;
  988. }
  989. thread_local size_t Cluster::unique_id_ = 0;
  990. } // namespace ge

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