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

5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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 <utility>
  20. #include "ir/signature.h"
  21. #include "pipeline/jit/parse/data_converter.h"
  22. #include "pipeline/jit/parse/python_adapter.h"
  23. #include "pybind11/pytypes.h"
  24. #include "pybind_api/api_register.h"
  25. #include "pybind_api/export_flags.h"
  26. #include "pybind_api/ir/base_ref_py.h"
  27. #include "utils/convert_utils_base.h"
  28. #include "utils/convert_utils_py.h"
  29. #include "utils/ms_context.h"
  30. #include "utils/primitive_utils.h"
  31. #include "utils/check_convert_utils.h"
  32. #include "pipeline/jit/resource.h"
  33. #include "pipeline/pynative/pynative_execute.h"
  34. namespace mindspore {
  35. namespace {
  36. constexpr auto kBpropAttrName = "bprop";
  37. constexpr auto kCellHookAttrName = "cell_hook";
  38. constexpr auto kCellIDAttrName = "cell_id";
  39. std::map<std::string, std::string> kOpAttrNameReplaceMap = {
  40. {"data_format", "format"},
  41. };
  42. void SyncData(const py::object &arg) {
  43. if (py::isinstance<py::tuple>(arg)) {
  44. py::tuple arg_list = py::cast<py::tuple>(arg);
  45. for (size_t i = 0; i < arg_list.size(); i++) {
  46. SyncData(arg_list[i]);
  47. }
  48. }
  49. if (py::isinstance<tensor::Tensor>(arg)) {
  50. auto tensor = py::cast<tensor::TensorPtr>(arg);
  51. tensor->data_sync();
  52. }
  53. }
  54. } // namespace
  55. std::map<std::string, py::object> PrimitivePy::hook_grad_;
  56. PrimitivePy::PrimitivePy(const std::string &name) : Primitive(name, false), python_obj_(py::none()) {}
  57. PrimitivePy::PrimitivePy(const py::object &python_obj, const PrimitivePyAdapterPtr &adapter)
  58. : Primitive(adapter->name_, false), python_obj_(python_obj), adapter_(adapter) {
  59. MS_LOG(DEBUG) << "New primitive:" << adapter->name_;
  60. set_signatures(adapter->signatures_);
  61. (void)Primitive::SetAttrs(adapter->attrs_);
  62. Primitive::set_prim_type(adapter->prim_type_);
  63. Primitive::set_const_prim(adapter->is_const_prim_);
  64. Primitive::set_const_input_indexes(adapter->const_input_indexes_);
  65. set_hook(adapter->hook_);
  66. set_instance_name(adapter->instance_name_);
  67. }
  68. PrimitivePy::~PrimitivePy() {}
  69. void PrimitivePy::set_signatures(const std::vector<Signature> &signatures) {
  70. signatures_ = signatures;
  71. set_has_signature(!signatures.empty());
  72. }
  73. py::function PrimitivePy::GetBpropFunction() {
  74. static const char *const get_bprop_func_name = "get_bprop";
  75. if (py::hasattr(python_obj_, get_bprop_func_name)) {
  76. py::function fn = python_obj_.attr(get_bprop_func_name)().cast<py::function>();
  77. return fn;
  78. } else {
  79. auto fn = GetBpropFunctionByObj(python_obj_);
  80. return fn;
  81. }
  82. }
  83. py::tuple check_bprop_out(const py::object &grads_obj, const py::tuple &py_args, const std::string &bprop_cls_name) {
  84. py::tuple grads;
  85. if (!py::isinstance<py::tuple>(grads_obj)) {
  86. grads = py::make_tuple(grads_obj);
  87. } else {
  88. grads = py::cast<py::tuple>(grads_obj);
  89. }
  90. constexpr int filter_args_size = 2;
  91. if (grads.size() != py_args.size() - filter_args_size) {
  92. MS_EXCEPTION(TypeError) << "For user defined bprop of net '" << bprop_cls_name
  93. << "', the gradients number: " << grads.size()
  94. << " is not equal to the args number: " << (py_args.size() - filter_args_size) << ".";
  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) << "For user defined bprop of net '" << bprop_cls_name << "', the gradient of the "
  101. << i << "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) << "For user defined bprop of net '" << bprop_cls_name << "', the gradient of the "
  111. << i << "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) << "For user defined bprop of net '" << bprop_cls_name << "', the gradient of the "
  117. << i << "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. py::object code_obj = py::getattr(hook_, "__code__");
  160. py::object co_name = py::getattr(code_obj, "co_name");
  161. MS_EXCEPTION(TypeError) << "The output type of:" << py::str(co_name) << " should be a tensor but got "
  162. << py::cast<std::string>(grad_out.attr("__class__").attr("__name__")) << ".";
  163. }
  164. auto actual_out_tensor = py::cast<tensor::TensorPtr>(grad_out);
  165. auto expected_out_tensor = py::cast<tensor::TensorPtr>(expected_grad_out);
  166. MS_EXCEPTION_IF_NULL(actual_out_tensor);
  167. MS_EXCEPTION_IF_NULL(expected_out_tensor);
  168. if (actual_out_tensor->GetShapeAndDataTypeInfo() != expected_out_tensor->GetShapeAndDataTypeInfo()) {
  169. hook_grad_.clear();
  170. py::object code_obj = py::getattr(hook_, "__code__");
  171. py::object co_name = py::getattr(code_obj, "co_name");
  172. MS_EXCEPTION(ValueError) << "The output type of " << py::str(co_name)
  173. << " is not consistent with the expected, it should be "
  174. << expected_out_tensor->GetShapeAndDataTypeInfo() << ", but got "
  175. << actual_out_tensor->GetShapeAndDataTypeInfo();
  176. }
  177. }
  178. }
  179. BaseRef PrimitivePy::RunCellBpropFunction(const py::tuple &py_args) const {
  180. SyncData(py_args);
  181. auto size = py_args.size();
  182. constexpr size_t grad_param_nums = 2;
  183. py::tuple input_args(size - grad_param_nums);
  184. for (size_t i = 0; i < size - grad_param_nums; ++i) {
  185. input_args[i] = py_args[i];
  186. }
  187. py::tuple convert_args(py_args.size());
  188. ConvertCTensorToPyTensor(py_args, &convert_args);
  189. auto inst = pynative::PynativeExecutor::GetInstance();
  190. MS_EXCEPTION_IF_NULL(inst);
  191. try {
  192. MS_LOG(DEBUG) << "Run bprop function start";
  193. inst->NewGraph(hook_, input_args.cast<py::args>());
  194. py::object grads_obj = hook_(*convert_args);
  195. py::tuple grads = check_bprop_out(grads_obj, py_args, bprop_cls_name_);
  196. inst->EndGraph(hook_, grads_obj, input_args.cast<py::args>());
  197. MS_LOG(DEBUG) << "Run bprop function end";
  198. return std::make_shared<PyObjectRef>(grads);
  199. } catch (std::exception &bt) {
  200. inst->ClearRes();
  201. std::rethrow_exception(std::current_exception());
  202. }
  203. }
  204. BaseRef PrimitivePy::RunCellHookFunction(const py::tuple &py_args) const {
  205. constexpr size_t grad_input_index = 1;
  206. constexpr size_t grad_output_index = 2;
  207. constexpr size_t input_param_nums = 3;
  208. SyncData(py_args[grad_output_index]);
  209. py::object obj;
  210. auto cell_id = GetValue<std::string>(this->GetAttr(kCellIDAttrName));
  211. auto iter = hook_grad_.find(cell_id);
  212. if (iter != hook_grad_.end()) {
  213. py::object code_obj = py::getattr(hook_, "__code__");
  214. py::object co_name = py::getattr(code_obj, "co_name");
  215. if (std::string(py::str(co_name)) == "staging_specialize") {
  216. py::object name_obj = py::getattr(hook_, "__name__");
  217. MS_LOG(EXCEPTION) << "Decorating hook function " << py::str(name_obj) << " with '@ms_function' is not supported.";
  218. }
  219. py::tuple convert_args(input_param_nums - 1);
  220. py::tuple input_args(input_param_nums - 1);
  221. input_args[0] = iter->second;
  222. input_args[1] = py_args[grad_output_index];
  223. ConvertCTensorToPyTensor(input_args, &convert_args);
  224. auto hook_args = py::tuple(input_param_nums);
  225. hook_args[0] = cell_id;
  226. hook_args[grad_input_index] = py::make_tuple(convert_args[0]);
  227. hook_args[grad_output_index] = py::make_tuple(convert_args[1]);
  228. obj = hook_(*hook_args);
  229. if (py::isinstance<py::none>(obj)) {
  230. obj = py_args[grad_output_index];
  231. }
  232. CheckHookConsistency(obj, py_args[grad_output_index]);
  233. (void)hook_grad_.erase(cell_id);
  234. } else {
  235. hook_grad_[cell_id] = py_args[grad_output_index];
  236. obj = py_args[grad_output_index];
  237. }
  238. obj = py::make_tuple(obj);
  239. return std::make_shared<PyObjectRef>(obj);
  240. }
  241. BaseRef PrimitivePy::RunVariableHookFunction(const py::tuple &py_args) const {
  242. py::object code_obj = py::getattr(hook_, "__code__");
  243. py::object co_name = py::getattr(code_obj, "co_name");
  244. if (std::string(py::str(co_name)) == "staging_specialize") {
  245. py::object name_obj = py::getattr(hook_, "__name__");
  246. MS_LOG(EXCEPTION) << "Decorating hook function " << py::str(name_obj) << " with '@ms_function' is not supported.";
  247. }
  248. constexpr size_t grad_output_index = 2;
  249. SyncData(py_args[grad_output_index]);
  250. py::object obj = hook_(py::make_tuple(py_args[grad_output_index]));
  251. if (py::isinstance<py::none>(obj)) {
  252. obj = py_args[grad_output_index];
  253. }
  254. CheckHookConsistency(obj, py_args[grad_output_index]);
  255. obj = py::make_tuple(obj);
  256. return std::make_shared<PyObjectRef>(obj);
  257. }
  258. BaseRef PrimitivePy::RunHookFunction(const VectorRef &args) const {
  259. py::tuple py_args = ConvertDatatoPyTuple(args);
  260. bool is_bprop = this->HasAttr(kBpropAttrName);
  261. if (is_bprop) {
  262. return RunCellBpropFunction(py_args);
  263. }
  264. bool is_cell = this->HasAttr(kCellHookAttrName);
  265. if (is_cell) {
  266. return RunCellHookFunction(py_args);
  267. }
  268. return RunVariableHookFunction(py_args);
  269. }
  270. py::function PrimitivePy::GetComputeFunction() const {
  271. static const char *const compute_func_name = "vm_impl";
  272. if (py::hasattr(python_obj_, compute_func_name)) {
  273. MS_LOG(DEBUG) << name() << " compute_func_name";
  274. py::function fn = python_obj_.attr(compute_func_name).cast<py::function>();
  275. return fn;
  276. }
  277. static const std::string vm_module = "mindspore.ops.vm_impl_registry";
  278. static const std::string get_vm_impl_fn = "get_vm_impl_fn";
  279. MS_LOG(DEBUG) << name() << ": get_vm_impl_fn";
  280. py::function get_fn = parse::python_adapter::GetPyFn(vm_module, get_vm_impl_fn);
  281. py::function vm_fn = get_fn(python_obj_);
  282. if (py::isinstance<py::none>(vm_fn)) {
  283. MS_LOG(DEBUG) << "Cannot find " << python_obj_.attr("__class__").attr("__name__").cast<std::string>();
  284. vm_fn = mindspore::GetComputeFunction(Primitive::name());
  285. }
  286. return vm_fn;
  287. }
  288. py::dict PrimitivePy::GetAttrDict() {
  289. py::dict attr_dict;
  290. for (auto &attr : attrs_) {
  291. attr_dict[py::str(attr.first)] = ValueToPyData(attr.second);
  292. }
  293. return attr_dict;
  294. }
  295. void PrimitivePy::CopyHookFunction(const PrimitivePtr &primitive) {
  296. MS_EXCEPTION_IF_NULL(primitive);
  297. if (!primitive->isa<PrimitivePy>()) {
  298. MS_LOG(EXCEPTION) << "Cannot copy a primitive which is not python primitive hook function to python primitive!";
  299. }
  300. auto primitive_py = primitive->cast<PrimitivePyPtr>();
  301. MS_EXCEPTION_IF_NULL(primitive_py);
  302. this->set_hook(primitive_py->hook());
  303. if (primitive_py->HasAttr(kBpropAttrName)) {
  304. set_bprop_cls_name(primitive_py->bprop_cls_name_);
  305. (void)this->AddAttr(kBpropAttrName, primitive_py->GetAttr(kBpropAttrName));
  306. }
  307. }
  308. BaseRef PrimitivePy::RunComputeFunction(const VectorRef &args) const {
  309. auto py_args = ConvertDatatoPyTuple(args);
  310. auto result = this->RunPyComputeFunction(py_args);
  311. if (py::isinstance<py::none>(result)) {
  312. return std::make_shared<BaseRef>(nullptr);
  313. }
  314. return std::make_shared<PyObjectRef>(result);
  315. }
  316. py::object PrimitivePy::RunPyComputeFunction(const py::tuple &py_args) const {
  317. auto func = this->GetComputeFunction();
  318. if (py::isinstance<py::none>(func)) {
  319. return py::none();
  320. }
  321. auto result = func(*py_args);
  322. return result;
  323. }
  324. bool PrimitivePy::HasComputeFunction() const {
  325. auto func = GetComputeFunction();
  326. return !py::isinstance<py::none>(func);
  327. }
  328. PrimitivePtr PrimitivePy::Clone() {
  329. auto clone_fn = python_obj_.attr("_clone");
  330. py::object obj_adapter = clone_fn();
  331. auto prim_adapter = obj_adapter.cast<PrimitivePyAdapterPtr>();
  332. auto prim = std::make_shared<PrimitivePy>(obj_adapter, prim_adapter);
  333. prim_adapter->set_attached_primitive(prim);
  334. return prim;
  335. }
  336. py::dict PrimitivePy::RunInfer(const py::tuple &args) {
  337. if (!HasPyObj()) {
  338. MS_LOG(EXCEPTION) << "[" << this->ToString() << "]: pyobj is empty";
  339. }
  340. // Python obj could be replaced as None, so it will losed the original info when throw exception in python.
  341. if (!py::hasattr(python_obj_, PY_PRIM_METHOD_INFER)) {
  342. MS_LOG(EXCEPTION) << "prim:" << ToString() << " has no attr:" << PY_PRIM_METHOD_INFER;
  343. }
  344. auto infer_fuc = python_obj_.attr(PY_PRIM_METHOD_INFER);
  345. return infer_fuc(*args);
  346. }
  347. void PrimitivePy::RunCheck(const py::tuple &args) {
  348. if (!HasPyObj()) {
  349. MS_LOG(EXCEPTION) << "[" << this->ToString() << "]: pyobj is empty";
  350. }
  351. // Python obj could be replaced as None, so it will losed the original info when throw exception in python.
  352. if (!py::hasattr(python_obj_, PY_PRIM_METHOD_CHECK)) {
  353. MS_LOG(EXCEPTION) << "prim:" << ToString() << " has no attr:" << PY_PRIM_METHOD_CHECK;
  354. }
  355. auto check_func = python_obj_.attr(PY_PRIM_METHOD_CHECK);
  356. (void)check_func(*args);
  357. }
  358. py::object PrimitivePy::RunInferValue(const py::tuple &args) {
  359. if (!HasPyObj()) {
  360. MS_LOG(EXCEPTION) << "[" << this->ToString() << "]: pyobj is empty";
  361. }
  362. // Python obj could be replaced as None, so it will losed the original info when throw exception in python.
  363. if (!py::hasattr(python_obj_, PY_PRIM_METHOD_INFER_VALUE)) {
  364. MS_LOG(EXCEPTION) << "prim:" << ToString() << " has no attr:" << PY_PRIM_METHOD_INFER_VALUE;
  365. }
  366. auto infer_value = python_obj_.attr(PY_PRIM_METHOD_INFER_VALUE);
  367. return infer_value(*args);
  368. }
  369. PrimitivePyAdapter::PrimitivePyAdapter(const py::str &name) : name_(name) {}
  370. void PrimitivePyAdapter::AddPyAttr(const py::str &name, const py::object &obj) {
  371. std::string attr_name = name;
  372. ValuePtr converted_ret = nullptr;
  373. if (py::isinstance<py::module>(obj)) {
  374. MS_LOG(EXCEPTION) << "Call 'add_attr' to add attribute to prim failed,"
  375. << " not support py::module to be attribute value; prim name: " << this->name_
  376. << ", attribute name: " << attr_name << " attribute value: " << py::str(obj);
  377. }
  378. bool converted = parse::ConvertData(obj, &converted_ret);
  379. if (!converted) {
  380. MS_LOG(EXCEPTION) << "Call 'add_attr' to add attribute to prim failed,"
  381. << " convert python obj to MindSpore obj failed; prim name: " << this->name_
  382. << ", attribute name:" << attr_name << ", attribute value:" << py::str(obj)
  383. << ", attribute type:" << py::cast<std::string>(obj.attr("__class__").attr("__name__"));
  384. }
  385. if (kOpAttrNameReplaceMap.find(attr_name) != kOpAttrNameReplaceMap.end()) {
  386. attr_name = kOpAttrNameReplaceMap[attr_name];
  387. }
  388. (void)CheckAndConvertUtils::ConvertAttrValueToInt(this->name_, name, &converted_ret);
  389. if (attr_name == "primitive_target") {
  390. MS_EXCEPTION_IF_NULL(converted_ret);
  391. if (!converted_ret->isa<StringImm>()) {
  392. MS_LOG(EXCEPTION) << "Call 'add_attr' to add attribute to prim '" << this->name_
  393. << "' failed, value of attribute 'primitive_target' must be CPU|GPU|Ascend but got "
  394. << py::str(obj);
  395. }
  396. auto target = GetValue<std::string>(converted_ret);
  397. if (!target.empty() && target != kCPUDevice && target != kGPUDevice && target != kAscendDevice &&
  398. target != "Device") {
  399. MS_LOG(EXCEPTION) << "Call 'add_attr' to add attribute to prim '" << this->name_
  400. << "' failed, value of attribute 'primitive_target' must be CPU|GPU|Ascend but got "
  401. << py::str(obj);
  402. }
  403. if (target != kCPUDevice && target != kGPUDevice) {
  404. auto context_ptr = MsContext::GetInstance();
  405. MS_EXCEPTION_IF_NULL(context_ptr);
  406. context_ptr->set_param<bool>(MS_CTX_ALREADY_SET_ENABLE_MINDRT, true);
  407. }
  408. }
  409. attrs_[attr_name] = converted_ret;
  410. auto prim = attached_primitive_.lock();
  411. if (prim != nullptr) {
  412. (void)prim->AddAttr(attr_name, converted_ret);
  413. }
  414. }
  415. void PrimitivePyAdapter::DelPyAttr(const py::str &name) {
  416. (void)attrs_.erase(name);
  417. auto prim = attached_primitive_.lock();
  418. if (prim != nullptr) {
  419. (void)prim->DelAttr(name);
  420. }
  421. }
  422. py::dict PrimitivePyAdapter::GetAttrDict() {
  423. auto prim = attached_primitive_.lock();
  424. if (prim != nullptr) {
  425. return prim->GetAttrDict();
  426. }
  427. py::dict attr_dict;
  428. for (auto &attr : attrs_) {
  429. attr_dict[py::str(attr.first)] = ValueToPyData(attr.second);
  430. }
  431. return attr_dict;
  432. }
  433. void PrimitivePyAdapter::set_prim_type(const PrimType t) {
  434. prim_type_ = t;
  435. auto prim = attached_primitive_.lock();
  436. if (prim != nullptr) {
  437. prim->set_prim_type(t);
  438. }
  439. }
  440. void PrimitivePyAdapter::set_const_prim(bool is_const_prim) {
  441. is_const_prim_ = is_const_prim;
  442. auto prim = attached_primitive_.lock();
  443. if (prim != nullptr) {
  444. prim->set_const_prim(is_const_prim);
  445. }
  446. }
  447. void PrimitivePyAdapter::set_const_input_indexes(const std::vector<size_t> &const_input_indexes) {
  448. const_input_indexes_ = const_input_indexes;
  449. auto prim = attached_primitive_.lock();
  450. if (prim != nullptr) {
  451. prim->set_const_input_indexes(const_input_indexes);
  452. }
  453. }
  454. void PrimitivePyAdapter::set_signatures(const std::vector<Signature> &signatures) {
  455. signatures_ = signatures;
  456. auto prim = attached_primitive_.lock();
  457. if (prim != nullptr) {
  458. prim->set_signatures(signatures);
  459. }
  460. }
  461. void PrimitivePyAdapter::set_hook(const py::function &hook) {
  462. hook_ = hook;
  463. auto prim = attached_primitive_.lock();
  464. if (prim != nullptr) {
  465. prim->set_hook(hook);
  466. }
  467. }
  468. void PrimitivePyAdapter::set_instance_name(const std::string &s) {
  469. instance_name_ = s;
  470. auto prim = attached_primitive_.lock();
  471. if (prim != nullptr) {
  472. prim->set_instance_name(s);
  473. }
  474. }
  475. void PrimitivePyAdapter::set_attached_primitive(const PrimitivePyPtr &prim) {
  476. if (attached_primitive_.lock() != nullptr) {
  477. MS_LOG(EXCEPTION) << "PrimitivePyAdapter can't attach to multi Primitive.";
  478. }
  479. MS_EXCEPTION_IF_NULL(prim);
  480. attached_primitive_ = prim;
  481. }
  482. REGISTER_PYBIND_DEFINE(Primitive_, ([](const py::module *m) {
  483. (void)py::enum_<PrimType>(*m, "prim_type", py::arithmetic())
  484. .value("unknown", PrimType::kPrimTypeUnknown)
  485. .value("builtin", PrimType::kPrimTypeBuiltIn)
  486. .value("py_infer_shape", PrimType::kPrimTypePyInfer)
  487. .value("user_custom", PrimType::kPrimTypeUserCustom)
  488. .value("py_infer_check", PrimType::kPrimTypePyCheck);
  489. (void)py::class_<PrimitivePyAdapter, std::shared_ptr<PrimitivePyAdapter>>(*m, "Primitive_")
  490. .def_readonly(PYTHON_PRIMITIVE_FLAG, &PrimitivePyAdapter::parse_info_)
  491. .def(py::init<py::str &>())
  492. .def("add_attr", &PrimitivePyAdapter::AddPyAttr, "add primitive attr")
  493. .def("del_attr", &PrimitivePyAdapter::DelPyAttr, "del primitive attr")
  494. .def("get_attr_dict", &PrimitivePyAdapter::GetAttrDict, "get primitive attr")
  495. .def("set_prim_type", &PrimitivePyAdapter::set_prim_type, "Set primitive type.")
  496. .def("set_const_prim", &PrimitivePyAdapter::set_const_prim, "Set primitive is const.")
  497. .def("set_const_input_indexes", &PrimitivePyAdapter::set_const_input_indexes,
  498. "Set primitive const input indexes.")
  499. .def("set_signatures", &PrimitivePyAdapter::set_signatures,
  500. "Set primitive inputs signature.")
  501. .def("register_hook", &PrimitivePyAdapter::set_hook, "Set primitive hook function.")
  502. .def("set_instance_name", &PrimitivePyAdapter::set_instance_name,
  503. "Set primitive instance name.");
  504. }));
  505. } // namespace mindspore