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

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