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.

function_block.cc 17 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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 "pipeline/jit/parse/function_block.h"
  19. #include <string>
  20. #include <memory>
  21. #include "pipeline/jit/parse/resolve.h"
  22. #include "pipeline/jit/parse/parse.h"
  23. #include "frontend/operator/ops.h"
  24. #include "utils/info.h"
  25. #include "debug/trace.h"
  26. #include "pybind11/pybind11.h"
  27. namespace mindspore {
  28. namespace py = pybind11;
  29. namespace parse {
  30. FunctionBlock::FunctionBlock(const Parser &parser) : parser_(parser) {
  31. func_graph_ = std::make_shared<FuncGraph>();
  32. matured_ = false;
  33. }
  34. void FunctionBlock::AddPrevBlock(const FunctionBlockPtr &block) { prev_blocks_.push_back(block.get()); }
  35. static bool CanBeIsolateNode(const std::string &var_name, const AnfNodePtr &node) {
  36. auto cnode = dyn_cast<CNode>(node);
  37. if (cnode == nullptr || cnode->inputs().empty()) {
  38. // Not a valid cnode, can not be isolate node.
  39. return false;
  40. }
  41. auto prim = GetValueNode<PrimitivePtr>(cnode->inputs().at(0));
  42. if (prim == nullptr) {
  43. // Not a primitive cnode, it may have side effects or not,
  44. // we add it as an isolate node if its name is not '_' or empty.
  45. // this means that code like:
  46. // _ = func_call()
  47. // will be ignored even if func_call() has side effects.
  48. return !var_name.empty() && var_name != "_";
  49. }
  50. // For primitive cnode, only those with side effects can be isolate nodes.
  51. auto effect_info = GetPrimEffectInfo(prim);
  52. bool has_effects = (effect_info.memory || effect_info.io);
  53. return has_effects;
  54. }
  55. // write variable records the variable name to corresponding node
  56. void FunctionBlock::WriteVariable(const std::string &var_name, const AnfNodePtr &node) {
  57. MS_LOG(DEBUG) << func_graph_->ToString() << " write var " << var_name << " with node " << node->DebugString();
  58. auto [iter, is_new_name] = vars_.emplace(var_name, std::make_pair(node, false));
  59. if (!is_new_name) {
  60. // If a cnode variable with same name already existed but not used,
  61. // add it as an isolate node. for example:
  62. // a = print(x)
  63. // a = print(y)
  64. // when we write variable 'a = print(y)',
  65. // the cnode 'print(x)' should added as an isolate node.
  66. if (!iter->second.second && CanBeIsolateNode(var_name, iter->second.first)) {
  67. func_graph_->AddIsolateNode(iter->second.first);
  68. }
  69. iter->second = std::make_pair(node, false);
  70. }
  71. }
  72. // read variable from predecessors
  73. AnfNodePtr FunctionBlock::ReadVariable(const std::string &var) {
  74. // get var node if it is found
  75. auto found = vars_.find(var);
  76. if (found != vars_.end()) {
  77. auto &node = found->second.first;
  78. MS_EXCEPTION_IF_NULL(node);
  79. // Mark the variable as used.
  80. found->second.second = true;
  81. auto iter = resolve_to_removable_phis_.find(node);
  82. if (iter != resolve_to_removable_phis_.end()) {
  83. return iter->second;
  84. }
  85. return node;
  86. }
  87. // get var from predecessor block ,if can't get the make a resolve node to it
  88. if (matured_) {
  89. // If only one predecessor block, read the definition of var from it.
  90. if (prev_blocks_.size() == 1) {
  91. auto block = prev_blocks_[0];
  92. MS_EXCEPTION_IF_NULL(block);
  93. return block->ReadVariable(var);
  94. } else if (prev_blocks_.empty()) {
  95. // get namespace and make Resolve
  96. auto it = var_to_resolve_.find(var);
  97. if (it != var_to_resolve_.end()) {
  98. return it->second;
  99. }
  100. auto tmp_node = MakeResolveSymbol(var);
  101. var_to_resolve_[var] = tmp_node;
  102. return tmp_node;
  103. }
  104. }
  105. // If have more than one predecessor blocks then build a phi node.
  106. auto debug_info = std::make_shared<NodeDebugInfo>();
  107. debug_info->set_name(var);
  108. TraceGuard guard(std::make_shared<TracePhi>(debug_info));
  109. ParameterPtr phi_param = std::make_shared<Parameter>(func_graph());
  110. MS_LOG(DEBUG) << func_graph_->ToString() << " generate phi node " << phi_param->ToString() << " for " << var;
  111. func_graph()->add_parameter(phi_param);
  112. phi_nodes_[phi_param] = var;
  113. WriteVariable(var, phi_param);
  114. if (matured_) {
  115. SetPhiArgument(phi_param);
  116. }
  117. return phi_param;
  118. }
  119. // Resolve Ast operator node
  120. AnfNodePtr FunctionBlock::MakeResolveAstOp(const py::object &op) {
  121. auto ast = parser_.ast();
  122. MS_EXCEPTION_IF_NULL(ast);
  123. TraceGuard trace_guard(parser_.GetLocation(op));
  124. py::tuple namespace_var = ast->CallParserObjMethod(PYTHON_PARSE_GET_AST_NAMESPACE_SYMBOL, op);
  125. if (namespace_var.size() != 2) {
  126. MS_LOG(EXCEPTION) << "Resolve ast op failed, get namespace tuple size=" << namespace_var.size();
  127. }
  128. NameSpacePtr name_space = std::make_shared<NameSpace>(RESOLVE_NAMESPACE_NAME_AST, namespace_var[0]);
  129. SymbolPtr symbol = std::make_shared<Symbol>(namespace_var[1].cast<std::string>());
  130. return MakeResolve(name_space, symbol);
  131. }
  132. // Resolve class member, two possible: method, member variable
  133. AnfNodePtr FunctionBlock::MakeResolveClassMember(const std::string &attr) {
  134. py::object namespace_var =
  135. parser_.ast()->CallParseModFunction(PYTHON_MOD_GET_MEMBER_NAMESPACE_SYMBOL, parser_.ast()->obj());
  136. NameSpacePtr name_space = std::make_shared<NameSpace>(RESOLVE_NAMESPACE_NAME_CLASS_MEMBER, namespace_var);
  137. SymbolPtr symbol = std::make_shared<Symbol>(attr);
  138. return MakeResolve(name_space, symbol);
  139. }
  140. // Make a resolve node for symbol string
  141. AnfNodePtr FunctionBlock::MakeResolveSymbol(const std::string &value) {
  142. if (value.compare(0, strlen("self"), "self") == 0) {
  143. auto start = value.find_first_of('.') + 1;
  144. if (start >= value.size()) {
  145. MS_LOG(ERROR) << "Find invalid resolve symbol str: " << value;
  146. return nullptr;
  147. }
  148. auto bits_str = value.substr(start);
  149. return MakeResolveClassMember(bits_str);
  150. }
  151. py::tuple namespace_var = parser_.ast()->CallParserObjMethod(PYTHON_PARSE_GET_NAMESPACE_SYMBOL, value);
  152. NameSpacePtr name_space = std::make_shared<NameSpace>(RESOLVE_NAMESPACE_NAME_SYMBOL_STR, namespace_var[0]);
  153. SymbolPtr symbol = std::make_shared<Symbol>(namespace_var[1].cast<std::string>());
  154. return MakeResolve(name_space, symbol);
  155. }
  156. AnfNodePtr FunctionBlock::MakeResolveOperation(const std::string &value) {
  157. py::tuple namespace_var = parser_.ast()->CallParserObjMethod(PYTHON_PARSE_GET_OPERATION_NAMESPACE_SYMBOL, value);
  158. NameSpacePtr name_space = std::make_shared<NameSpace>(RESOLVE_NAMESPACE_NAME_COMMON_OPS, namespace_var[0]);
  159. SymbolPtr symbol = std::make_shared<Symbol>(namespace_var[1].cast<std::string>());
  160. return MakeResolve(name_space, symbol);
  161. }
  162. AnfNodePtr FunctionBlock::MakeResolve(const NameSpacePtr &name_space, const SymbolPtr &resolve_symbol) {
  163. MS_LOG(DEBUG) << "MakeResolve for " << ((std::string)py::str(name_space->obj())) << " , "
  164. << ((std::string)resolve_symbol->symbol());
  165. ValueNodePtr module_node = NewValueNode(name_space);
  166. ValueNodePtr symbol_node = NewValueNode(resolve_symbol);
  167. auto node = func_graph()->NewCNodeInOrder({NewValueNode(prim::kPrimResolve), module_node, symbol_node});
  168. return node;
  169. }
  170. // add input for the block's phi parameter
  171. void FunctionBlock::SetPhiArgument(const ParameterPtr &phi) {
  172. std::string var = phi_nodes_[phi];
  173. MS_LOG(DEBUG) << "graph " << func_graph_->ToString() << " set phi " << phi->ToString() << " for var " << var;
  174. auto removable = CollectRemovablePhi(phi);
  175. // If the phi node is not necessary, not need to add to jumps_ of the prev blocks.
  176. if (removable) {
  177. MS_LOG(DEBUG) << "remove the phi when call graph " << func_graph_->ToString() << " var " << var;
  178. return;
  179. }
  180. for (auto &pred : prev_blocks_) {
  181. MS_EXCEPTION_IF_NULL(pred);
  182. MS_LOG(DEBUG) << "graph " << func_graph_->ToString() << " pred_blocks_ " << pred->func_graph_->ToString();
  183. AnfNodePtr arg_node = pred->ReadVariable(var);
  184. CNodePtr jump = pred->jumps_[this];
  185. jump->add_input(arg_node);
  186. }
  187. }
  188. AnfNodePtr FunctionBlock::SearchReplaceNode(const std::string &var, const ParameterPtr &phi) {
  189. AnfNodePtr arg_node = nullptr;
  190. for (auto &prev : prev_blocks_) {
  191. MS_EXCEPTION_IF_NULL(prev);
  192. AnfNodePtr temp_node = prev->ReadVariable(var);
  193. MS_LOG(DEBUG) << "graph " << prev->func_graph_->ToString() << " phi " << phi->ToString() << " for var " << var
  194. << " is " << temp_node->DebugString();
  195. if (temp_node != phi) {
  196. if (arg_node == nullptr) {
  197. arg_node = temp_node;
  198. MS_LOG(DEBUG) << "graph " << prev->func_graph_->ToString() << " phi " << phi->ToString()
  199. << " may be replaced by node " << arg_node->DebugString();
  200. } else if (temp_node == arg_node) {
  201. MS_LOG(DEBUG) << "graph " << prev->func_graph_->ToString() << " phi " << phi->ToString() << " is same as node "
  202. << arg_node->DebugString();
  203. } else {
  204. MS_LOG(DEBUG) << "phi " << phi->ToString()
  205. << " cannot be removed as it assigns to different node. node1: " << arg_node->DebugString()
  206. << ", node2: " << temp_node->DebugString();
  207. return nullptr;
  208. }
  209. }
  210. }
  211. return arg_node;
  212. }
  213. // Check if there is removable unnecessary phi node in this graph.
  214. // as per the FIRM TR 3.2, a phi node can be remove if:
  215. // <Quote>
  216. // If all arguments of a φ-function are the same value s or the φfunction itself,
  217. // then we remove the φ-function and let all users directly uses. We call such a
  218. // φ-function obviously unnecessary.
  219. // When we removed a φ-function p, then we recursively try to apply this simplification
  220. // rule with all (former) users of p, because they may have become obviously unnecessary
  221. // due to the removal of p
  222. // <Quote>
  223. // phi node in graph will be removed after the whole function is parsed in a DFS visit
  224. // of that graph.The reason is :
  225. // 1. when this function is called, not all usage of this phi node had bound to the
  226. // graph of this function block, some may stay in vars_ in other blocks.
  227. // 2. it's costly to iterate the graph to replace the phi for each phi.
  228. // Args :
  229. // phi : This parameter node is functioning as a phi node.
  230. bool FunctionBlock::CollectRemovablePhi(const ParameterPtr &phi) {
  231. MS_EXCEPTION_IF_NULL(phi);
  232. std::string var = phi_nodes_[phi];
  233. MS_LOG(DEBUG) << "check phi " << phi->DebugString() << " for " << var;
  234. if (prev_blocks_.size() == 0) {
  235. MS_LOG(DEBUG) << "no phi " << phi->DebugString() << " for var " << var;
  236. return false;
  237. }
  238. AnfNodePtr arg_node = SearchReplaceNode(var, phi);
  239. if (arg_node != nullptr) {
  240. MS_LOG(DEBUG) << "graph " << func_graph_->ToString() << " phi " << phi->ToString() << " can be replaced with "
  241. << arg_node->DebugString();
  242. // replace var with new one. This equal to statement in TR "v0 is immediately replaced by v1."
  243. WriteVariable(var, arg_node);
  244. removable_phis_[phi] = arg_node;
  245. resolve_to_removable_phis_[arg_node] = phi;
  246. // The following equal to statement "The φ-function defining v1, which now reads φ(v2, v1), is optimized
  247. // recursively". check if phi1 is assigned with this phi before, then phi1 can be replaced with arg_node.
  248. for (auto &prev : prev_blocks_) {
  249. MS_EXCEPTION_IF_NULL(prev);
  250. if (!prev->matured_) {
  251. continue;
  252. }
  253. for (auto &phi_iter : prev->removable_phis_) {
  254. MS_EXCEPTION_IF_NULL(phi_iter.second);
  255. if (phi_iter.second->isa<Parameter>()) {
  256. const auto &param = phi_iter.second->cast<ParameterPtr>();
  257. if (param == phi) {
  258. MS_LOG(DEBUG) << "graph " << prev->func_graph_->ToString() << " var " << phi_iter.first->DebugString()
  259. << " can be replaced from " << param->DebugString() << " with " << arg_node->DebugString()
  260. << " in graph " << arg_node->func_graph()->ToString();
  261. prev->removable_phis_[phi_iter.first] = arg_node;
  262. }
  263. }
  264. }
  265. }
  266. return true;
  267. }
  268. return false;
  269. }
  270. // A block should be marked matured if its predecessor blocks have been processed
  271. void FunctionBlock::Mature() {
  272. const auto &graphParamVec = func_graph_->parameters();
  273. for (auto &paramItr : graphParamVec) {
  274. MS_EXCEPTION_IF_NULL(paramItr);
  275. ParameterPtr param = paramItr->cast<ParameterPtr>();
  276. if (phi_nodes_.find(param) != phi_nodes_.cend()) {
  277. SetPhiArgument(param);
  278. }
  279. }
  280. matured_ = true;
  281. }
  282. // Force the conditIon node to bool using bool operation
  283. CNodePtr FunctionBlock::ForceToBoolNode(const AnfNodePtr &cond) {
  284. TraceGuard trace_guard(std::make_shared<TraceForceBool>(cond->debug_info()));
  285. CNodePtr op_apply_node = func_graph()->NewCNodeInOrder({MakeResolveOperation(NAMED_PRIMITIVE_BOOL), cond});
  286. return op_apply_node;
  287. }
  288. CNodePtr FunctionBlock::ForceToWhileCond(const AnfNodePtr &cond) {
  289. TraceGuard trace_guard(std::make_shared<TraceForceWhileCond>(cond->debug_info()));
  290. CNodePtr op_apply_node = func_graph()->NewCNodeInOrder({MakeResolveOperation("while_cond"), cond});
  291. return op_apply_node;
  292. }
  293. // Perform a jump from this block to target block
  294. void FunctionBlock::Jump(const FunctionBlockPtr &target_block, AnfNodePtr node) {
  295. if (func_graph()->get_return() != nullptr) {
  296. MS_LOG(EXCEPTION) << "Failure: have return node! NodeInfo: "
  297. << trace::GetDebugInfo(func_graph()->get_return()->debug_info());
  298. }
  299. std::vector<AnfNodePtr> input_nodes;
  300. input_nodes.emplace_back(NewValueNode(target_block->func_graph()));
  301. if (node != nullptr) {
  302. input_nodes.emplace_back(node);
  303. }
  304. CNodePtr jump = func_graph()->NewCNodeInOrder(input_nodes);
  305. jumps_[target_block.get()] = jump;
  306. target_block->AddPrevBlock(shared_from_this());
  307. func_graph()->set_output(jump);
  308. }
  309. // Perform a conditional jump using switch operation.
  310. // The first CNode select graph with condition, and than execute this graph
  311. void FunctionBlock::ConditionalJump(AnfNodePtr condNode, const FunctionBlockPtr &true_block,
  312. const FunctionBlockPtr &false_block, bool unroll_loop) {
  313. if (func_graph()->get_return() != nullptr) {
  314. MS_LOG(EXCEPTION) << "Failure: have return node! NodeInfo: "
  315. << trace::GetDebugInfo(func_graph()->get_return()->debug_info());
  316. }
  317. CNodePtr switch_app =
  318. func_graph()->NewCNodeInOrder({NewValueNode(prim::kPrimSwitch), condNode, NewValueNode(true_block->func_graph()),
  319. NewValueNode(false_block->func_graph())});
  320. CNodePtr switch_app_new = func_graph()->NewCNodeInOrder({switch_app});
  321. func_graph()->set_output(switch_app_new);
  322. }
  323. // Create cnode for the assign statement like 'self.target = source'.
  324. // convert it to 'P.Assign(self.target, source)' and then add the cnode as isolate node.
  325. void FunctionBlock::SetStateAssign(const AnfNodePtr &target, const AnfNodePtr &source) {
  326. const std::string primitive_name("assign");
  327. const std::string module_name("mindspore.ops.functional");
  328. ValueNodePtr assign_op = NewValueNode(prim::GetPythonOps(primitive_name, module_name, true));
  329. auto assign = func_graph_->NewCNodeInOrder({assign_op, target, source});
  330. func_graph_->AddIsolateNode(assign);
  331. }
  332. void FunctionBlock::FindIsolateVariables() {
  333. //
  334. // Search isolate nodes from variables, for example,
  335. // variable 'a' is an isolate node in below code:
  336. //
  337. // def construct(self, x, y):
  338. // a = print(x) # isolate node
  339. // return x + y
  340. //
  341. std::set<AnfNodePtr> used;
  342. // Find used variables.
  343. for (const auto &var : vars_) {
  344. auto &node = var.second.first;
  345. if (node == nullptr) {
  346. continue;
  347. }
  348. bool is_used = var.second.second;
  349. if (is_used) {
  350. used.emplace(node);
  351. }
  352. }
  353. // Add isolate nodes which is unused var but not found in used set.
  354. for (const auto &var : vars_) {
  355. auto &node = var.second.first;
  356. bool is_used = var.second.second;
  357. if (node == nullptr || is_used) {
  358. continue;
  359. }
  360. auto &var_name = var.first;
  361. if (used.find(node) == used.end() && CanBeIsolateNode(var_name, node)) {
  362. func_graph_->AddIsolateNode(node);
  363. }
  364. }
  365. }
  366. } // namespace parse
  367. } // namespace mindspore