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.

resolve.cc 13 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. /**
  2. * Copyright 2019 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "pipeline/jit/parse/resolve.h"
  17. #include <string>
  18. #include <memory>
  19. #include <vector>
  20. #include "ir/param_info.h"
  21. #include "pipeline/jit/parse/data_converter.h"
  22. #include "pipeline/jit/parse/parse.h"
  23. #include "pipeline/jit/parse/python_adapter.h"
  24. #include "utils/any.h"
  25. #include "frontend/operator/ops.h"
  26. #include "frontend/optimizer/opt.h"
  27. #include "frontend/optimizer/irpass.h"
  28. namespace mindspore {
  29. namespace parse {
  30. abstract::AbstractBasePtr ClassObject::ToAbstract() {
  31. ClassPtr cls_ptr = ParseDataClass(obj());
  32. auto abs_scalar = std::make_shared<abstract::AbstractScalar>();
  33. abs_scalar->set_type(std::make_shared<TypeType>());
  34. abs_scalar->set_value(cls_ptr);
  35. AbstractBasePtrList args_spec_list = {abs_scalar};
  36. auto func_ptr = std::make_shared<abstract::PrimitiveAbstractClosure>(prim::kPrimMakeRecord);
  37. return std::make_shared<abstract::PartialAbstractClosure>(func_ptr, args_spec_list);
  38. }
  39. abstract::AbstractBasePtr ClassType::ToAbstract() {
  40. auto abs_scalar =
  41. std::make_shared<abstract::AbstractScalar>(shared_from_base<ClassType>(), std::make_shared<TypeType>());
  42. AbstractBasePtrList args_spec_list = {abs_scalar};
  43. auto func_ptr = std::make_shared<abstract::PrimitiveAbstractClosure>(prim::kPrimCreateInstance);
  44. auto ret_val = std::make_shared<abstract::PartialAbstractClosure>(func_ptr, args_spec_list);
  45. ret_val->set_value_desc(ToString());
  46. return ret_val;
  47. }
  48. // call python PYTHON_MOD_RESOLVE_FUNCTION interface to resolve the symbol in corresponding namespace
  49. bool SymbolResolver::Resolve() {
  50. py::module mod = python_adapter::GetPyModule(PYTHON_MOD_PARSE_MODULE);
  51. py::object obj = namespace_->obj();
  52. std::string symbol = symbol_->symbol();
  53. if (py::isinstance<py::none>(obj)) {
  54. MS_LOG(ERROR) << "Unresolved symbol: " << symbol;
  55. return false;
  56. }
  57. result_ = python_adapter::CallPyModFn(mod, PYTHON_MOD_RESOLVE_FUNCTION, obj, common::SafeCStr(symbol));
  58. return true;
  59. }
  60. namespace {
  61. // if any mixed precision flag add a cast node after the parameter node.
  62. // argument obj should be python Parameter object
  63. // it will be converted to Parameter node here
  64. AnfNodePtr ResolveParameterObj(const FuncGraphPtr &func_graph, const py::object &obj) {
  65. MS_EXCEPTION_IF_NULL(func_graph);
  66. // parameter object should not be none
  67. if (py::isinstance<py::none>(obj)) {
  68. MS_LOG(EXCEPTION) << "Resolve class Parameter error because obj is null.";
  69. }
  70. if (!py::hasattr(obj, "name")) {
  71. MS_LOG(EXCEPTION) << "Resolve class Parameter error: cannot find name attr for obj";
  72. }
  73. // get the parameter name from parameter object
  74. auto name_attr = python_adapter::GetPyObjAttr(obj, "name");
  75. if (py::isinstance<py::none>(name_attr)) {
  76. MS_LOG(EXCEPTION) << "Parameter object should have name attribute";
  77. }
  78. auto param_name = py::cast<std::string>(name_attr);
  79. auto top_graph = Parser::GetTopFuncGraph();
  80. // if the parameter node has been created , return it
  81. AnfNodePtr para_node = nullptr;
  82. for (auto const &param : top_graph->parameters()) {
  83. auto param_node = dyn_cast<Parameter>(param);
  84. if (param_node != nullptr && param_node->name() == param_name) {
  85. para_node = param;
  86. break;
  87. }
  88. }
  89. if (para_node == nullptr) {
  90. auto node = top_graph->AddWeightParameter(param_name);
  91. auto value = py::cast<tensor::MetaTensorPtr>(obj);
  92. node->set_default_param(value);
  93. // set_abstract for parameter
  94. auto abs = value->ToAbstract();
  95. node->set_abstract(abs);
  96. para_node = node;
  97. }
  98. func_graph->add_used_global_parameters(para_node);
  99. return para_node;
  100. }
  101. bool ResolveObjectToNode(const FuncGraphPtr &func_graph, const py::object &obj, AnfNodePtr *const node) {
  102. AnfNodePtr output = nullptr;
  103. if (py::hasattr(obj, "__parameter__") && py::isinstance<tensor::MetaTensor>(obj)) {
  104. auto param = ResolveParameterObj(func_graph, obj);
  105. if (param == nullptr) {
  106. MS_LOG(ERROR) << "Resolve parameter object failed, got nullptr";
  107. return false;
  108. }
  109. MS_LOG(DEBUG) << "Add param graph:" << func_graph->ToString() << ", " << param->DebugString();
  110. output = param;
  111. } else if (py::hasattr(obj, "__parameter_tuple__")) {
  112. auto tuple = obj.cast<py::tuple>();
  113. std::vector<AnfNodePtr> args;
  114. args.push_back(NewValueNode(prim::kPrimMakeTuple));
  115. for (size_t it = 0; it < tuple.size(); ++it) {
  116. AnfNodePtr out = nullptr;
  117. bool success = ResolveObjectToNode(func_graph, tuple[it], &out);
  118. if (!success) {
  119. MS_LOG(ERROR) << "Resolve object to node failed";
  120. return false;
  121. }
  122. args.push_back(out);
  123. }
  124. output = NewCNode(args, func_graph);
  125. } else {
  126. ValuePtr convert_result = nullptr;
  127. bool converted = ConvertData(obj, &convert_result, parse::python_adapter::UseSignatureInResolve());
  128. if (!converted) {
  129. MS_LOG(ERROR) << "Convert data failed";
  130. return false;
  131. }
  132. MS_EXCEPTION_IF_NULL(convert_result);
  133. output = NewValueNode(convert_result);
  134. if (convert_result->isa<tensor::Tensor>()) {
  135. output = GetMixedPrecisionCastHelp(func_graph, output);
  136. }
  137. }
  138. *node = output;
  139. return true;
  140. }
  141. bool IsAllFuncInValueSequence(const std::vector<ValuePtr> &value_vec) {
  142. if (value_vec.empty()) {
  143. return false;
  144. }
  145. for (auto &elem : value_vec) {
  146. if (elem->isa<ValueTuple>() || elem->isa<ValueList>()) {
  147. const auto &vec = GetValue<ValuePtrList>(elem);
  148. auto is_graph = IsAllFuncInValueSequence(vec);
  149. if (!is_graph) {
  150. return false;
  151. }
  152. } else if (!elem->isa<FuncGraph>() && !elem->isa<Primitive>()) {
  153. return false;
  154. }
  155. }
  156. return true;
  157. }
  158. AnfNodePtr TransformToMakeTupleNodes(const FuncGraphManagerPtr &manager, const FuncGraphPtr &func_graph,
  159. const std::vector<ValuePtr> &value_vec) {
  160. std::vector<AnfNodePtr> nodes;
  161. nodes.emplace_back(NewValueNode(prim::kPrimMakeTuple));
  162. for (auto &elem : value_vec) {
  163. AnfNodePtr node = nullptr;
  164. if (elem->isa<ValueTuple>() || elem->isa<ValueList>()) {
  165. const auto &vec = GetValue<std::vector<ValuePtr>>(elem);
  166. node = TransformToMakeTupleNodes(manager, func_graph, vec);
  167. } else if (elem->isa<FuncGraph>()) {
  168. FuncGraphPtr new_fg = elem->cast<FuncGraphPtr>();
  169. manager->AddFuncGraph(new_fg);
  170. node = NewValueNode(new_fg);
  171. } else if (elem->isa<Primitive>()) {
  172. node = NewValueNode(elem);
  173. } else {
  174. MS_LOG(EXCEPTION) << "TransformToMakeTupleNodes error, expect funcgraph, got " << elem->ToString();
  175. }
  176. nodes.emplace_back(node);
  177. }
  178. auto cnode = func_graph->NewCNode(nodes);
  179. return cnode;
  180. }
  181. // transform the ValueTuple or ValueList of graph/primitive node to make tuple of const graph/primitive node
  182. bool TransformVectorFuncValueNode(const FuncGraphManagerPtr &manager, const FuncGraphPtr &func_graph,
  183. const ValueNodePtr &value_node, AnfNodePtr *const transformed) {
  184. MS_EXCEPTION_IF_NULL(value_node);
  185. const auto &value_vec = GetValue<ValuePtrList>(value_node->value());
  186. if (!IsAllFuncInValueSequence(value_vec)) {
  187. return false;
  188. }
  189. // (1) The celllist or ordered_cell will be parsed as valuetuple of const graph in it,
  190. // So if has graph in list, try to replace the node with make tuple of graph value node.
  191. // we do this because the graph manager won't investigate the graph inside valuetuple,
  192. // change the vector of graph to be make_tuple of graph value node.
  193. // (2) the primitive valuetuple or valuelist may encounter to abstract error, make it all
  194. // independent nodes.
  195. auto node_tuple_graphs = TransformToMakeTupleNodes(manager, func_graph, value_vec);
  196. // replace the ret ptr to be make tuple of graph value node
  197. *transformed = node_tuple_graphs;
  198. return true;
  199. }
  200. // resolve the python obj, and if the resovled node is valuenode with graphs, add the graphs to manager
  201. AnfNodePtr ResolveObjectAndAddToManager(const FuncGraphManagerPtr &manager, const py::object &obj,
  202. const AnfNodePtr &node) {
  203. ScopeGuard scope_guard(node->scope());
  204. AnfNodePtr resolved_node = nullptr;
  205. bool success = ResolveObjectToNode(node->func_graph(), obj, &resolved_node);
  206. if (!success) {
  207. MS_LOG(EXCEPTION) << "Parse Resolve covert failed NodeInfo.";
  208. }
  209. if (IsValueNode<FuncGraph>(resolved_node)) {
  210. auto new_fg = GetValueNode<FuncGraphPtr>(resolved_node);
  211. manager->AddFuncGraph(new_fg);
  212. }
  213. // if the constant node is constant of vector of graph ,add graph to manager
  214. if (IsValueNode<ValueTuple>(resolved_node) || IsValueNode<ValueList>(resolved_node)) {
  215. (void)TransformVectorFuncValueNode(manager, node->func_graph(), resolved_node->cast<ValueNodePtr>(),
  216. &resolved_node);
  217. }
  218. return resolved_node;
  219. }
  220. } // namespace
  221. AnfNodePtr ResolveSymbol(const FuncGraphManagerPtr &manager, const NameSpacePtr &name_space, const SymbolPtr &symbol,
  222. const AnfNodePtr &node) {
  223. MS_EXCEPTION_IF_NULL(node);
  224. TraceGuard trace_guard(std::make_shared<TraceResolve>(node->debug_info()));
  225. if (node->func_graph() == nullptr || manager == nullptr) {
  226. MS_LOG(EXCEPTION) << "Node " << node->DebugString() << " graph or manager is nullptr";
  227. }
  228. SymbolResolver symbol_resolver(name_space, symbol, node);
  229. if (!symbol_resolver.Resolve()) {
  230. MS_EXCEPTION(TypeError) << "Parse Resolve node failed NodeInfo.";
  231. }
  232. py::object obj = symbol_resolver.result();
  233. AnfNodePtr resolved_node = ResolveObjectAndAddToManager(manager, obj, node);
  234. TraceManager::ClearParseOrResolveDebugInfo();
  235. return resolved_node;
  236. }
  237. AnfNodePtr ResolveCellwithAttr(const FuncGraphManagerPtr &manager, const NameSpacePtr &name_space,
  238. const SymbolPtr &symbol, const AnfNodePtr &node, const std::string &attr) {
  239. MS_EXCEPTION_IF_NULL(node);
  240. TraceGuard trace_guard(std::make_shared<TraceResolve>(node->debug_info()));
  241. if (node->func_graph() == nullptr || manager == nullptr) {
  242. MS_LOG(EXCEPTION) << "Node " << node->DebugString() << " graph or manager is nullptr";
  243. }
  244. SymbolResolver symbol_resolver(name_space, symbol, node);
  245. if (!symbol_resolver.Resolve()) {
  246. MS_LOG(EXCEPTION) << "Parse Resolve node failed NodeInfo.";
  247. }
  248. py::object obj = symbol_resolver.result();
  249. if (!data_converter::IsCellInstance(obj)) {
  250. return nullptr;
  251. }
  252. const std::string fn = PYTHON_MOD_GET_MEMBER_NAMESPACE_SYMBOL;
  253. const std::string module = "mindspore._extends.parse.parser";
  254. py::object namespace_obj = parse::python_adapter::GetPyFn(module, fn)(obj);
  255. auto new_namespace = std::make_shared<NameSpace>(RESOLVE_NAMESPACE_NAME_CLASS_MEMBER, namespace_obj);
  256. auto new_symbol = std::make_shared<Symbol>(attr);
  257. AnfNodePtrList inputs = {NewValueNode(prim::kPrimResolve), NewValueNode(new_namespace), NewValueNode(new_symbol)};
  258. AnfNodePtr resolved_node = node->func_graph()->NewCNode(inputs);
  259. TraceManager::ClearParseOrResolveDebugInfo();
  260. return resolved_node;
  261. }
  262. namespace {
  263. opt::OptPassGroupMap GetOptResolvePasses(const opt::irpass::ResolveIRPassLib &irpass) {
  264. opt::OptPassGroupMap map({
  265. {"resolve",
  266. {
  267. // for resolve and getattr primitive;
  268. irpass.resolver_resolve_and_getattr_,
  269. }},
  270. });
  271. return map;
  272. }
  273. } // namespace
  274. bool ResolveFuncGraph(const FuncGraphPtr &func_graph, const pipeline::ResourceBasePtr &res, bool use_profile) {
  275. if (func_graph == nullptr || res == nullptr) {
  276. MS_LOG(ERROR) << "func_graph or resource is null";
  277. return false;
  278. }
  279. opt::irpass::ResolveIRPassLib irpass;
  280. opt::OptimizerPtr opt_resolve = opt::Optimizer::MakeOptimizer("opt_resolve", res, GetOptResolvePasses(irpass));
  281. (void)parse::python_adapter::set_python_scoped();
  282. MS_EXCEPTION_IF_NULL(opt_resolve);
  283. (void)opt_resolve->step(func_graph, use_profile);
  284. return true;
  285. }
  286. bool ResolveAll(const FuncGraphManagerPtr &manager) {
  287. if (manager == nullptr) {
  288. MS_LOG(ERROR) << "func graph manager is null";
  289. return false;
  290. }
  291. if (manager->roots().size() > 1) {
  292. MS_LOG(WARNING)
  293. << "After call ResolveAll, only one graph will be kept in GraphManager. ResolveAll can resolve graphs"
  294. "called from root graph, so it's not necessary to pass all graphs as roots. "
  295. "Please ensure your usage.";
  296. }
  297. // should not use pipeline::Resource as Resource::Clean will clean some
  298. // global variable such as ScopeManager, it will cause JExpandedGraphs::GetBprop
  299. // fail as valid scope has been cleaned.
  300. auto res = std::make_shared<pipeline::ResourceBase>();
  301. res->set_manager(manager);
  302. auto roots = manager->roots();
  303. for (auto &fg : roots) {
  304. bool ret = ResolveFuncGraph(fg, res, false);
  305. if (!ret) {
  306. MS_EXCEPTION_IF_NULL(fg);
  307. MS_LOG(ERROR) << "Resolve fg " << fg->ToString() << " failed";
  308. }
  309. }
  310. return true;
  311. }
  312. } // namespace parse
  313. } // namespace mindspore