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 11 kB

5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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 "ir/signature.h"
  19. #include "pipeline/jit/parse/python_adapter.h"
  20. #include "pipeline/jit/parse/data_converter.h"
  21. #include "pybind11/pytypes.h"
  22. #include "utils/convert_utils_base.h"
  23. #include "utils/primitive_utils.h"
  24. #include "utils/base_ref_extends.h"
  25. #include "utils/ms_context.h"
  26. #include "pybind_api/api_register.h"
  27. #include "pybind_api/export_flags.h"
  28. #include "pybind_api/ir/base_ref_py.h"
  29. namespace mindspore {
  30. namespace {
  31. constexpr auto kBpropAttrName = "bprop";
  32. constexpr auto kCellHookAttrName = "cell_hook";
  33. constexpr auto kCellIDAttrName = "cell_id";
  34. void SyncData(const py::object &arg) {
  35. if (py::isinstance<py::tuple>(arg)) {
  36. py::tuple arg_list = py::cast<py::tuple>(arg);
  37. for (size_t i = 0; i < arg_list.size(); i++) {
  38. SyncData(arg_list[i]);
  39. }
  40. }
  41. if (py::isinstance<tensor::Tensor>(arg)) {
  42. auto tensor = py::cast<tensor::TensorPtr>(arg);
  43. (void)tensor->data_sync();
  44. }
  45. }
  46. } // namespace
  47. std::map<std::string, py::object> PrimitivePy::hook_grad_;
  48. static ValuePtr PyArgToValue(const py::object &arg) {
  49. if (py::isinstance<SignatureEnumKind>(arg) &&
  50. py::cast<SignatureEnumKind>(arg) == SignatureEnumKind::kKindEmptyDefaultValue) {
  51. return nullptr;
  52. }
  53. return parse::data_converter::PyDataToValue(arg);
  54. }
  55. void PrimitivePy::set_signatures(
  56. std::vector<std::tuple<std::string, SignatureEnumRW, SignatureEnumKind, py::object, SignatureEnumDType>> signatures) {
  57. signatures_.clear();
  58. for (auto &signature : signatures) {
  59. auto [name, rw, kind, arg_default, dtype] = signature;
  60. auto default_value = PyArgToValue(arg_default);
  61. signatures_.emplace_back(name, rw, kind, default_value, dtype);
  62. }
  63. set_has_signature(true);
  64. }
  65. py::function PrimitivePy::GetBpropFunction() {
  66. static const char *const get_bprop_func_name = "get_bprop";
  67. if (py::hasattr(python_obj_, get_bprop_func_name)) {
  68. py::function fn = python_obj_.attr(get_bprop_func_name)().cast<py::function>();
  69. return fn;
  70. } else {
  71. auto fn = GetBpropFunctionByObj(python_obj_);
  72. return fn;
  73. }
  74. }
  75. py::tuple check_bprop_out(const py::object &grads_obj, const py::tuple &py_args) {
  76. py::tuple grads;
  77. if (!py::isinstance<py::tuple>(grads_obj)) {
  78. grads = py::make_tuple(grads_obj);
  79. } else {
  80. grads = py::cast<py::tuple>(grads_obj);
  81. }
  82. if (grads.size() != py_args.size() - 2) {
  83. MS_EXCEPTION(ValueError) << "For user define net bprop, the gradients number: " << grads.size()
  84. << " is not equal to the args number: " << py_args.size() - 2 << ".";
  85. }
  86. if (MsContext::GetInstance()->check_bprop_flag()) {
  87. for (size_t i = 0; i < grads.size(); i++) {
  88. if (py::isinstance<tensor::Tensor>(py_args[i])) {
  89. if (!py::isinstance<tensor::Tensor>(grads[i])) {
  90. MS_EXCEPTION(ValueError) << "For user define net bprop, the gradient of the " << i
  91. << "th arg should be Tensor, but got "
  92. << py::cast<std::string>(grads[i].attr("__class__").attr("__name__"))
  93. << ", and the value is " << py::cast<py::str>(grads[i]) << ".";
  94. }
  95. py::tuple grad_shape = grads[i].attr("shape");
  96. py::object grad_dtype = grads[i].attr("dtype");
  97. py::tuple arg_shape = py_args[i].attr("shape");
  98. py::object arg_dtype = py_args[i].attr("dtype");
  99. if (!grad_shape.equal(arg_shape) || !grad_dtype.is(arg_dtype)) {
  100. MS_EXCEPTION(ValueError) << "For user define net bprop, the gradient of the " << i
  101. << "th arg should have the same shape and dtype as the " << i << "th arg, but the "
  102. << i << "th arg shape: " << py::cast<py::str>(arg_shape)
  103. << " and dtype: " << py::cast<py::str>(arg_dtype)
  104. << ", the gradient shape: " << py::cast<py::str>(grad_shape)
  105. << " and dtype: " << py::cast<py::str>(grad_dtype) << ".";
  106. }
  107. }
  108. }
  109. }
  110. return grads;
  111. }
  112. BaseRef PrimitivePy::RunHookFunction(const VectorRef &args) const {
  113. py::tuple py_args = ConvertDatatoPyTuple(args);
  114. bool is_bprop = this->HasAttr(kBpropAttrName);
  115. if (is_bprop) {
  116. SyncData(py_args);
  117. py::tuple convert_args(py_args.size());
  118. for (size_t i = 0; i < py_args.size(); i++) {
  119. convert_args[i] = py::isinstance<tensor::Tensor>(py_args[i])
  120. ? parse::python_adapter::CallPyFn(parse::PYTHON_MOD_PARSE_MODULE,
  121. parse::PYTHON_MOD_CONVERT_TO_MS_TENSOR, py_args[i])
  122. : py_args[i];
  123. }
  124. py::object grads_obj = hook_(*convert_args);
  125. py::tuple grads = check_bprop_out(grads_obj, py_args);
  126. return std::make_shared<PyObjectRef>(grads);
  127. }
  128. SyncData(py_args[2]);
  129. bool is_cell = this->HasAttr(kCellHookAttrName);
  130. py::object obj;
  131. if (is_cell) {
  132. auto cell_id = GetValue<std::string>(this->GetAttr(kCellIDAttrName));
  133. auto iter = hook_grad_.find(cell_id);
  134. if (iter != hook_grad_.end()) {
  135. auto hook_args = py::tuple(3);
  136. hook_args[0] = cell_id;
  137. hook_args[1] = py::make_tuple(iter->second);
  138. hook_args[2] = py::make_tuple(py_args[2]);
  139. obj = hook_(*hook_args);
  140. if (py::isinstance<py::none>(obj)) {
  141. obj = py_args[2];
  142. }
  143. hook_grad_.erase(cell_id);
  144. } else {
  145. hook_grad_[cell_id] = py_args[2];
  146. obj = py_args[2];
  147. }
  148. } else {
  149. // Hook operator for execute variable hook function
  150. obj = hook_(py::make_tuple(py_args[2]));
  151. if (py::isinstance<py::none>(obj)) {
  152. obj = py_args[2];
  153. }
  154. }
  155. obj = py::make_tuple(obj);
  156. return std::make_shared<PyObjectRef>(obj);
  157. }
  158. py::function PrimitivePy::GetComputeFunction() const {
  159. static const char *const compute_func_name = "vm_impl";
  160. if (py::hasattr(python_obj_, compute_func_name)) {
  161. MS_LOG(INFO) << name() << " compute_func_name";
  162. py::function fn = python_obj_.attr(compute_func_name).cast<py::function>();
  163. return fn;
  164. }
  165. static const std::string vm_module = "mindspore.ops.vm_impl_registry";
  166. static const std::string get_vm_impl_fn = "get_vm_impl_fn";
  167. MS_LOG(INFO) << name() << ": get_vm_impl_fn";
  168. py::function get_fn = parse::python_adapter::GetPyFn(vm_module, get_vm_impl_fn);
  169. py::function vm_fn = get_fn(python_obj_);
  170. if (py::isinstance<py::none>(vm_fn)) {
  171. MS_LOG(INFO) << "Cannot find " << python_obj_.attr("__class__").attr("__name__").cast<std::string>();
  172. vm_fn = mindspore::GetComputeFunction(Primitive::name());
  173. }
  174. return vm_fn;
  175. }
  176. void PrimitivePy::AddPyAttr(const py::str &name, const py::object &obj) {
  177. std::string attr_name = name;
  178. ValuePtr converted_ret = nullptr;
  179. if (py::isinstance<py::module>(obj)) {
  180. MS_LOG(EXCEPTION) << "AddPyAttr failed, obj should not be py::module";
  181. }
  182. bool converted = parse::ConvertData(obj, &converted_ret);
  183. if (!converted) {
  184. MS_LOG(EXCEPTION) << "Attribute convert error with type: " << std::string(py::str(obj));
  185. }
  186. (void)this->AddAttr(attr_name, converted_ret);
  187. }
  188. py::dict PrimitivePy::GetAttrDict() {
  189. py::dict attr_dict;
  190. for (auto &attr : attrs_) {
  191. attr_dict[py::str(attr.first)] = ValuePtrToPyData(attr.second);
  192. }
  193. return attr_dict;
  194. }
  195. void PrimitivePy::CopyHookFunction(const PrimitivePtr &primitive) {
  196. MS_EXCEPTION_IF_NULL(primitive);
  197. if (!primitive->isa<PrimitivePy>()) {
  198. MS_LOG(EXCEPTION) << "Cannot copy a primtive which is not python primitive hook function to python primitive!";
  199. }
  200. auto primitive_py = primitive->cast<PrimitivePyPtr>();
  201. MS_EXCEPTION_IF_NULL(primitive_py);
  202. this->set_hook(primitive_py->hook());
  203. }
  204. BaseRef PrimitivePy::RunComputeFunction(const VectorRef &args) const {
  205. auto py_args = ConvertDatatoPyTuple(args);
  206. auto result = this->RunPyComputeFunction(py_args);
  207. if (py::isinstance<py::none>(result)) {
  208. return std::make_shared<BaseRef>(nullptr);
  209. }
  210. return std::make_shared<PyObjectRef>(result);
  211. }
  212. py::object PrimitivePy::RunPyComputeFunction(const py::tuple &py_args) const {
  213. auto func = this->GetComputeFunction();
  214. if (py::isinstance<py::none>(func)) {
  215. return py::none();
  216. }
  217. auto result = func(*py_args);
  218. return result;
  219. }
  220. bool PrimitivePy::HasComputeFunction() const {
  221. auto func = GetComputeFunction();
  222. if (py::isinstance<py::none>(func)) {
  223. return false;
  224. }
  225. return true;
  226. }
  227. PrimitivePtr PrimitivePy::Clone() {
  228. auto clone_fn = python_obj_.attr("_clone");
  229. py::object new_obj = clone_fn();
  230. auto cloned_prim = new_obj.cast<PrimitivePyPtr>();
  231. return cloned_prim;
  232. }
  233. py::dict PrimitivePy::RunInfer(const py::tuple &args) {
  234. if (!HasPyObj()) {
  235. MS_LOG(EXCEPTION) << "[" << this->ToString() << "]: pyobj is empty";
  236. }
  237. auto infer_fuc = python_obj_.attr("__infer__");
  238. return infer_fuc(*args);
  239. }
  240. REGISTER_PYBIND_DEFINE(Primitive_, ([](const py::module *m) {
  241. (void)py::enum_<PrimType>(*m, "prim_type", py::arithmetic())
  242. .value("unknown", PrimType::kPrimTypeUnknown)
  243. .value("builtin", PrimType::kPrimTypeBuiltIn)
  244. .value("py_infer_shape", PrimType::kPrimTypePyInferShape)
  245. .value("user_custom", PrimType::kPrimTypeUserCustom);
  246. (void)py::class_<PrimitivePy, std::shared_ptr<PrimitivePy>>(*m, "Primitive_")
  247. .def_readonly(PYTHON_PRIMITIVE_FLAG, &PrimitivePy::parse_info_)
  248. .def(py::init<py::str &, py::object>())
  249. .def("add_attr", &PrimitivePy::AddPyAttr, "add primitive attr")
  250. .def("get_attr_dict", &PrimitivePy::GetAttrDict, "get primitive attr")
  251. .def("set_prim_type", &PrimitivePy::set_prim_type, "Set primitive type.")
  252. .def("set_is_const_value", &PrimitivePy::set_is_const_value, "Set primitive is const value.")
  253. .def("set_signatures", &PrimitivePy::set_signatures, "Set primitive inputs signature.")
  254. .def("register_hook", &PrimitivePy::set_hook, "Set primitive hook function.")
  255. .def("set_instance_name", &PrimitivePy::set_instance_name, "Set primitive instance name.");
  256. }));
  257. } // namespace mindspore