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
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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_parameter_obj_node(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. for (auto &elem : value_vec) {
  143. if (elem->isa<ValueTuple>() || elem->isa<ValueList>()) {
  144. const auto &vec = GetValue<std::vector<ValuePtr>>(elem);
  145. auto is_graph = IsAllFuncInValueSequence(vec);
  146. if (!is_graph) {
  147. return false;
  148. }
  149. } else if (!elem->isa<FuncGraph>() && !elem->isa<Primitive>()) {
  150. return false;
  151. }
  152. }
  153. return true;
  154. }
  155. AnfNodePtr TransformToMakeTupleNodes(const FuncGraphManagerPtr &manager, const FuncGraphPtr &func_graph,
  156. const std::vector<ValuePtr> &value_vec) {
  157. std::vector<AnfNodePtr> nodes;
  158. nodes.emplace_back(NewValueNode(prim::kPrimMakeTuple));
  159. for (auto &elem : value_vec) {
  160. AnfNodePtr node = nullptr;
  161. if (elem->isa<ValueTuple>() || elem->isa<ValueList>()) {
  162. const auto &vec = GetValue<std::vector<ValuePtr>>(elem);
  163. node = TransformToMakeTupleNodes(manager, func_graph, vec);
  164. } else if (elem->isa<FuncGraph>()) {
  165. FuncGraphPtr new_fg = elem->cast<FuncGraphPtr>();
  166. manager->AddFuncGraph(new_fg);
  167. node = NewValueNode(new_fg);
  168. } else if (elem->isa<Primitive>()) {
  169. node = NewValueNode(elem);
  170. } else {
  171. MS_LOG(EXCEPTION) << "TransformToMakeTupleNodes error, expect funcgraph, got " << elem->ToString();
  172. }
  173. nodes.emplace_back(node);
  174. }
  175. auto cnode = func_graph->NewCNode(nodes);
  176. return cnode;
  177. }
  178. // transform the ValueTuple or ValueList of graph/primitve node to make tuple of const graph/primitve node
  179. bool TransformVectorFuncValueNode(const FuncGraphManagerPtr &manager, const FuncGraphPtr &func_graph,
  180. const ValueNodePtr &value_node, AnfNodePtr *const transformed) {
  181. MS_EXCEPTION_IF_NULL(value_node);
  182. const auto &value_vec = GetValue<std::vector<ValuePtr>>(value_node->value());
  183. if (!IsAllFuncInValueSequence(value_vec)) {
  184. return false;
  185. }
  186. // (1) The celllist or ordered_cell will be parsed as valuetuple of const graph in it,
  187. // So if has graph in list, try to replace the node with make tuple of graph value node.
  188. // we do this because the graphmanger won't investigate the graph inside valuetuple,
  189. // change the vector of graph to be make_tuple of graph value node.
  190. // (2) the primitve valuetuple or valuelist may encounter to abstract error, make it all
  191. // independent nodes.
  192. auto node_tuple_graphs = TransformToMakeTupleNodes(manager, func_graph, value_vec);
  193. // replace the ret ptr to be make tuple of graph value node
  194. *transformed = node_tuple_graphs;
  195. return true;
  196. }
  197. // resolve the python obj, and if the resovled node is valuenode with graphs, add the graphs to manager
  198. AnfNodePtr ResolveObjectAndAddToManager(const FuncGraphManagerPtr &manager, const py::object &obj,
  199. const AnfNodePtr &node) {
  200. ScopeGuard scope_guard(node->scope());
  201. AnfNodePtr resolved_node = nullptr;
  202. TraceManager::DebugTrace(std::make_shared<TraceResolve>(node->debug_info()));
  203. bool success = ResolveObjectToNode(node->func_graph(), obj, &resolved_node);
  204. if (!success) {
  205. MS_LOG(EXCEPTION) << "Parse Resolve covert failed NodeInfo: " << trace::GetDebugInfo(node->debug_info());
  206. }
  207. if (IsValueNode<FuncGraph>(resolved_node)) {
  208. auto new_fg = GetValueNode<FuncGraphPtr>(resolved_node);
  209. manager->AddFuncGraph(new_fg);
  210. }
  211. // if the constant node is constant of vector of graph ,add graph to manager
  212. if (IsValueNode<ValueTuple>(resolved_node) || IsValueNode<ValueList>(resolved_node)) {
  213. (void)TransformVectorFuncValueNode(manager, node->func_graph(), resolved_node->cast<ValueNodePtr>(),
  214. &resolved_node);
  215. }
  216. TraceManager::EndTrace();
  217. return resolved_node;
  218. }
  219. } // namespace
  220. AnfNodePtr ResolveSymbol(const FuncGraphManagerPtr &manager, const NameSpacePtr &name_space, const SymbolPtr &symbol,
  221. const AnfNodePtr &node) {
  222. if (node->func_graph() == nullptr || manager == nullptr) {
  223. MS_LOG(EXCEPTION) << "Node " << node->DebugString() << " graph or manager is nullptr";
  224. }
  225. SymbolResolver symbol_resolver(name_space, symbol, node);
  226. if (!symbol_resolver.Resolve()) {
  227. MS_EXCEPTION(TypeError) << "Parse Resolve node failed NodeInfo: " << trace::GetDebugInfo(node->debug_info());
  228. }
  229. py::object obj = symbol_resolver.result();
  230. AnfNodePtr resolved_node = ResolveObjectAndAddToManager(manager, obj, node);
  231. return resolved_node;
  232. }
  233. AnfNodePtr ResolveCellwithAttr(const FuncGraphManagerPtr &manager, const NameSpacePtr &name_space,
  234. const SymbolPtr &symbol, const AnfNodePtr &node, const std::string &attr) {
  235. if (node->func_graph() == nullptr || manager == nullptr) {
  236. MS_LOG(EXCEPTION) << "Node " << node->DebugString() << " graph or manager is nullptr";
  237. }
  238. SymbolResolver symbol_resolver(name_space, symbol, node);
  239. if (!symbol_resolver.Resolve()) {
  240. MS_LOG(EXCEPTION) << "Parse Resolve node failed NodeInfo: " << trace::GetDebugInfo(node->debug_info());
  241. }
  242. py::object obj = symbol_resolver.result();
  243. if (!data_converter::IsCellInstance(obj)) {
  244. return nullptr;
  245. }
  246. py::object obj_attr = obj.attr(attr.c_str());
  247. AnfNodePtr resolved_node = ResolveObjectAndAddToManager(manager, obj_attr, node);
  248. return resolved_node;
  249. }
  250. namespace {
  251. opt::OptPassGroupMap GetOptResolvePasses(const opt::irpass::ResolveIRPassLib &irpass) {
  252. opt::OptPassGroupMap map({
  253. {"resolve_attr",
  254. {
  255. // for resolve primitive;
  256. irpass.resolver_resolve_attr_,
  257. }},
  258. {"resolve",
  259. {
  260. // for resolve and getattr primitive;
  261. irpass.resolver_resolve_,
  262. irpass.resolver_getattr_,
  263. }},
  264. });
  265. return map;
  266. }
  267. } // namespace
  268. bool ResolveFuncGraph(const FuncGraphPtr &func_graph, const pipeline::ResourceBasePtr &res, bool use_profile) {
  269. if (func_graph == nullptr || res == nullptr) {
  270. MS_LOG(ERROR) << "func_graph or resource is null";
  271. return false;
  272. }
  273. opt::irpass::ResolveIRPassLib irpass;
  274. opt::OptimizerPtr opt_resolve = opt::Optimizer::MakeOptimizer("opt_resolve", res, GetOptResolvePasses(irpass));
  275. (void)parse::python_adapter::set_python_scoped();
  276. MS_EXCEPTION_IF_NULL(opt_resolve);
  277. (void)opt_resolve->step(func_graph, use_profile);
  278. return true;
  279. }
  280. bool ResolveAll(const FuncGraphManagerPtr &manager) {
  281. if (manager == nullptr) {
  282. MS_LOG(ERROR) << "func graph manager is null";
  283. return false;
  284. }
  285. if (manager->roots().size() > 1) {
  286. MS_LOG(WARNING)
  287. << "After call ResolveAll, only one graph will be kept in GraphManager. ResolveAll can resolve graphs"
  288. "called from root graph, so it's not necessary to pass all graphs as roots. "
  289. "Please ensure your usage.";
  290. }
  291. // should not use pipeline::Resource as Resource::Clean will clean some
  292. // global variable such as ScopeManager, it will cause JExpandedGraphs::GetBprop
  293. // fail as valid scope has been cleaned.
  294. auto res = std::make_shared<pipeline::ResourceBase>();
  295. res->set_manager(manager);
  296. auto roots = manager->roots();
  297. for (auto &fg : roots) {
  298. bool ret = ResolveFuncGraph(fg, res, false);
  299. if (!ret) {
  300. MS_EXCEPTION_IF_NULL(fg);
  301. MS_LOG(ERROR) << "Resolve fg " << fg->ToString() << " failed";
  302. }
  303. }
  304. return true;
  305. }
  306. } // namespace parse
  307. } // namespace mindspore