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.

graph_utils.cc 16 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. /**
  2. * This is the C++ adaptation and derivative work of Myia (https://github.com/mila-iqia/myia/).
  3. *
  4. * Copyright 2019 Huawei Technologies Co., Ltd
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. #include "utils/graph_utils.h"
  19. #include <unordered_map>
  20. #include <unordered_set>
  21. #include <utility>
  22. #include <stack>
  23. #include <vector>
  24. #include <list>
  25. #include <string>
  26. #include <fstream>
  27. #include "ir/visitor.h"
  28. #include "utils/log_adapter.h"
  29. #include "common/utils.h"
  30. #include "pipeline/parse/function_block.h"
  31. #include "pipeline/parse/python_adapter.h"
  32. namespace mindspore {
  33. using SymbolicKeyTypePtr = std::shared_ptr<SymbolicKeyType>;
  34. namespace {
  35. class DeepFirstSearcher : public AnfVisitor {
  36. public:
  37. explicit DeepFirstSearcher(const IncludeFunc &include) : include_(include) {}
  38. ~DeepFirstSearcher() override = default;
  39. std::vector<AnfNodePtr> Search(const AnfNodePtr &root) {
  40. if (root == nullptr) {
  41. return res_;
  42. }
  43. Visit(root);
  44. return res_;
  45. }
  46. void Visit(const AnfNodePtr &node) override {
  47. MS_EXCEPTION_IF_NULL(node);
  48. if (seen_.count(node) != 0) {
  49. return;
  50. }
  51. (void)seen_.insert(node);
  52. auto incl = include_(node);
  53. if (incl == EXCLUDE) {
  54. return;
  55. }
  56. res_.push_back(node);
  57. if (incl == FOLLOW) {
  58. AnfVisitor::Visit(node);
  59. }
  60. }
  61. private:
  62. IncludeFunc include_;
  63. std::vector<AnfNodePtr> res_{};
  64. std::set<AnfNodePtr> seen_{};
  65. };
  66. class DeepScopedGraphSearcher : public DeepFirstSearcher {
  67. public:
  68. explicit DeepScopedGraphSearcher(const IncludeFunc &include) : DeepFirstSearcher(include) {}
  69. ~DeepScopedGraphSearcher() override = default;
  70. void Visit(const CNodePtr &cnode) override {
  71. if (cnode->func_graph() == nullptr) {
  72. return;
  73. }
  74. AnfNodePtr ret = cnode->func_graph()->get_return();
  75. if (ret != nullptr) {
  76. DeepFirstSearcher::Visit(ret);
  77. }
  78. auto &inputs = cnode->inputs();
  79. for (auto iter = inputs.rbegin(); iter != inputs.rend(); ++iter) {
  80. DeepFirstSearcher::Visit(*iter);
  81. }
  82. }
  83. void Visit(const ValueNodePtr &vnode) override {
  84. if (!IsValueNode<FuncGraph>(vnode)) {
  85. return;
  86. }
  87. auto graph = GetValueNode<FuncGraphPtr>(vnode);
  88. AnfNodePtr ret = graph->get_return();
  89. if (ret != nullptr) {
  90. DeepFirstSearcher::Visit(ret);
  91. }
  92. }
  93. void Visit(const ParameterPtr &param) override {
  94. if (param->func_graph() == nullptr) {
  95. return;
  96. }
  97. AnfNodePtr ret = param->func_graph()->get_return();
  98. if (ret != nullptr) {
  99. DeepFirstSearcher::Visit(ret);
  100. }
  101. }
  102. };
  103. class DeepUsedGraphSearcher : public DeepFirstSearcher {
  104. public:
  105. explicit DeepUsedGraphSearcher(const IncludeFunc &include) : DeepFirstSearcher(include) {}
  106. ~DeepUsedGraphSearcher() override = default;
  107. void Visit(const CNodePtr &cnode) override {
  108. auto &inputs = cnode->inputs();
  109. for (auto iter = inputs.rbegin(); iter != inputs.rend(); ++iter) {
  110. DeepFirstSearcher::Visit(*iter);
  111. }
  112. }
  113. void Visit(const ValueNodePtr &vnode) override {
  114. if (!IsValueNode<FuncGraph>(vnode)) {
  115. return;
  116. }
  117. auto graph = GetValueNode<FuncGraphPtr>(vnode);
  118. AnfNodePtr ret = graph->get_return();
  119. if (ret != nullptr) {
  120. DeepFirstSearcher::Visit(ret);
  121. }
  122. }
  123. };
  124. class DeepLinkedGraphSearcher : public DeepFirstSearcher {
  125. public:
  126. explicit DeepLinkedGraphSearcher(const IncludeFunc &include) : DeepFirstSearcher(include) {}
  127. ~DeepLinkedGraphSearcher() override = default;
  128. void Visit(const CNodePtr &cnode) override {
  129. auto &inputs = cnode->inputs();
  130. for (auto iter = inputs.rbegin(); iter != inputs.rend(); ++iter) {
  131. DeepFirstSearcher::Visit(*iter);
  132. }
  133. }
  134. void Visit(const ValueNodePtr &) override {}
  135. };
  136. } // namespace
  137. std::vector<AnfNodePtr> DeepScopedGraphSearch(const AnfNodePtr &root, const IncludeFunc &include) {
  138. return DeepScopedGraphSearcher(include).Search(root);
  139. }
  140. std::vector<AnfNodePtr> DeepUsedGraphSearch(const AnfNodePtr &root, const IncludeFunc &include) {
  141. return DeepUsedGraphSearcher(include).Search(root);
  142. }
  143. std::vector<AnfNodePtr> DeepLinkedGraphSearch(const AnfNodePtr &root, const IncludeFunc &include) {
  144. return DeepLinkedGraphSearcher(include).Search(root);
  145. }
  146. std::vector<AnfNodePtr> TopoSort(const AnfNodePtr &root, const SuccFunc &succ, const IncludeFunc &include) {
  147. std::unordered_set<AnfNodePtr> done;
  148. std::list<AnfNodePtr> todo(1, root);
  149. std::unordered_map<AnfNodePtr, size_t> rank;
  150. std::vector<AnfNodePtr> res;
  151. while (!todo.empty()) {
  152. AnfNodePtr node = todo.back();
  153. if (done.find(node) != done.end()) {
  154. todo.pop_back();
  155. continue;
  156. }
  157. if (rank.find(node) != rank.end() && rank[node] != todo.size()) {
  158. MS_LOG(EXCEPTION) << "Graph exists cycle, node " << node->DebugString();
  159. }
  160. rank[node] = todo.size();
  161. bool cont = false;
  162. auto incl = include(node);
  163. if (incl == FOLLOW) {
  164. auto succs = succ(node);
  165. for (const auto i : succs) {
  166. if ((done.find(i) == done.end())
  167. // Handle the case for 2 subgraphs calls each other.
  168. // If the ValueNodeGraph's return is already in the todo list, do not follow it.
  169. && !((std::find(todo.begin(), todo.end(), i) != todo.end()) && (i->func_graph() != nullptr) &&
  170. (i->func_graph()->get_return() == i))) {
  171. todo.push_back(i);
  172. cont = true;
  173. }
  174. }
  175. } else if (incl == NOFOLLOW) {
  176. // do nothing
  177. } else if (incl == EXCLUDE) {
  178. (void)done.insert(node);
  179. todo.pop_back();
  180. continue;
  181. } else {
  182. MS_LOG(EXCEPTION) << "include(node) must return one of: \"follow\", \"nofollow\", \"exclude\"";
  183. }
  184. if (cont) {
  185. continue;
  186. }
  187. (void)done.insert(node);
  188. res.push_back(node);
  189. todo.pop_back();
  190. }
  191. return res;
  192. }
  193. std::vector<AnfNodePtr> SuccDeeper(const AnfNodePtr &node) {
  194. std::vector<AnfNodePtr> vecs;
  195. if (node == nullptr) {
  196. return vecs;
  197. }
  198. if (IsValueNode<FuncGraph>(node)) {
  199. auto graph = GetValueNode<FuncGraphPtr>(node);
  200. auto ret = graph->get_return();
  201. if (ret != nullptr) {
  202. vecs.push_back(ret);
  203. }
  204. return vecs;
  205. } else if (node->func_graph() != nullptr) {
  206. if (node->isa<CNode>()) {
  207. auto &inputs = node->cast<CNodePtr>()->inputs();
  208. (void)vecs.insert(vecs.end(), inputs.begin(), inputs.end());
  209. }
  210. auto graph = node->func_graph();
  211. if (graph->get_return() != nullptr) {
  212. vecs.push_back(graph->get_return());
  213. }
  214. return vecs;
  215. }
  216. return vecs;
  217. }
  218. std::vector<AnfNodePtr> SuccDeeperSimple(const AnfNodePtr &node) {
  219. std::vector<AnfNodePtr> vecs;
  220. if (node == nullptr) {
  221. return vecs;
  222. }
  223. if (IsValueNode<FuncGraph>(node)) {
  224. auto graph = GetValueNode<FuncGraphPtr>(node);
  225. auto ret = graph->get_return();
  226. if (ret != nullptr) {
  227. vecs.push_back(ret);
  228. }
  229. return vecs;
  230. } else {
  231. if (node->isa<CNode>()) {
  232. auto &inputs = node->cast<CNodePtr>()->inputs();
  233. (void)vecs.insert(vecs.end(), inputs.begin(), inputs.end());
  234. }
  235. return vecs;
  236. }
  237. }
  238. std::vector<AnfNodePtr> SuccIncoming(const AnfNodePtr &node) {
  239. std::vector<AnfNodePtr> vecs;
  240. if (node == nullptr) {
  241. return vecs;
  242. }
  243. if (node->isa<CNode>()) {
  244. auto &inputs = node->cast<CNodePtr>()->inputs();
  245. (void)vecs.insert(vecs.end(), inputs.begin(), inputs.end());
  246. }
  247. return vecs;
  248. }
  249. std::vector<AnfNodePtr> SuccIncludeFV(const FuncGraphPtr &fg, const AnfNodePtr &node) {
  250. std::vector<AnfNodePtr> vecs;
  251. if (node == nullptr) {
  252. return vecs;
  253. }
  254. if (node->isa<CNode>()) {
  255. auto cnode = node->cast<CNodePtr>();
  256. auto &inputs = cnode->inputs();
  257. // Check if free variables used.
  258. for (const auto &input : inputs) {
  259. auto input_fg = GetValueNode<FuncGraphPtr>(input);
  260. if (input_fg) {
  261. for (auto &fv : input_fg->free_variables_nodes()) {
  262. if (fv->func_graph() == fg && fg->nodes().contains(fv)) {
  263. vecs.push_back(fv);
  264. }
  265. }
  266. }
  267. }
  268. (void)vecs.insert(vecs.end(), inputs.begin(), inputs.end());
  269. }
  270. return vecs;
  271. }
  272. IncludeType AlwaysInclude(const AnfNodePtr &) { return FOLLOW; }
  273. IncludeType IncludeBelongGraph(const FuncGraphPtr &fg, const AnfNodePtr &node) {
  274. if (node->func_graph() == fg) {
  275. return FOLLOW;
  276. } else {
  277. return EXCLUDE;
  278. }
  279. }
  280. FuncGraphIndex::FuncGraphIndex(const FuncGraphPtr &fg, const SearchFunc &search, const IncludeFunc &include) {
  281. MS_EXCEPTION_IF_NULL(fg);
  282. Acquire(fg);
  283. auto vec = search(fg->get_return(), include);
  284. for (auto &node : vec) {
  285. MS_EXCEPTION_IF_NULL(node);
  286. Acquire(node);
  287. if (node->func_graph() != nullptr) {
  288. Acquire(node->func_graph());
  289. }
  290. }
  291. }
  292. std::set<FuncGraphPtr> FuncGraphIndex::GetFuncGraphs(const std::string &key) {
  293. std::set<FuncGraphPtr> func_graphs;
  294. if (index_func_graph_.find(key) != index_func_graph_.end()) {
  295. func_graphs = index_func_graph_[key];
  296. }
  297. return func_graphs;
  298. }
  299. std::set<AnfNodePtr> FuncGraphIndex::GetNodes(const std::string &key) {
  300. if (index_node_.find(key) != index_node_.end()) {
  301. return index_node_[key];
  302. }
  303. return std::set<AnfNodePtr>();
  304. }
  305. FuncGraphPtr FuncGraphIndex::GetFirstFuncGraph(const std::string &key) {
  306. if (GetFuncGraphs(key).empty()) {
  307. return nullptr;
  308. }
  309. auto fg = *GetFuncGraphs(key).begin();
  310. return fg;
  311. }
  312. AnfNodePtr FuncGraphIndex::GetFirstNode(const std::string &key) {
  313. if (GetNodes(key).empty()) {
  314. return nullptr;
  315. }
  316. auto node = *GetNodes(key).begin();
  317. return node;
  318. }
  319. void FuncGraphIndex::Acquire(const FuncGraphPtr &key) {
  320. std::string name = label_manage::Label(key->debug_info());
  321. if (!name.empty()) {
  322. (void)index_func_graph_[name].insert(key);
  323. }
  324. }
  325. void FuncGraphIndex::Acquire(const AnfNodePtr &key) {
  326. std::string name = label_manage::Label(key->debug_info());
  327. if (!name.empty()) {
  328. (void)index_node_[name].insert(key);
  329. }
  330. }
  331. // Isomorphism
  332. static bool SameNodeShallow(const AnfNodePtr &node1, const AnfNodePtr &node2, FuncGraphPairMapEquiv *equiv_func_graph,
  333. NodeMapEquiv *const equiv_node) {
  334. if (equiv_node == nullptr) {
  335. MS_LOG(ERROR) << "Invalid equiv_node";
  336. return false;
  337. }
  338. if (equiv_node->count(node1) > 0 && (*equiv_node)[node1] == node2) {
  339. return true;
  340. }
  341. if (IsValueNode<FuncGraph>(node1) && IsValueNode<FuncGraph>(node2)) {
  342. return Isomorphic(GetValueNode<FuncGraphPtr>(node1), GetValueNode<FuncGraphPtr>(node2), equiv_func_graph,
  343. equiv_node);
  344. }
  345. if (node1->isa<ValueNode>() && node2->isa<ValueNode>()) {
  346. auto a1 = GetValueNode(node1);
  347. auto a2 = GetValueNode(node2);
  348. if (a1->isa<Primitive>() && a2->isa<Primitive>()) {
  349. return a1->cast<PrimitivePtr>()->name() == a2->cast<PrimitivePtr>()->name();
  350. } else if (a1->isa<tensor::Tensor>() && a2->isa<tensor::Tensor>()) {
  351. return a1->cast<tensor::TensorPtr>()->ValueEqual(*(a2->cast<tensor::TensorPtr>()));
  352. } else {
  353. return *a1 == *a2;
  354. }
  355. }
  356. if (node1->isa<Parameter>() && node2->isa<Parameter>()) {
  357. auto para1 = node1->cast<ParameterPtr>();
  358. auto para2 = node2->cast<ParameterPtr>();
  359. if (para1->name() == para2->name()) {
  360. return true;
  361. }
  362. MS_LOG(DEBUG) << "two parameters are not equal.";
  363. return false;
  364. }
  365. MS_LOG(ERROR) << "type error";
  366. return false;
  367. }
  368. static bool SameNode(const AnfNodePtr &node1, const AnfNodePtr &node2, FuncGraphPairMapEquiv *equiv_func_graph,
  369. NodeMapEquiv *const equiv_node) {
  370. MS_EXCEPTION_IF_NULL(node1);
  371. MS_EXCEPTION_IF_NULL(node2);
  372. if (node1->isa<CNode>() && node2->isa<CNode>()) {
  373. auto &inputs1 = node1->cast<CNodePtr>()->inputs();
  374. auto &inputs2 = node2->cast<CNodePtr>()->inputs();
  375. for (std::size_t i = 0; i < inputs1.size(); ++i) {
  376. if (!SameNodeShallow(inputs1[i], inputs2[i], equiv_func_graph, equiv_node)) {
  377. return false;
  378. }
  379. }
  380. return true;
  381. }
  382. return SameNodeShallow(node1, node2, equiv_func_graph, equiv_node);
  383. }
  384. static bool SameSubgraph(AnfNodePtr root1, AnfNodePtr root2, FuncGraphPairMapEquiv *equiv_func_graph,
  385. NodeMapEquiv *const equiv_node) {
  386. std::unordered_set<AnfNodePtr> done;
  387. std::stack<std::pair<AnfNodePtr, AnfNodePtr>> todo;
  388. todo.push(std::make_pair(root1, root2));
  389. while (todo.size() > 0) {
  390. AnfNodePtr node1 = todo.top().first;
  391. if (done.count(node1) > 0) {
  392. todo.pop();
  393. continue;
  394. }
  395. AnfNodePtr node2 = todo.top().second;
  396. bool condition = false;
  397. std::vector<AnfNodePtr> s1 = SuccIncoming(node1);
  398. std::vector<AnfNodePtr> s2 = SuccIncoming(node2);
  399. if (s1.size() != s2.size()) {
  400. return false;
  401. }
  402. for (std::size_t i = 0; i < s1.size(); ++i) {
  403. if (done.count(s1[i]) == 0) {
  404. todo.push(std::make_pair(s1[i], s2[i]));
  405. condition = true;
  406. }
  407. }
  408. if (condition) {
  409. continue;
  410. }
  411. (void)done.insert(node1);
  412. auto res = SameNode(node1, node2, equiv_func_graph, equiv_node);
  413. if (res) {
  414. (*equiv_node)[node1] = node2;
  415. } else {
  416. return false;
  417. }
  418. todo.pop();
  419. }
  420. return true;
  421. }
  422. bool Isomorphic(FuncGraphPtr fg1, FuncGraphPtr fg2, FuncGraphPairMapEquiv *equiv_func_graph,
  423. NodeMapEquiv *const equiv_node) {
  424. auto fg1_fg2 = std::make_pair(fg1, fg2);
  425. if (equiv_func_graph == nullptr) {
  426. MS_LOG(ERROR) << "equiv_func_graph not init";
  427. return false;
  428. }
  429. if (equiv_func_graph->find(fg1_fg2) != equiv_func_graph->end()) {
  430. return (*equiv_func_graph)[fg1_fg2] != kNotEquiv;
  431. }
  432. if (fg1 == nullptr || fg2 == nullptr) {
  433. MS_LOG(ERROR) << "Invalid function graph";
  434. return false;
  435. }
  436. if (fg1->parameters().size() != fg2->parameters().size()) {
  437. MS_LOG(DEBUG) << "parameters size not match";
  438. return false;
  439. }
  440. if (equiv_node != nullptr) {
  441. for (std::size_t i = 0; i < fg1->parameters().size(); ++i) {
  442. (*equiv_node)[fg1->parameters()[i]] = fg2->parameters()[i];
  443. }
  444. (*equiv_func_graph)[fg1_fg2] = kPending;
  445. auto result = SameSubgraph(fg1->get_return(), fg2->get_return(), equiv_func_graph, equiv_node);
  446. (*equiv_func_graph)[fg1_fg2] = EquivState(result);
  447. return result;
  448. }
  449. MS_LOG(ERROR) << "equiv_node not init";
  450. return false;
  451. }
  452. tensor::TensorPtr ScalarToTensor(const ScalarPtr &scalar) {
  453. if (scalar == nullptr) {
  454. MS_EXCEPTION(ArgumentError) << "Nullptr Error!";
  455. }
  456. tensor::TensorPtr tensor = nullptr;
  457. if (scalar->isa<FloatImm>()) {
  458. tensor = std::make_shared<tensor::Tensor>(py::float_(GetValue<float>(scalar)), kFloat32);
  459. } else if (scalar->isa<IntergerImm>()) {
  460. tensor = std::make_shared<tensor::Tensor>(py::int_(GetValue<int>(scalar)), kInt32);
  461. } else if (scalar->isa<BoolImm>()) {
  462. tensor = std::make_shared<tensor::Tensor>(py::array(py::bool_(GetValue<bool>(scalar))), kBool);
  463. } else {
  464. auto type = scalar->type();
  465. auto type_str = (type == nullptr) ? "nullptr" : type->ToString();
  466. MS_LOG(EXCEPTION) << "Invalid scalar type: " << type_str;
  467. }
  468. MS_EXCEPTION_IF_NULL(tensor);
  469. return tensor;
  470. }
  471. } // namespace mindspore