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.

transform.cc 31 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  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 "vm/transform.h"
  19. #include <algorithm>
  20. #include <map>
  21. #include <queue>
  22. #include <stack>
  23. #include <set>
  24. #include <string>
  25. #include <vector>
  26. #include "abstract/abstract_value.h"
  27. #ifdef ENABLE_GE
  28. #include "transform/graph_ir/convert.h"
  29. #endif
  30. #include "ir/graph_utils.h"
  31. #include "utils/ms_context.h"
  32. #include "debug/trace.h"
  33. #include "debug/anf_ir_dump.h"
  34. namespace mindspore {
  35. namespace compile {
  36. using mindspore::abstract::AbstractFunction;
  37. using mindspore::abstract::AbstractFunctionPtr;
  38. using PrimTypePair = std::pair<PrimitivePtr, AbstractFunctionPtr>;
  39. using MapPrimTypeFuncGraph = std::map<PrimTypePair, FuncGraphPtr>;
  40. using TypedPrimitiveAbstractClosurePtr = std::shared_ptr<abstract::TypedPrimitiveAbstractClosure>;
  41. std::vector<PrimitivePtr> nonlinear_ops = {prim::kPrimReturn, prim::kPrimPartial, prim::kPrimSwitch,
  42. prim::kPrimMakeTuple, prim::kPrimBpropCut};
  43. const std::vector<PrimitivePtr> &GetMsNonlinearOps() {
  44. static const std::vector<PrimitivePtr> ms_nonlinear_ops = {prim::kPrimReturn, prim::kPrimPartial,
  45. prim::kPrimSwitch, prim::kPrimMakeTuple,
  46. prim::kPrimBpropCut, prim::kPrimSwitchLayer};
  47. return ms_nonlinear_ops;
  48. }
  49. namespace {
  50. bool ContainMultiTarget(const std::vector<AnfNodePtr> &nodes) {
  51. auto context_ptr = MsContext::GetInstance();
  52. MS_EXCEPTION_IF_NULL(context_ptr);
  53. std::string last_target = context_ptr->device_target();
  54. for (auto &node : nodes) {
  55. if (node->isa<CNode>()) {
  56. std::string cur_target = GetCNodeTarget(node);
  57. if (last_target != cur_target) {
  58. return true;
  59. }
  60. last_target = cur_target;
  61. }
  62. }
  63. return false;
  64. }
  65. bool ExtractNodes(const FuncGraphPtr &graph, const AnfNodePtr &prior_node, const AnfNodePtr &behind_node,
  66. std::vector<AnfNodePtr> *prior_nodes, std::vector<AnfNodePtr> *depend_nodes) {
  67. MS_EXCEPTION_IF_NULL(prior_node);
  68. MS_EXCEPTION_IF_NULL(behind_node);
  69. MS_EXCEPTION_IF_NULL(graph);
  70. auto manager = graph->manager();
  71. MS_EXCEPTION_IF_NULL(manager);
  72. auto &node_users = manager->node_users();
  73. if (prior_node->isa<Parameter>()) {
  74. for (auto &user : node_users[prior_node]) {
  75. auto cnode = user.first->cast<CNodePtr>();
  76. MS_EXCEPTION_IF_NULL(cnode);
  77. if (!IsPrimitiveCNode(cnode, prim::kPrimControlDepend)) {
  78. prior_nodes->emplace_back(cnode);
  79. }
  80. }
  81. } else if (!IsPrimitiveCNode(prior_node, prim::kPrimControlDepend)) {
  82. prior_nodes->emplace_back(prior_node);
  83. } else {
  84. return false;
  85. }
  86. if (behind_node->isa<Parameter>()) {
  87. for (auto &user : node_users[behind_node]) {
  88. auto cnode = user.first->cast<CNodePtr>();
  89. MS_EXCEPTION_IF_NULL(cnode);
  90. if (!IsPrimitiveCNode(cnode, prim::kPrimControlDepend)) {
  91. depend_nodes->emplace_back(cnode);
  92. }
  93. }
  94. } else if (!IsPrimitiveCNode(behind_node, prim::kPrimControlDepend)) {
  95. depend_nodes->emplace_back(behind_node);
  96. } else {
  97. return false;
  98. }
  99. return true;
  100. }
  101. void AddControlEdge(const FuncGraphPtr &graph, const AnfNodePtr &node,
  102. std::map<AnfNodePtr, std::vector<AnfNodePtr>> *control_edges,
  103. std::map<AnfNodePtr, size_t> *nodes_ref) {
  104. MS_EXCEPTION_IF_NULL(node);
  105. auto input_cnode = node->cast<CNodePtr>();
  106. MS_EXCEPTION_IF_NULL(input_cnode);
  107. auto prior_node = input_cnode->input(kControlDependPriorIndex);
  108. auto depend_node = input_cnode->input(kControlDependBehindIndex);
  109. MS_EXCEPTION_IF_NULL(prior_node);
  110. MS_EXCEPTION_IF_NULL(depend_node);
  111. PrimitivePtr prim_ptr = GetValueNode<PrimitivePtr>(input_cnode->input(0));
  112. MS_EXCEPTION_IF_NULL(prim_ptr);
  113. ValuePtr mode_ptr = prim_ptr->GetAttr("depend_mode");
  114. int depend_mode = 0;
  115. if (mode_ptr != nullptr) {
  116. depend_mode = GetValue<int>(mode_ptr);
  117. }
  118. if ((prior_node->isa<Parameter>() || depend_node->isa<Parameter>()) && depend_mode == 0) {
  119. return;
  120. }
  121. std::vector<AnfNodePtr> prior_nodes;
  122. std::vector<AnfNodePtr> behind_nodes;
  123. if (!ExtractNodes(graph, prior_node, depend_node, &prior_nodes, &behind_nodes)) {
  124. return;
  125. }
  126. for (auto &first_node : prior_nodes) {
  127. for (auto &second_node : behind_nodes) {
  128. MS_EXCEPTION_IF_NULL(first_node);
  129. MS_EXCEPTION_IF_NULL(second_node);
  130. auto iter = control_edges->find(second_node);
  131. if (iter == control_edges->end()) {
  132. (void)control_edges->insert(
  133. std::pair<AnfNodePtr, std::vector<AnfNodePtr>>(second_node, std::vector<AnfNodePtr>{first_node}));
  134. } else {
  135. iter->second.emplace_back(first_node);
  136. }
  137. auto ref_iter = nodes_ref->find(first_node);
  138. if (ref_iter != nodes_ref->end()) {
  139. ref_iter->second++;
  140. } else {
  141. (void)nodes_ref->insert(std::pair<AnfNodePtr, size_t>(first_node, 1));
  142. }
  143. }
  144. }
  145. }
  146. void CalcNodeRefCount(const FuncGraphPtr &graph, std::map<AnfNodePtr, size_t> *nodes_ref,
  147. std::map<AnfNodePtr, std::vector<AnfNodePtr>> *control_edges) {
  148. std::queue<AnfNodePtr> queue;
  149. queue.push(graph->get_return());
  150. std::set<AnfNodePtr> visited;
  151. while (!queue.empty()) {
  152. auto &node = queue.front();
  153. queue.pop();
  154. MS_EXCEPTION_IF_NULL(node);
  155. if (!node->isa<CNode>()) {
  156. continue;
  157. }
  158. auto cnode = node->cast<CNodePtr>();
  159. MS_EXCEPTION_IF_NULL(cnode);
  160. for (auto &input : cnode->inputs()) {
  161. if (IsPrimitiveCNode(input, prim::kPrimControlDepend)) {
  162. AddControlEdge(graph, input, control_edges, nodes_ref);
  163. }
  164. auto iter = nodes_ref->find(input);
  165. if (iter != nodes_ref->end()) {
  166. iter->second++;
  167. } else {
  168. (void)nodes_ref->insert(std::pair<AnfNodePtr, size_t>(input, 1));
  169. }
  170. if (visited.find(input) != visited.end()) {
  171. continue;
  172. }
  173. visited.insert(input);
  174. queue.push(input);
  175. }
  176. }
  177. }
  178. std::vector<AnfNodePtr> OptimizeGetItemOrder(const std::vector<AnfNodePtr> &nodes) {
  179. std::vector<AnfNodePtr> result;
  180. std::map<size_t, std::vector<AnfNodePtr>> insert_positions;
  181. std::map<AnfNodePtr, size_t> node_positions;
  182. for (auto &node : nodes) {
  183. if (node->isa<CNode>() && IsPrimitiveCNode(node, prim::kPrimTupleGetItem)) {
  184. auto cnode = node->cast<CNodePtr>();
  185. MS_EXCEPTION_IF_NULL(cnode);
  186. auto &inputs = cnode->inputs();
  187. if (inputs.size() < 2) {
  188. MS_LOG(EXCEPTION) << "Invalid get item node";
  189. }
  190. auto &parent = inputs[1];
  191. auto iter = node_positions.find(parent);
  192. if (iter != node_positions.end()) {
  193. size_t position = iter->second;
  194. auto iter_nodes = insert_positions.find(position);
  195. if (iter_nodes != insert_positions.end()) {
  196. iter_nodes->second.push_back(node);
  197. } else {
  198. (void)insert_positions.insert(
  199. std::pair<size_t, std::vector<AnfNodePtr>>(position, std::vector<AnfNodePtr>{node}));
  200. }
  201. continue;
  202. }
  203. }
  204. result.emplace_back(node);
  205. node_positions[node] = result.size();
  206. }
  207. size_t insert_num = 0;
  208. for (auto &item : insert_positions) {
  209. size_t position = item.first + insert_num;
  210. (void)result.insert(result.begin() + position, item.second.begin(), item.second.end());
  211. insert_num += item.second.size();
  212. }
  213. return result;
  214. }
  215. std::vector<AnfNodePtr> SplitSort(const FuncGraphPtr &graph, const std::string &default_target) {
  216. std::vector<AnfNodePtr> result;
  217. std::stack<AnfNodePtr> to_visit;
  218. std::stack<AnfNodePtr> next_to_visit;
  219. std::map<AnfNodePtr, size_t> nodes_ref;
  220. std::map<AnfNodePtr, std::vector<AnfNodePtr>> control_edges;
  221. CalcNodeRefCount(graph, &nodes_ref, &control_edges);
  222. std::string handle_target = default_target;
  223. std::string next_target = "";
  224. to_visit.push(graph->get_return());
  225. while (!to_visit.empty() || !next_to_visit.empty()) {
  226. if (to_visit.empty()) {
  227. to_visit.swap(next_to_visit);
  228. handle_target = next_target;
  229. }
  230. auto &node = to_visit.top();
  231. MS_EXCEPTION_IF_NULL(node);
  232. to_visit.pop();
  233. result.emplace_back(node);
  234. if (!node->isa<CNode>()) {
  235. continue;
  236. }
  237. auto cnode = node->cast<CNodePtr>();
  238. MS_EXCEPTION_IF_NULL(cnode);
  239. auto node_inputs = cnode->inputs();
  240. std::reverse(node_inputs.begin(), node_inputs.end());
  241. auto ctrl_inputs = control_edges.find(node);
  242. if (ctrl_inputs != control_edges.end()) {
  243. node_inputs.insert(node_inputs.end(), ctrl_inputs->second.begin(), ctrl_inputs->second.end());
  244. }
  245. for (auto &input : node_inputs) {
  246. auto iter = nodes_ref.find(input);
  247. if (iter != nodes_ref.end()) {
  248. iter->second--;
  249. if (iter->second != 0) {
  250. continue;
  251. }
  252. }
  253. if (!input->isa<CNode>()) {
  254. to_visit.push(input);
  255. continue;
  256. }
  257. std::string input_target = GetCNodeTarget(input);
  258. if (input_target == handle_target) {
  259. to_visit.push(input);
  260. } else if (next_to_visit.empty() || input_target == next_target) {
  261. next_to_visit.push(input);
  262. next_target = input_target;
  263. } else {
  264. MS_LOG(EXCEPTION) << "only support two different target";
  265. }
  266. }
  267. }
  268. std::reverse(result.begin(), result.end());
  269. return result;
  270. }
  271. bool IsSubGraph(const AnfNodePtr &node) {
  272. MS_EXCEPTION_IF_NULL(node);
  273. if (node->isa<CNode>()) {
  274. auto cnode = node->cast<CNodePtr>();
  275. auto &inputs = cnode->inputs();
  276. if (inputs.empty()) {
  277. MS_LOG(EXCEPTION) << "Inputs of apply node is empty";
  278. }
  279. AnfNodePtr fn = inputs[0];
  280. if (!IsValueNode<Primitive>(fn)) {
  281. return false;
  282. }
  283. auto node_prim = GetValueNode<PrimitivePtr>(fn);
  284. if (node_prim->name() == prim::kPrimPartial->name()) {
  285. return true;
  286. }
  287. } else if (IsValueNode<FuncGraph>(node)) {
  288. return true;
  289. }
  290. return false;
  291. }
  292. } // namespace
  293. CompileGraph::CompileGraph(const BackendPtr &backend, const std::vector<PrimitivePtr> &cut_list)
  294. : backend_(backend), cut_list_(cut_list) {
  295. MS_EXCEPTION_IF_NULL(backend_);
  296. lin_convert_ = backend_->convert_fn();
  297. if (lin_convert_ == nullptr) {
  298. MS_LOG(EXCEPTION) << "Attribute 'lin_convert' is null.: " << backend->name();
  299. }
  300. is_gevm_convert_ = false;
  301. if (backend->name() == kGeVm) {
  302. MS_LOG(INFO) << "Attribute 'is_gevm_convert' is true";
  303. is_gevm_convert_ = true;
  304. }
  305. }
  306. bool CompileGraph::IsCut(const AnfNodePtr &node) {
  307. MS_EXCEPTION_IF_NULL(node);
  308. if (node->isa<CNode>()) {
  309. auto cnode = node->cast<CNodePtr>();
  310. auto &inputs = cnode->inputs();
  311. if (inputs.empty()) {
  312. MS_LOG(EXCEPTION) << "Inputs of apply node is empty";
  313. }
  314. AnfNodePtr fn = inputs[0];
  315. if (IsValueNode<FuncGraph>(fn)) {
  316. auto fg = GetValueNode<FuncGraphPtr>(fn);
  317. if (fg->has_attr(FUNC_GRAPH_ATTR_GRAPH_KERNEL)) {
  318. return false;
  319. }
  320. }
  321. if (!IsValueNode<Primitive>(fn)) {
  322. return true;
  323. }
  324. PrimitivePtr node_prim = GetValueNode<PrimitivePtr>(fn);
  325. for (auto &prim : cut_list_) {
  326. MS_EXCEPTION_IF_NULL(prim);
  327. if (prim->name() == node_prim->name()) {
  328. if (prim->name() == prim::kPrimBpropCut->name()) {
  329. auto ms_context = MsContext::GetInstance();
  330. MS_EXCEPTION_IF_NULL(ms_context);
  331. ms_context->set_enable_pynative_hook(true);
  332. }
  333. if (backend_->name() == kMsConvert && prim->name() == prim::kPrimMakeTuple->name()) {
  334. if (inputs.size() < 2) {
  335. return false;
  336. }
  337. auto ret = IsSubGraph(inputs[1]);
  338. return ret;
  339. }
  340. return true;
  341. }
  342. }
  343. #ifdef ENABLE_GE
  344. if (is_gevm_convert_) {
  345. auto name = GetCNodeFuncName(cnode);
  346. auto adpt = transform::DfGraphConvertor::FindAdapter(name);
  347. if (adpt == nullptr) {
  348. return true;
  349. }
  350. }
  351. #endif
  352. }
  353. return false;
  354. }
  355. VectorRef CompileGraph::SplitNodesWithTarget(const std::vector<AnfNodePtr> &input_nodes, const FuncGraphPtr &graph) {
  356. MS_EXCEPTION_IF_NULL(graph);
  357. auto nodes = OptimizeGetItemOrder(input_nodes);
  358. VectorRef splits;
  359. VectorRef split;
  360. std::string last_target;
  361. for (auto &node : nodes) {
  362. MS_EXCEPTION_IF_NULL(node);
  363. if (IsCut(node)) {
  364. if (split.size() != 0) {
  365. splits.push_back(split);
  366. }
  367. splits.push_back(node);
  368. split.clear();
  369. } else if (node->isa<CNode>()) {
  370. std::string cur_target = GetCNodeTarget(node);
  371. if (cur_target != last_target && !last_target.empty() && split.size() != 0) {
  372. splits.push_back(split);
  373. split.clear();
  374. }
  375. last_target = cur_target;
  376. split.push_back(node);
  377. }
  378. }
  379. return splits;
  380. }
  381. VectorRef CompileGraph::SplitNodes(const FuncGraphPtr &graph) {
  382. MS_EXCEPTION_IF_NULL(graph);
  383. auto nodes = TopoSort(graph->get_return());
  384. MS_LOG(DEBUG) << "Split all nodes size:" << nodes.size();
  385. if (ContainMultiTarget(nodes)) {
  386. auto context_ptr = MsContext::GetInstance();
  387. MS_EXCEPTION_IF_NULL(context_ptr);
  388. std::string default_target = context_ptr->device_target();
  389. nodes = SplitSort(graph, default_target);
  390. return SplitNodesWithTarget(nodes, graph);
  391. }
  392. VectorRef splits;
  393. VectorRef split;
  394. for (auto &node : nodes) {
  395. MS_EXCEPTION_IF_NULL(node);
  396. if (IsCut(node)) {
  397. if (split.size() != 0) {
  398. splits.push_back(split);
  399. }
  400. splits.push_back(node);
  401. split.clear();
  402. } else if (node->isa<CNode>()) {
  403. split.push_back(node);
  404. }
  405. }
  406. return splits;
  407. }
  408. // Push the value node on the stack.
  409. void CompileGraph::Push(const AnfNodePtr &node) {
  410. MS_EXCEPTION_IF_NULL(node);
  411. if (slots_.count(node) > 0) {
  412. MS_LOG(EXCEPTION) << "Push failed node in slots:" << node->DebugString()
  413. << " NodeInfo: " << trace::GetDebugInfo(node->debug_info());
  414. }
  415. MS_LOG(DEBUG) << "Push node: " << node->DebugString(true) << " height_: " << height_
  416. << " is parameter: " << node->isa<Parameter>();
  417. slots_[node] = height_;
  418. set_height(height_ + 1);
  419. }
  420. void CompileGraph::AddInst(const Instruction &inst, const int &arg) {
  421. VectorRef args;
  422. args.push_back(arg);
  423. AddInst(inst, args);
  424. }
  425. void CompileGraph::AddInst(const Instruction &inst, const ValuePtr &arg) {
  426. VectorRef args;
  427. args.push_back(arg);
  428. AddInst(inst, args);
  429. }
  430. void CompileGraph::AddInst(const Instruction &inst, const VectorRef &args) {
  431. inst_.push_back(std::make_pair(inst, args));
  432. }
  433. // Gets the stack reference for the node value. If the node is a constant,
  434. // it may actually cause the push in to not be mentioned before.
  435. int CompileGraph::Ref(const AnfNodePtr &node) {
  436. MS_EXCEPTION_IF_NULL(node);
  437. MS_LOG(DEBUG) << "Start Ref node " << node->DebugString(true) << " height_: " << height_;
  438. if (slots_.count(node) == 0 && node->isa<ValueNode>()) {
  439. if (IsValueNode<FuncGraph>(node)) {
  440. MS_LOG(DEBUG) << "Push graph.";
  441. AddInst(Instruction::kGraph, GetValueNode(node));
  442. } else {
  443. MS_LOG(DEBUG) << "Push.";
  444. if (IsValueNode<Primitive>(node)) {
  445. MS_LOG(EXCEPTION) << "must not be primitive in here NodeInfo: " << trace::GetDebugInfo(node->debug_info());
  446. } else {
  447. AddInst(Instruction::kPush, GetValueNode(node));
  448. }
  449. }
  450. Push(node);
  451. }
  452. MS_LOG(DEBUG) << "End Ref node end height_: " << height_ << ", slots: " << slots_[node]
  453. << ", return: " << slots_[node] - height_;
  454. return slots_[node] - height_;
  455. }
  456. // Make sure the value of node is at the top of the stack.
  457. void CompileGraph::AddInput(const AnfNodePtr &node) {
  458. MS_EXCEPTION_IF_NULL(node);
  459. if (slots_.count(node) == 0) {
  460. MS_LOG(DEBUG) << "Input node is null " << node->DebugString(true);
  461. (void)Ref(node);
  462. return;
  463. }
  464. AddInst(Instruction::kInput, Ref(node));
  465. set_height(height_ + 1);
  466. }
  467. // Call back effect in stack
  468. void CompileGraph::Ret(int nargs) { set_height(height_ - nargs); }
  469. void CompileGraph::PushParameters(const FuncGraphPtr &graph) {
  470. MS_EXCEPTION_IF_NULL(graph);
  471. std::vector<AnfNodePtr> parameters = graph->parameters();
  472. for (size_t i = parameters.size(); i != 0; i--) {
  473. Push(parameters[i - 1]);
  474. MS_LOG(DEBUG) << "Push parameter " << i - 1 << ": " << parameters[i - 1]->DebugString(true);
  475. }
  476. }
  477. int CompileGraph::LinConvert(const FuncGraphPtr &graph, const AnfNodePtrList &node_list, const std::string &target) {
  478. MS_LOG(DEBUG) << "LinConvert start";
  479. LinConvertResult result;
  480. result = lin_convert_(node_list, target);
  481. if (result.run == nullptr) {
  482. MS_LOG(ERROR) << "LinConvert failed";
  483. return RET_FAILED;
  484. }
  485. if (!(*result.run)) {
  486. if (result.inputs.size() != result.outputs.size()) {
  487. MS_EXCEPTION_IF_NULL(graph);
  488. MS_LOG(EXCEPTION) << "must inputs equal outputs NodeInfo: " << trace::GetDebugInfo(graph->debug_info());
  489. } else {
  490. size_t size = result.inputs.size();
  491. for (size_t i = 0; i < size; i++) {
  492. Tie(result.inputs[i], result.outputs[i]);
  493. }
  494. return RET_CONTINUE;
  495. }
  496. }
  497. AddExternal(result);
  498. for (auto &o : result.outputs) {
  499. Push(o);
  500. }
  501. return RET_SUCCESS;
  502. }
  503. int CompileGraph::InterpretNode(const FuncGraphPtr &graph, const CNodePtr &node) {
  504. MS_EXCEPTION_IF_NULL(node);
  505. MS_LOG(DEBUG) << "Interpret node: " << node->DebugString(true);
  506. std::vector<AnfNodePtr> node_inputs = node->inputs();
  507. if (node_inputs.empty()) {
  508. MS_LOG(EXCEPTION) << "The node->inputs() is empty";
  509. }
  510. AnfNodePtr fn = node_inputs[0];
  511. if (IsValueNode<Primitive>(fn)) {
  512. PrimitivePtr value = GetValueNode<PrimitivePtr>(fn);
  513. MS_LOG(DEBUG) << "The fn is primitive " << (*value).name();
  514. for (size_t i = node_inputs.size() - 1; i > 0; i--) {
  515. AddInput(node->input(i));
  516. }
  517. if (IsPrimitive(fn, prim::kPrimReturn)) {
  518. AddReturn(node);
  519. return RET_BREAK;
  520. }
  521. if (IsPrimitive(fn, prim::kPrimPartial)) {
  522. AddPartial(node);
  523. } else if (IsPrimitive(fn, prim::kPrimSwitch)) {
  524. AddSwitch(node);
  525. } else if (IsPrimitive(fn, prim::kPrimSwitchLayer)) {
  526. AddSwitchLayer(node);
  527. } else if (IsPrimitive(fn, prim::kPrimMakeTuple)) {
  528. AddMakeTuple(node);
  529. } else {
  530. AddPrimitive(node, value);
  531. }
  532. } else {
  533. int ret = AddCall(graph, node);
  534. if (ret == RET_BREAK) {
  535. return ret;
  536. }
  537. }
  538. Push(node);
  539. return RET_SUCCESS;
  540. }
  541. bool CompileGraph::SplitGraph(const FuncGraphPtr &graph) {
  542. MS_LOG(DEBUG) << "Start split graph";
  543. MS_EXCEPTION_IF_NULL(graph);
  544. VectorRef splits = SplitNodes(graph);
  545. MS_LOG(DEBUG) << "Split nodes size:" << splits.size();
  546. for (auto &split : splits) {
  547. int ret = RET_SUCCESS;
  548. if (utils::isa<VectorRef>(split)) {
  549. MS_LOG(DEBUG) << "Start a extern LinConvert";
  550. std::vector<AnfNodePtr> args;
  551. auto vec_ref = utils::cast<VectorRef>(split);
  552. (void)std::transform(vec_ref.begin(), vec_ref.end(), std::back_inserter(args),
  553. [](const BaseRef &v) { return utils::cast<AnfNodePtr>(v); });
  554. if (args.size() > 0) {
  555. std::string cur_target = GetCNodeTarget(args[0]);
  556. ret = LinConvert(graph, args, cur_target);
  557. } else {
  558. ret = LinConvert(graph, args);
  559. }
  560. MS_LOG(DEBUG) << "End a extern LinConvert";
  561. if (ret == RET_FAILED) {
  562. return false;
  563. }
  564. if (ret == RET_CONTINUE) {
  565. continue;
  566. }
  567. } else {
  568. MS_LOG(DEBUG) << "Start a cut node";
  569. if (!(utils::isa<AnfNodePtr>(split) && utils::cast<AnfNodePtr>(split)->isa<CNode>())) {
  570. MS_LOG(EXCEPTION) << "must be anfnode here NodeInfo: " << trace::GetDebugInfo(graph->debug_info());
  571. }
  572. CNodePtr node = utils::cast<AnfNodePtr>(split)->cast<CNodePtr>();
  573. ret = InterpretNode(graph, node);
  574. MS_LOG(DEBUG) << "End a cut node";
  575. if (ret == RET_BREAK) {
  576. break;
  577. }
  578. }
  579. }
  580. MS_LOG(DEBUG) << "End split graph";
  581. return true;
  582. }
  583. InstSet CompileGraph::Run(const FuncGraphPtr &graph) {
  584. MS_EXCEPTION_IF_NULL(graph);
  585. Reset();
  586. PushParameters(graph);
  587. int param_height = height_;
  588. MS_LOG(DEBUG) << "'param_height': " << height_ << " to split graph: " << graph->get_return()->DebugString(true);
  589. if (!SplitGraph(graph)) {
  590. return inst_;
  591. }
  592. AddPadStack(param_height);
  593. auto ret = inst_;
  594. Reset();
  595. return ret;
  596. }
  597. void CompileGraph::AddPadStack(int param_height) {
  598. int stack_sizes = max_height_ - param_height;
  599. MS_LOG(DEBUG) << "Pad stack max_height_:" << max_height_ << " param:" << param_height
  600. << " need_stack:" << stack_sizes;
  601. if (stack_sizes > 0) {
  602. VectorRef need_stacks({stack_sizes});
  603. (void)inst_.insert(inst_.begin(), std::make_pair(Instruction::kPadStack, need_stacks));
  604. }
  605. }
  606. void CompileGraph::AddTailCall(const AnfNodePtr &fn, size_t size) {
  607. VectorRef args;
  608. args.emplace_back(Ref(fn));
  609. args.emplace_back(height_);
  610. args.emplace_back(static_cast<int>(size - 1));
  611. MS_LOG(DEBUG) << "Tail call:" << Ref(fn) << ", " << height_ << ", " << size - 1;
  612. AddInst(Instruction::kTailCall, args);
  613. }
  614. void CompileGraph::AddPartial(const CNodePtr &node) {
  615. auto inputs = node->inputs();
  616. VectorRef args;
  617. auto fn = inputs[1];
  618. if (!IsValueNode<FuncGraph>(fn)) {
  619. MS_LOG(EXCEPTION) << "The type of 1st input of node must be FuncGraph";
  620. }
  621. for (size_t i = 1; i < inputs.size(); i++) {
  622. args.emplace_back(Ref(inputs[i]));
  623. }
  624. AddInst(Instruction::kPartial, args);
  625. }
  626. void CompileGraph::AddMakeTuple(const CNodePtr &node) {
  627. auto inputs = node->inputs();
  628. VectorRef args;
  629. for (size_t i = 1; i < inputs.size(); i++) {
  630. args.emplace_back(Ref(inputs[i]));
  631. }
  632. AddInst(Instruction::kTuple, args);
  633. }
  634. void CompileGraph::AddSwitch(const CNodePtr &node) {
  635. auto inputs = node->inputs();
  636. if (inputs.size() < 4) {
  637. MS_LOG(EXCEPTION) << "Length of inputs of primitive " << prim::kPrimSwitch->name() << " is less than 4";
  638. }
  639. VectorRef args;
  640. args.emplace_back(Ref(inputs[1]));
  641. args.emplace_back(Ref(inputs[2]));
  642. args.emplace_back(Ref(inputs[3]));
  643. AddInst(Instruction::kSwitch, args);
  644. }
  645. void CompileGraph::AddSwitchLayer(const CNodePtr &node) {
  646. auto inputs = node->inputs();
  647. if (inputs.size() != 3) {
  648. MS_LOG(EXCEPTION) << "Switch layer must have index and branches.";
  649. }
  650. VectorRef args;
  651. args.emplace_back(Ref(inputs[1]));
  652. args.emplace_back(Ref(inputs[2]));
  653. AddInst(Instruction::kSwitchLayer, args);
  654. }
  655. void CompileGraph::AddReturn(const CNodePtr &node) {
  656. VectorRef args;
  657. args.emplace_back(Ref(node->input(1)));
  658. args.emplace_back(height_);
  659. AddInst(Instruction::kReturn, args);
  660. }
  661. void CompileGraph::AddPrimitive(const CNodePtr &node, const PrimitivePtr &prim) {
  662. auto inputs = node->inputs();
  663. VectorRef args;
  664. args.push_back(prim);
  665. for (size_t i = 1; i < inputs.size(); i++) {
  666. args.emplace_back(Ref(inputs[i]));
  667. }
  668. AddInst(Instruction::kPrim, args);
  669. }
  670. int CompileGraph::AddCall(const FuncGraphPtr &graph, const CNodePtr &node) {
  671. auto inputs = node->inputs();
  672. AnfNodePtr fn = inputs[0];
  673. (void)Ref(fn);
  674. size_t size = inputs.size();
  675. for (size_t i = size - 1; i > 0; i--) {
  676. AddInput(inputs[i]);
  677. }
  678. if (node == graph->output()) {
  679. AddTailCall(fn, size);
  680. return RET_BREAK;
  681. }
  682. MS_LOG(DEBUG) << "Call:" << Ref(fn) << ", " << height_ << ", " << size - 1;
  683. AddInst(Instruction::kCall, Ref(fn));
  684. Ret(static_cast<int>(size - 1));
  685. return RET_SUCCESS;
  686. }
  687. void CompileGraph::AddExternal(const LinConvertResult &result) {
  688. VectorRef args;
  689. args.push_back(result.run);
  690. args.push_back(result.simu_run);
  691. size_t size = result.inputs.size();
  692. for (size_t i = 0; i < size; i++) {
  693. args.emplace_back(Ref(result.inputs[i]));
  694. }
  695. AddInst(Instruction::kExternal, args);
  696. }
  697. void TraverseGraphMap(
  698. const FuncGraphManagerPtr &manager_ptr, FuncGraphTransaction *const tr, const FuncGraphSet &fgs,
  699. const std::function<std::shared_ptr<FuncGraph>(const PrimitivePtr, const AbstractFunctionPtr)> &get_prim_graph) {
  700. MS_EXCEPTION_IF_NULL(manager_ptr);
  701. MS_EXCEPTION_IF_NULL(tr);
  702. for (const auto &fg : fgs) {
  703. for (const auto &ct_any : fg->value_nodes()) {
  704. AnfNodePtr const_primitive_node = ct_any.first;
  705. if (const_primitive_node != nullptr && IsValueNode<Primitive>(const_primitive_node)) {
  706. auto users = manager_ptr->node_users()[const_primitive_node];
  707. for (auto &use : users) {
  708. CNodePtr node = use.first->cast<CNodePtr>();
  709. MS_EXCEPTION_IF_NULL(node);
  710. if (node->func_graph() != fg) {
  711. continue;
  712. }
  713. int key = use.second;
  714. if (key != 0) {
  715. MS_EXCEPTION_IF_NULL(node->input(0));
  716. bool key_is_const = node->input(0)->isa<ValueNode>();
  717. PrimitivePtr value = GetValueNode<PrimitivePtr>(node->input(0));
  718. if (value != nullptr) {
  719. bool is_prim_array_map = !(prim::kPrimArrayMap->name().compare(value->name()));
  720. bool is_prim_array_reduce = !(prim::kPrimArrayReduce->name().compare(value->name()));
  721. if (key == 1 && key_is_const && (is_prim_array_map || is_prim_array_reduce)) {
  722. continue;
  723. }
  724. }
  725. FuncGraphPtr g = get_prim_graph(GetValueNode<PrimitivePtr>(const_primitive_node),
  726. dyn_cast<AbstractFunction>(const_primitive_node->abstract()));
  727. tr->SetEdge(node, key, NewValueNode(g));
  728. }
  729. }
  730. }
  731. }
  732. }
  733. }
  734. FuncGraphPtr WrapPrimitives(const FuncGraphPtr &graph) {
  735. MS_EXCEPTION_IF_NULL(graph);
  736. FuncGraphManagerPtr manager_ptr = graph->manager();
  737. MS_EXCEPTION_IF_NULL(manager_ptr);
  738. MapPrimTypeFuncGraph prim_graphs;
  739. auto get_prim_graph = [&](const PrimitivePtr &prim, const AbstractFunctionPtr &type) {
  740. PrimTypePair prim_type = std::make_pair(prim, type);
  741. if (prim_graphs.end() == prim_graphs.find(prim_type)) {
  742. FuncGraphPtr g = std::make_shared<FuncGraph>();
  743. std::vector<AnfNodePtr> args;
  744. ValueNodePtr prim_ct = NewValueNode(prim);
  745. MS_EXCEPTION_IF_NULL(prim_ct);
  746. prim_ct->set_abstract(type);
  747. args.push_back(prim_ct);
  748. MS_EXCEPTION_IF_NULL(type);
  749. TypedPrimitiveAbstractClosurePtr tp = dyn_cast<abstract::TypedPrimitiveAbstractClosure>(type->GetUnique());
  750. MS_EXCEPTION_IF_NULL(tp);
  751. MS_EXCEPTION_IF_NULL(g);
  752. for (auto t : tp->args_spec_list()) {
  753. ParameterPtr p = g->add_parameter();
  754. p->set_abstract(t);
  755. args.push_back(p);
  756. }
  757. AnfNodePtr out = g->NewCNode(args);
  758. out->set_abstract(tp->output());
  759. g->set_output(out);
  760. prim_graphs[prim_type] = g;
  761. }
  762. return prim_graphs[prim_type];
  763. };
  764. FuncGraphTransaction tr = manager_ptr->Transact();
  765. auto &fgs = manager_ptr->func_graphs();
  766. TraverseGraphMap(manager_ptr, &tr, fgs, get_prim_graph);
  767. tr.Commit();
  768. return graph;
  769. }
  770. CompileGraphs::CompileGraphs(const BackendPtr &backend, const std::vector<PrimitivePtr> &cut_list) : backend_(backend) {
  771. MS_EXCEPTION_IF_NULL(backend);
  772. MS_LOG(DEBUG) << "Start vm: " << backend->name();
  773. transform_ = std::make_shared<CompileGraph>(backend, cut_list);
  774. Reset();
  775. }
  776. // Convert graphs to unlinked instructions.
  777. void CompileGraphs::Compile(const FuncGraphPtr &graph) {
  778. MS_LOG(DEBUG) << "Start";
  779. mapping_[graph] = static_cast<int>(insts_.size());
  780. if (transform_ != nullptr) {
  781. InstSet insts = transform_->Run(graph);
  782. if (!insts.empty()) {
  783. (void)insts_.insert(insts_.end(), insts.begin(), insts.end());
  784. }
  785. }
  786. MS_LOG(DEBUG) << "End";
  787. }
  788. // Link instructions from multiple function graphs together.
  789. FinalVMPtr CompileGraphs::Link(const FuncGraphPtr &graph) {
  790. MS_LOG(DEBUG) << "Start";
  791. for (std::size_t i = 0; i < insts_.size(); i++) {
  792. InstType inst = insts_[i];
  793. MS_LOG(DEBUG) << "Link point:" << inst_str[inst.first];
  794. if (Instruction::kGraph == inst.first) {
  795. if (inst.second.empty()) {
  796. MS_LOG(EXCEPTION) << "The second element of inst is empty";
  797. }
  798. FuncGraphPtr func_graph = utils::cast<ValuePtr>(inst.second[0])->cast<FuncGraphPtr>();
  799. MS_LOG(DEBUG) << "Link graph:" << func_graph->ToString();
  800. insts_[i] = std::make_pair(Instruction::kPush, VectorRef(std::vector<BaseRef>{mapping_[func_graph]}));
  801. }
  802. }
  803. FinalVMPtr rt = std::make_shared<FinalVM>(insts_, backend_);
  804. MS_LOG(DEBUG) << "End";
  805. return rt;
  806. }
  807. // Convert all graphs to unlinked instructions and link them.
  808. FinalVMPtr CompileGraphs::CompileAndLink(const FuncGraphPtr &graph) {
  809. MS_EXCEPTION_IF_NULL(graph);
  810. MS_LOG(DEBUG) << "Start";
  811. Reset();
  812. MS_LOG(DEBUG) << "Begin parameter:" << graph->parameters().size();
  813. FuncGraphPtr prim_graph = WrapPrimitives(graph);
  814. Compile(prim_graph);
  815. MS_EXCEPTION_IF_NULL(prim_graph);
  816. FuncGraphSet graphs = prim_graph->manager()->func_graphs();
  817. for (auto g : graphs) {
  818. if (g != graph && g != nullptr && !(g->has_attr(FUNC_GRAPH_ATTR_GRAPH_KERNEL))) {
  819. Compile(g);
  820. }
  821. }
  822. FinalVMPtr rt = Link(graph);
  823. Reset();
  824. MS_LOG(DEBUG) << "End";
  825. return rt;
  826. }
  827. bool CompileGraphs::ContainMixedTarget(const FuncGraphPtr &graph) {
  828. MS_EXCEPTION_IF_NULL(graph);
  829. auto graph_manager = graph->manager();
  830. MS_EXCEPTION_IF_NULL(graph_manager);
  831. FuncGraphSet graphs = graph_manager->func_graphs();
  832. for (auto &g : graphs) {
  833. auto nodes = TopoSort(g->get_return());
  834. if (ContainMultiTarget(nodes)) {
  835. return true;
  836. }
  837. }
  838. return false;
  839. }
  840. BackendPtr CreateBackend() {
  841. auto context_ptr = MsContext::GetInstance();
  842. MS_EXCEPTION_IF_NULL(context_ptr);
  843. std::string name = context_ptr->backend_policy();
  844. MS_LOG(INFO) << "CreateBackend is: " << name;
  845. if (backend_list.count(name) == 0) {
  846. MS_LOG(EXCEPTION) << "Backend is error: " << name;
  847. }
  848. if (name == kMsConvert) {
  849. std::string target = context_ptr->device_target();
  850. uint32_t device_id = context_ptr->device_id();
  851. auto backend = std::make_shared<MsBackend>(name, target, device_id);
  852. std::string device_target = MsContext::GetInstance()->device_target();
  853. if (device_target == kAscendDevice) {
  854. if (MsContext::GetInstance()->execution_mode() == kPynativeMode) {
  855. backend->set_is_multi_graph_sink(false);
  856. context_ptr->set_is_multi_graph_sink(false);
  857. } else {
  858. backend->set_is_multi_graph_sink(true);
  859. context_ptr->set_is_multi_graph_sink(true);
  860. }
  861. }
  862. return backend;
  863. }
  864. return std::make_shared<Backend>(name);
  865. }
  866. } // namespace compile
  867. } // namespace mindspore