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 30 kB

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