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

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