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.

primitive_py.cc 17 kB

5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. /**
  2. * Copyright 2019-2020 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 "pybind_api/ir/primitive_py.h"
  17. #include <mutex>
  18. #include <map>
  19. #include "ir/signature.h"
  20. #include "pipeline/jit/parse/data_converter.h"
  21. #include "pipeline/jit/parse/python_adapter.h"
  22. #include "pybind11/pytypes.h"
  23. #include "pybind_api/api_register.h"
  24. #include "pybind_api/export_flags.h"
  25. #include "pybind_api/ir/base_ref_py.h"
  26. #include "utils/convert_utils_base.h"
  27. #include "utils/convert_utils_py.h"
  28. #include "utils/ms_context.h"
  29. #include "utils/primitive_utils.h"
  30. #include "utils/check_convert_utils.h"
  31. #include "pipeline/jit/resource.h"
  32. #include "pipeline/pynative/pynative_execute.h"
  33. namespace mindspore {
  34. namespace {
  35. constexpr auto kBpropAttrName = "bprop";
  36. constexpr auto kCellHookAttrName = "cell_hook";
  37. constexpr auto kCellIDAttrName = "cell_id";
  38. std::map<std::string, std::string> kOpAttrNameReplaceMap = {
  39. {"data_format", "format"},
  40. };
  41. void SyncData(const py::object &arg) {
  42. if (py::isinstance<py::tuple>(arg)) {
  43. py::tuple arg_list = py::cast<py::tuple>(arg);
  44. for (size_t i = 0; i < arg_list.size(); i++) {
  45. SyncData(arg_list[i]);
  46. }
  47. }
  48. if (py::isinstance<tensor::Tensor>(arg)) {
  49. auto tensor = py::cast<tensor::TensorPtr>(arg);
  50. (void)tensor->data_sync();
  51. }
  52. }
  53. } // namespace
  54. std::map<std::string, py::object> PrimitivePy::hook_grad_;
  55. PrimitivePy::PrimitivePy(const py::str &name, const py::object &python_obj)
  56. : Primitive(name, false), python_obj_(python_obj), signatures_() {
  57. auto &mem_cleaner = pipeline::Resource::mem_cleaner();
  58. mem_cleaner.RecordPrimitivePy(this);
  59. MS_LOG(DEBUG) << "New primitive:" << name;
  60. if (mem_cleaner.IsInPynativeConstructProcess() && !mem_cleaner.IsInPynativeEndGraphProcess()) {
  61. mem_cleaner.RecordPynativeShortLifePrimitivePy(this);
  62. }
  63. }
  64. PrimitivePy::~PrimitivePy() {
  65. // Erase primitive here to set released flag false, to avoid calling released pointer when clear primitives in
  66. // resource.
  67. pipeline::Resource::mem_cleaner().ReleasePrimitivePyObj(this);
  68. MS_LOG(DEBUG) << "Release:" << ToString();
  69. }
  70. void PrimitivePy::SetPyObj(const py::object &obj) { python_obj_ = obj; }
  71. void PrimitivePy::set_signatures(const std::vector<Signature> &signatures) {
  72. signatures_ = signatures;
  73. set_has_signature(true);
  74. }
  75. py::function PrimitivePy::GetBpropFunction() {
  76. static const char *const get_bprop_func_name = "get_bprop";
  77. if (py::hasattr(python_obj_, get_bprop_func_name)) {
  78. py::function fn = python_obj_.attr(get_bprop_func_name)().cast<py::function>();
  79. return fn;
  80. } else {
  81. auto fn = GetBpropFunctionByObj(python_obj_);
  82. return fn;
  83. }
  84. }
  85. py::tuple check_bprop_out(const py::object &grads_obj, const py::tuple &py_args) {
  86. py::tuple grads;
  87. if (!py::isinstance<py::tuple>(grads_obj)) {
  88. grads = py::make_tuple(grads_obj);
  89. } else {
  90. grads = py::cast<py::tuple>(grads_obj);
  91. }
  92. if (grads.size() != py_args.size() - 2) {
  93. MS_EXCEPTION(ValueError) << "For user define net bprop, the gradients number: " << grads.size()
  94. << " is not equal to the args number: " << py_args.size() - 2 << ".";
  95. }
  96. if (MsContext::GetInstance()->get_param<bool>(MS_CTX_CHECK_BPROP_FLAG)) {
  97. for (size_t i = 0; i < grads.size(); i++) {
  98. if (py::isinstance<tensor::Tensor>(py_args[i])) {
  99. if (!py::isinstance<tensor::Tensor>(grads[i])) {
  100. MS_EXCEPTION(ValueError) << "When user defines the net bprop,, the gradient of the " << i
  101. << "th arg should be Tensor, but got "
  102. << py::cast<std::string>(grads[i].attr("__class__").attr("__name__"))
  103. << ", and the value is " << py::cast<py::str>(grads[i]) << ".";
  104. }
  105. py::object arg_dtype = py_args[i].attr("dtype");
  106. py::object grad_dtype = grads[i].attr("dtype");
  107. py::tuple arg_shape = py_args[i].attr("shape");
  108. py::tuple grad_shape = grads[i].attr("shape");
  109. if (!grad_dtype.equal(arg_dtype)) {
  110. MS_EXCEPTION(TypeError) << "When user defines the net bprop, the gradient of the " << i
  111. << "th arg should have the same dtype as the " << i << "th arg, but the " << i
  112. << "th arg dtype is: " << py::cast<py::str>(arg_dtype)
  113. << ", the gradient dtype is: " << py::cast<py::str>(grad_dtype) << ".";
  114. }
  115. if (!grad_shape.equal(arg_shape)) {
  116. MS_EXCEPTION(ValueError) << "When user defines the net bprop, the gradient of the " << i
  117. << "th arg should have the same shape as the " << i << "th arg, but the " << i
  118. << "th arg shape is: " << py::cast<py::str>(arg_shape)
  119. << ", the gradient shape is: " << py::cast<py::str>(grad_shape) << ".";
  120. }
  121. }
  122. }
  123. }
  124. return grads;
  125. }
  126. void PrimitivePy::ConvertCTensorToPyTensor(const py::tuple &input_args, py::tuple *convert_args) const {
  127. MS_EXCEPTION_IF_NULL(convert_args);
  128. if (input_args.size() != (*convert_args).size()) {
  129. MS_LOG(EXCEPTION) << "The size of input_args: " << input_args.size()
  130. << " should be equal to the size of convert_args: " << (*convert_args).size();
  131. }
  132. for (size_t i = 0; i < input_args.size(); ++i) {
  133. (*convert_args)[i] = py::isinstance<tensor::Tensor>(input_args[i])
  134. ? parse::python_adapter::CallPyFn(parse::PYTHON_MOD_PARSE_MODULE,
  135. parse::PYTHON_MOD_CONVERT_TO_MS_TENSOR, input_args[i])
  136. : input_args[i];
  137. }
  138. }
  139. void PrimitivePy::CheckHookConsistency(const py::object &grad_out, const py::object &expected_grad_out) const {
  140. if (py::isinstance<py::tuple>(expected_grad_out)) {
  141. if (!py::isinstance<py::tuple>(grad_out)) {
  142. hook_grad_.clear();
  143. MS_EXCEPTION(TypeError) << "The output gradient should be a tuple!";
  144. }
  145. auto actual_out_tuple = py::cast<py::tuple>(grad_out);
  146. auto expected_out_tuple = py::cast<py::tuple>(expected_grad_out);
  147. if (actual_out_tuple.size() != expected_out_tuple.size()) {
  148. hook_grad_.clear();
  149. MS_EXCEPTION(ValueError) << "The tuple size of output gradient should be " << expected_out_tuple.size()
  150. << ", but it is " << actual_out_tuple.size();
  151. }
  152. for (size_t i = 0; i < expected_out_tuple.size(); ++i) {
  153. CheckHookConsistency(actual_out_tuple[i], expected_out_tuple[i]);
  154. }
  155. }
  156. if (py::isinstance<tensor::Tensor>(expected_grad_out)) {
  157. if (!py::isinstance<tensor::Tensor>(grad_out)) {
  158. hook_grad_.clear();
  159. MS_EXCEPTION(TypeError) << "The output gradient should be a tensor!";
  160. }
  161. auto actual_out_tensor = py::cast<tensor::TensorPtr>(grad_out);
  162. auto expected_out_tensor = py::cast<tensor::TensorPtr>(expected_grad_out);
  163. MS_EXCEPTION_IF_NULL(actual_out_tensor);
  164. MS_EXCEPTION_IF_NULL(expected_out_tensor);
  165. if (actual_out_tensor->GetShapeAndDataTypeInfo() != expected_out_tensor->GetShapeAndDataTypeInfo()) {
  166. hook_grad_.clear();
  167. MS_EXCEPTION(ValueError) << "The output gradient is not consistent with the expected, it should be "
  168. << expected_out_tensor->GetShapeAndDataTypeInfo() << ", but it is "
  169. << actual_out_tensor->GetShapeAndDataTypeInfo();
  170. }
  171. }
  172. }
  173. BaseRef PrimitivePy::RunHookFunction(const VectorRef &args) const {
  174. py::tuple py_args = ConvertDatatoPyTuple(args);
  175. bool is_bprop = this->HasAttr(kBpropAttrName);
  176. if (is_bprop) {
  177. SyncData(py_args);
  178. auto size = py_args.size();
  179. py::tuple input_args(size - 2);
  180. for (size_t i = 0; i < size - 2; ++i) {
  181. input_args[i] = py_args[i];
  182. }
  183. py::tuple convert_args(py_args.size());
  184. ConvertCTensorToPyTensor(py_args, &convert_args);
  185. auto inst = pynative::PynativeExecutor::GetInstance();
  186. MS_EXCEPTION_IF_NULL(inst);
  187. try {
  188. MS_LOG(DEBUG) << "Run bprop function start";
  189. inst->NewGraph(hook_, input_args.cast<py::args>());
  190. py::object grads_obj = hook_(*convert_args);
  191. py::tuple grads = check_bprop_out(grads_obj, py_args);
  192. inst->EndGraph(hook_, grads_obj, input_args.cast<py::args>());
  193. MS_LOG(DEBUG) << "Run bprop function end";
  194. return std::make_shared<PyObjectRef>(grads);
  195. } catch (std::exception &bt) {
  196. inst->ClearRes();
  197. std::rethrow_exception(std::current_exception());
  198. }
  199. }
  200. SyncData(py_args[2]);
  201. bool is_cell = this->HasAttr(kCellHookAttrName);
  202. py::object obj;
  203. if (is_cell) {
  204. auto cell_id = GetValue<std::string>(this->GetAttr(kCellIDAttrName));
  205. auto iter = hook_grad_.find(cell_id);
  206. if (iter != hook_grad_.end()) {
  207. py::tuple convert_args(2);
  208. py::tuple input_args(2);
  209. input_args[0] = iter->second;
  210. input_args[1] = py_args[2];
  211. ConvertCTensorToPyTensor(input_args, &convert_args);
  212. auto hook_args = py::tuple(3);
  213. hook_args[0] = cell_id;
  214. hook_args[1] = py::make_tuple(convert_args[0]);
  215. hook_args[2] = py::make_tuple(convert_args[1]);
  216. obj = hook_(*hook_args);
  217. if (py::isinstance<py::none>(obj)) {
  218. obj = py_args[2];
  219. }
  220. CheckHookConsistency(obj, py_args[2]);
  221. hook_grad_.erase(cell_id);
  222. } else {
  223. hook_grad_[cell_id] = py_args[2];
  224. obj = py_args[2];
  225. }
  226. } else {
  227. // Hook operator for execute variable hook function
  228. obj = hook_(py::make_tuple(py_args[2]));
  229. if (py::isinstance<py::none>(obj)) {
  230. obj = py_args[2];
  231. }
  232. CheckHookConsistency(obj, py_args[2]);
  233. }
  234. obj = py::make_tuple(obj);
  235. return std::make_shared<PyObjectRef>(obj);
  236. }
  237. py::function PrimitivePy::GetComputeFunction() const {
  238. static const char *const compute_func_name = "vm_impl";
  239. if (py::hasattr(python_obj_, compute_func_name)) {
  240. MS_LOG(INFO) << name() << " compute_func_name";
  241. py::function fn = python_obj_.attr(compute_func_name).cast<py::function>();
  242. return fn;
  243. }
  244. static const std::string vm_module = "mindspore.ops.vm_impl_registry";
  245. static const std::string get_vm_impl_fn = "get_vm_impl_fn";
  246. MS_LOG(INFO) << name() << ": get_vm_impl_fn";
  247. py::function get_fn = parse::python_adapter::GetPyFn(vm_module, get_vm_impl_fn);
  248. py::function vm_fn = get_fn(python_obj_);
  249. if (py::isinstance<py::none>(vm_fn)) {
  250. MS_LOG(INFO) << "Cannot find " << python_obj_.attr("__class__").attr("__name__").cast<std::string>();
  251. vm_fn = mindspore::GetComputeFunction(Primitive::name());
  252. }
  253. return vm_fn;
  254. }
  255. void PrimitivePy::AddPyAttr(const py::str &name, const py::object &obj) {
  256. std::string attr_name = name;
  257. ValuePtr converted_ret = nullptr;
  258. if (py::isinstance<py::module>(obj)) {
  259. MS_LOG(EXCEPTION) << "AddPyAttr failed, obj should not be py::module";
  260. }
  261. bool converted = parse::ConvertData(obj, &converted_ret);
  262. if (!converted) {
  263. MS_LOG(EXCEPTION) << "Attribute convert error with type: " << std::string(py::str(obj));
  264. }
  265. if (kOpAttrNameReplaceMap.find(attr_name) != kOpAttrNameReplaceMap.end()) {
  266. attr_name = kOpAttrNameReplaceMap[attr_name];
  267. }
  268. const std::string &prim_name = this->name();
  269. CheckAndConvertUtils::ConvertAttrValueToInt(prim_name, attr_name, &converted_ret);
  270. (void)this->AddAttr(attr_name, converted_ret);
  271. }
  272. void PrimitivePy::DelPyAttr(const py::str &name) {
  273. std::string attr_name = name;
  274. (void)this->DelAttr(attr_name);
  275. }
  276. py::dict PrimitivePy::GetAttrDict() {
  277. py::dict attr_dict;
  278. for (auto &attr : attrs_) {
  279. attr_dict[py::str(attr.first)] = ValuePtrToPyData(attr.second);
  280. }
  281. return attr_dict;
  282. }
  283. void PrimitivePy::CopyHookFunction(const PrimitivePtr &primitive) {
  284. MS_EXCEPTION_IF_NULL(primitive);
  285. if (!primitive->isa<PrimitivePy>()) {
  286. MS_LOG(EXCEPTION) << "Cannot copy a primtive which is not python primitive hook function to python primitive!";
  287. }
  288. auto primitive_py = primitive->cast<PrimitivePyPtr>();
  289. MS_EXCEPTION_IF_NULL(primitive_py);
  290. this->set_hook(primitive_py->hook());
  291. }
  292. BaseRef PrimitivePy::RunComputeFunction(const VectorRef &args) const {
  293. auto py_args = ConvertDatatoPyTuple(args);
  294. auto result = this->RunPyComputeFunction(py_args);
  295. if (py::isinstance<py::none>(result)) {
  296. return std::make_shared<BaseRef>(nullptr);
  297. }
  298. return std::make_shared<PyObjectRef>(result);
  299. }
  300. py::object PrimitivePy::RunPyComputeFunction(const py::tuple &py_args) const {
  301. auto func = this->GetComputeFunction();
  302. if (py::isinstance<py::none>(func)) {
  303. return py::none();
  304. }
  305. auto result = func(*py_args);
  306. return result;
  307. }
  308. bool PrimitivePy::HasComputeFunction() const {
  309. auto func = GetComputeFunction();
  310. return !py::isinstance<py::none>(func);
  311. }
  312. PrimitivePtr PrimitivePy::Clone() {
  313. auto clone_fn = python_obj_.attr("_clone");
  314. py::object new_obj = clone_fn();
  315. auto cloned_prim = new_obj.cast<PrimitivePyPtr>();
  316. return cloned_prim;
  317. }
  318. py::dict PrimitivePy::RunInfer(const py::tuple &args) {
  319. if (!HasPyObj()) {
  320. MS_LOG(EXCEPTION) << "[" << this->ToString() << "]: pyobj is empty";
  321. }
  322. // Python obj could be replaced as None, so it will losed the original info when throw exception in python.
  323. if (!py::hasattr(python_obj_, PY_PRIM_METHOD_INFER)) {
  324. MS_LOG(EXCEPTION) << "prim:" << ToString() << " has no attr:" << PY_PRIM_METHOD_INFER;
  325. }
  326. auto infer_fuc = python_obj_.attr(PY_PRIM_METHOD_INFER);
  327. return infer_fuc(*args);
  328. }
  329. void PrimitivePy::RunCheck(const py::tuple &args) {
  330. if (!HasPyObj()) {
  331. MS_LOG(EXCEPTION) << "[" << this->ToString() << "]: pyobj is empty";
  332. }
  333. // Python obj could be replaced as None, so it will losed the original info when throw exception in python.
  334. if (!py::hasattr(python_obj_, PY_PRIM_METHOD_CHECK)) {
  335. MS_LOG(EXCEPTION) << "prim:" << ToString() << " has no attr:" << PY_PRIM_METHOD_CHECK;
  336. }
  337. auto check_func = python_obj_.attr(PY_PRIM_METHOD_CHECK);
  338. (void)check_func(*args);
  339. }
  340. py::object PrimitivePy::RunInferValue(const py::tuple &args) {
  341. if (!HasPyObj()) {
  342. MS_LOG(EXCEPTION) << "[" << this->ToString() << "]: pyobj is empty";
  343. }
  344. // Python obj could be replaced as None, so it will losed the original info when throw exception in python.
  345. if (!py::hasattr(python_obj_, PY_PRIM_METHOD_INFER_VALUE)) {
  346. MS_LOG(EXCEPTION) << "prim:" << ToString() << " has no attr:" << PY_PRIM_METHOD_INFER_VALUE;
  347. }
  348. auto infer_value = python_obj_.attr(PY_PRIM_METHOD_INFER_VALUE);
  349. return infer_value(*args);
  350. }
  351. REGISTER_PYBIND_DEFINE(Primitive_, ([](const py::module *m) {
  352. (void)py::enum_<PrimType>(*m, "prim_type", py::arithmetic())
  353. .value("unknown", PrimType::kPrimTypeUnknown)
  354. .value("builtin", PrimType::kPrimTypeBuiltIn)
  355. .value("py_infer_shape", PrimType::kPrimTypePyInferShape)
  356. .value("user_custom", PrimType::kPrimTypeUserCustom)
  357. .value("py_infer_check", PrimType::kPrimTypePyInferCheck);
  358. (void)py::class_<PrimitivePy, std::shared_ptr<PrimitivePy>>(*m, "Primitive_")
  359. .def_readonly(PYTHON_PRIMITIVE_FLAG, &PrimitivePy::parse_info_)
  360. .def(py::init<py::str &, py::object>())
  361. .def("add_attr", &PrimitivePy::AddPyAttr, "add primitive attr")
  362. .def("del_attr", &PrimitivePy::DelPyAttr, "del primitive attr")
  363. .def("get_attr_dict", &PrimitivePy::GetAttrDict, "get primitive attr")
  364. .def("set_prim_type", &PrimitivePy::set_prim_type, "Set primitive type.")
  365. .def("set_const_prim", &PrimitivePy::set_const_prim, "Set primitive is const.")
  366. .def("set_const_input_indexes", &PrimitivePy::set_const_input_indexes,
  367. "Set primitive const input indexes.")
  368. .def("set_signatures", &PrimitivePy::set_signatures, "Set primitive inputs signature.")
  369. .def("register_hook", &PrimitivePy::set_hook, "Set primitive hook function.")
  370. .def("set_instance_name", &PrimitivePy::set_instance_name, "Set primitive instance name.");
  371. }));
  372. } // namespace mindspore