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

5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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 "./common.h"
  20. #include "pipeline/jit/parse/python_adapter.h"
  21. #include "pipeline/jit/parse/data_converter.h"
  22. #include "pybind11/pytypes.h"
  23. #include "utils/convert_utils_base.h"
  24. #include "utils/primitive_utils.h"
  25. #include "utils/base_ref_extends.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. BaseRef PrimitivePy::RunHookFunction(const VectorRef &args) const {
  76. py::tuple py_args = ConvertDatatoPyTuple(args);
  77. py::object obj;
  78. bool is_bprop = this->HasAttr(kBpropAttrName);
  79. if (is_bprop) {
  80. SyncData(py_args);
  81. py::tuple convert_args(py_args.size());
  82. for (size_t i = 0; i < py_args.size(); i++) {
  83. convert_args[i] = py::isinstance<tensor::Tensor>(py_args[i])
  84. ? parse::python_adapter::CallPyFn(parse::PYTHON_MOD_PARSE_MODULE,
  85. parse::PYTHON_MOD_CONVERT_TO_MS_TENSOR, py_args[i])
  86. : py_args[i];
  87. }
  88. obj = hook_(*convert_args);
  89. return std::make_shared<PyObjectRef>(obj);
  90. }
  91. SyncData(py_args[2]);
  92. bool is_cell = this->HasAttr(kCellHookAttrName);
  93. if (is_cell) {
  94. auto cell_id = GetValue<std::string>(this->GetAttr(kCellIDAttrName));
  95. auto iter = hook_grad_.find(cell_id);
  96. if (iter != hook_grad_.end()) {
  97. auto hook_args = py::tuple(3);
  98. hook_args[0] = cell_id;
  99. hook_args[1] = py::make_tuple(iter->second);
  100. hook_args[2] = py::make_tuple(py_args[2]);
  101. obj = hook_(*hook_args);
  102. if (py::isinstance<py::none>(obj)) {
  103. obj = py_args[2];
  104. }
  105. hook_grad_.erase(cell_id);
  106. } else {
  107. hook_grad_[cell_id] = py_args[2];
  108. obj = py_args[2];
  109. }
  110. } else {
  111. // Hook operator for execute variable hook function
  112. obj = hook_(py::make_tuple(py_args[2]));
  113. if (py::isinstance<py::none>(obj)) {
  114. obj = py_args[2];
  115. }
  116. }
  117. obj = py::make_tuple(obj);
  118. return std::make_shared<PyObjectRef>(obj);
  119. }
  120. py::function PrimitivePy::GetComputeFunction() const {
  121. static const char *const compute_func_name = "vm_impl";
  122. if (py::hasattr(python_obj_, compute_func_name)) {
  123. MS_LOG(INFO) << name() << " compute_func_name";
  124. py::function fn = python_obj_.attr(compute_func_name).cast<py::function>();
  125. return fn;
  126. }
  127. static const std::string vm_module = "mindspore.ops.vm_impl_registry";
  128. static const std::string get_vm_impl_fn = "get_vm_impl_fn";
  129. MS_LOG(INFO) << name() << ": get_vm_impl_fn";
  130. py::function get_fn = parse::python_adapter::GetPyFn(vm_module, get_vm_impl_fn);
  131. py::function vm_fn = get_fn(python_obj_);
  132. if (py::isinstance<py::none>(vm_fn)) {
  133. MS_LOG(WARNING) << "Cannot find " << python_obj_.attr("__class__").attr("__name__").cast<std::string>();
  134. vm_fn = mindspore::GetComputeFunction(Primitive::name());
  135. }
  136. return vm_fn;
  137. }
  138. void PrimitivePy::AddPyAttr(const py::str &name, const py::object &obj) {
  139. std::string attr_name = name;
  140. ValuePtr converted_ret = nullptr;
  141. if (py::isinstance<py::module>(obj)) {
  142. MS_LOG(EXCEPTION) << "AddPyAttr failed, obj should not be py::module";
  143. }
  144. bool converted = parse::ConvertData(obj, &converted_ret);
  145. if (!converted) {
  146. MS_LOG(EXCEPTION) << "Attribute convert error with type: " << std::string(py::str(obj));
  147. }
  148. (void)this->AddAttr(attr_name, converted_ret);
  149. }
  150. py::dict PrimitivePy::GetAttrDict() {
  151. py::dict attr_dict;
  152. for (auto &attr : attrs_) {
  153. attr_dict[py::str(attr.first)] = ValuePtrToPyData(attr.second);
  154. }
  155. return attr_dict;
  156. }
  157. void PrimitivePy::CopyHookFunction(const PrimitivePtr &primitive) {
  158. MS_EXCEPTION_IF_NULL(primitive);
  159. if (!primitive->isa<PrimitivePy>()) {
  160. MS_LOG(EXCEPTION) << "Cannot copy a primtive which is not python primitive hook function to python primitive!";
  161. }
  162. auto primitive_py = primitive->cast<PrimitivePyPtr>();
  163. MS_EXCEPTION_IF_NULL(primitive_py);
  164. this->set_hook(primitive_py->hook());
  165. }
  166. BaseRef PrimitivePy::RunComputeFunction(const VectorRef &args) const {
  167. auto py_args = ConvertDatatoPyTuple(args);
  168. auto result = this->RunPyComputeFunction(py_args);
  169. if (py::isinstance<py::none>(result)) {
  170. return std::make_shared<BaseRef>(nullptr);
  171. }
  172. return std::make_shared<PyObjectRef>(result);
  173. }
  174. py::object PrimitivePy::RunPyComputeFunction(const py::tuple &py_args) const {
  175. auto func = this->GetComputeFunction();
  176. if (py::isinstance<py::none>(func)) {
  177. return py::none();
  178. }
  179. auto result = func(*py_args);
  180. return result;
  181. }
  182. bool PrimitivePy::HasComputeFunction() const {
  183. auto func = GetComputeFunction();
  184. if (py::isinstance<py::none>(func)) {
  185. return false;
  186. }
  187. return true;
  188. }
  189. PrimitivePtr PrimitivePy::Clone() {
  190. auto clone_fn = python_obj_.attr("_clone");
  191. py::object new_obj = clone_fn();
  192. auto cloned_prim = new_obj.cast<PrimitivePyPtr>();
  193. return cloned_prim;
  194. }
  195. py::dict PrimitivePy::RunInfer(const py::tuple &args) {
  196. if (!HasPyObj()) {
  197. MS_LOG(EXCEPTION) << "[" << this->ToString() << "]: pyobj is empty";
  198. }
  199. auto infer_fuc = python_obj_.attr("__infer__");
  200. return infer_fuc(*args);
  201. }
  202. REGISTER_PYBIND_DEFINE(Primitive_, ([](const py::module *m) {
  203. (void)py::enum_<PrimType>(*m, "prim_type", py::arithmetic())
  204. .value("unknown", PrimType::kPrimTypeUnknown)
  205. .value("builtin", PrimType::kPrimTypeBuiltIn)
  206. .value("py_infer_shape", PrimType::kPrimTypePyInferShape)
  207. .value("user_custom", PrimType::kPrimTypeUserCustom);
  208. (void)py::class_<PrimitivePy, std::shared_ptr<PrimitivePy>>(*m, "Primitive_")
  209. .def_readonly(PYTHON_PRIMITIVE_FLAG, &PrimitivePy::parse_info_)
  210. .def(py::init<py::str &, py::object>())
  211. .def("add_attr", &PrimitivePy::AddPyAttr, "add primitive attr")
  212. .def("get_attr_dict", &PrimitivePy::GetAttrDict, "get primitive attr")
  213. .def("set_prim_type", &PrimitivePy::set_prim_type, "Set primitive type.")
  214. .def("set_is_const_value", &PrimitivePy::set_is_const_value, "Set primitive is const value.")
  215. .def("set_signatures", &PrimitivePy::set_signatures, "Set primitive inputs signature.")
  216. .def("register_hook", &PrimitivePy::set_hook, "Set primitive hook function.")
  217. .def("set_instance_name", &PrimitivePy::set_instance_name, "Set primitive instance name.");
  218. }));
  219. } // namespace mindspore