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.

resource.cc 18 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. /**
  2. * This is the C++ adaptation and derivative work of Myia (https://github.com/mila-iqia/myia/).
  3. *
  4. * Copyright 2019 Huawei Technologies Co., Ltd
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. #include "pipeline/jit/resource.h"
  19. #include "pipeline/jit/static_analysis/static_analysis.h"
  20. #include "debug/trace.h"
  21. #include "ir/dtype.h"
  22. #include "pipeline/jit/parse/data_converter.h"
  23. #include "frontend/operator/ops.h"
  24. #include "frontend/optimizer/ad/dfunctor.h"
  25. namespace mindspore {
  26. // namespace to support opmap definition
  27. namespace pipeline {
  28. BuiltInTypeMap &GetMethodMap() {
  29. static BuiltInTypeMap method_map = {{kObjectTypeString,
  30. {
  31. {"__bool__", std::string("str_bool")} // C.str_bool
  32. }},
  33. {kMetaTypeNone,
  34. {
  35. {"__bool__", std::string("none_bool")} // C.none_bool
  36. }},
  37. {kObjectTypeFunction,
  38. {
  39. {"__bool__", std::string("func_bool")} // C.str_bool
  40. }},
  41. {kNumberTypeBool,
  42. {
  43. {"__and__", prim::kPrimBoolAnd}, // P.bool_and
  44. {"__or__", prim::kPrimBoolOr}, // P.bool_or
  45. {"__eq__", prim::kPrimBoolEq}, // P.bool_eq
  46. {"__ne__", std::string("bool_ne")}, // C.bool_ne
  47. {"__bool__", prim::kPrimIdentity} // P.identity
  48. }},
  49. {kNumberTypeInt,
  50. {
  51. {"__add__", prim::kPrimScalarAdd}, // P.scalar_add
  52. {"__sub__", prim::kPrimScalarSub}, // P.scalar_sub
  53. {"__mul__", prim::kPrimScalarMul}, // P.scalar_mul
  54. {"__floordiv__", std::string("int_floordiv")}, // C.int_floordiv
  55. {"__truediv__", std::string("int_truediv")}, // C.int_truediv
  56. {"__mod__", prim::kPrimScalarMod}, // P.scalar_mod
  57. {"__pow__", prim::kPrimScalarPow}, // P.scalar_pow
  58. {"__floor__", prim::kPrimIdentity}, // P.identity
  59. {"__trunc__", prim::kPrimIdentity}, // P.identity
  60. {"__pos__", prim::kPrimScalarUadd}, // P.scalar_uadd
  61. {"__neg__", prim::kPrimScalarUsub}, // P.scalar_usub
  62. {"__eq__", prim::kPrimScalarEq}, // P.scalar_eq
  63. {"__ne__", prim::kPrimScalarNe}, // P.scalar_ne
  64. {"__lt__", prim::kPrimScalarLt}, // P.scalar_lt
  65. {"__gt__", prim::kPrimScalarGt}, // P.scalar_gt
  66. {"__le__", prim::kPrimScalarLe}, // P.scalar_le
  67. {"__ge__", prim::kPrimScalarGe}, // P.scalar_ge
  68. {"__bool__", std::string("int_bool")}, // C.int_bool
  69. {"__ms_to_array__", prim::kPrimScalarToArray}, // P.scalar_to_array
  70. }},
  71. {kNumberTypeUInt,
  72. {
  73. {"__add__", prim::kPrimScalarAdd}, // P.scalar_add,
  74. {"__sub__", prim::kPrimScalarSub}, // P.scalar_sub,
  75. {"__mul__", prim::kPrimScalarMul}, // P.scalar_mul,
  76. {"__floordiv__", prim::kPrimScalarDiv}, // P.scalar_div,
  77. {"__truediv__", std::string("int_truediv")}, // C.int_truediv
  78. {"__mod__", prim::kPrimScalarMod}, // P.scalar_mod,
  79. {"__pow__", prim::kPrimScalarPow}, // P.scalar_pow,
  80. {"__floor__", prim::kPrimIdentity}, // P.identity,
  81. {"__trunc__", prim::kPrimIdentity}, // P.identity,
  82. {"__pos__", prim::kPrimScalarUadd}, // P.scalar_uadd,
  83. {"__neg__", prim::kPrimScalarUsub}, // P.scalar_usub,
  84. {"__eq__", prim::kPrimScalarEq}, // P.scalar_eq,
  85. {"__ne__", prim::kPrimScalarNe}, // P.scalar_ne,
  86. {"__lt__", prim::kPrimScalarLt}, // P.scalar_lt,
  87. {"__gt__", prim::kPrimScalarGt}, // P.scalar_gt,
  88. {"__le__", prim::kPrimScalarLe}, // P.scalar_le,
  89. {"__ge__", prim::kPrimScalarGe}, // P.scalar_ge,
  90. {"__bool__", std::string("int_bool")}, // C.int_bool
  91. {"__ms_to_array__", prim::kPrimScalarToArray}, // P.scalar_to_array,
  92. }},
  93. {kNumberTypeFloat,
  94. {
  95. {"__add__", prim::kPrimScalarAdd}, // P.scalar_add,
  96. {"__sub__", prim::kPrimScalarSub}, // P.scalar_sub,
  97. {"__mul__", prim::kPrimScalarMul}, // P.scalar_mul,
  98. {"__floordiv__", std::string("float_floordiv")}, // C.float_floordiv
  99. {"__truediv__", prim::kPrimScalarDiv}, // P.scalar_div,
  100. {"__mod__", prim::kPrimScalarMod}, // P.scalar_mod,
  101. {"__pow__", prim::kPrimScalarPow}, // P.scalar_pow,
  102. {"__floor__", prim::kPrimScalarFloor}, // P.scalar_floor,
  103. {"__trunc__", prim::kPrimScalarTrunc}, // P.scalar_trunc,
  104. {"__pos__", prim::kPrimScalarUadd}, // P.scalar_uadd,
  105. {"__neg__", prim::kPrimScalarUsub}, // P.scalar_usub,
  106. {"__eq__", prim::kPrimScalarEq}, // P.scalar_eq,
  107. {"__ne__", prim::kPrimScalarNe}, // P.scalar_ne,
  108. {"__lt__", prim::kPrimScalarLt}, // P.scalar_lt,
  109. {"__gt__", prim::kPrimScalarGt}, // P.scalar_gt,
  110. {"__le__", prim::kPrimScalarLe}, // P.scalar_le,
  111. {"__ge__", prim::kPrimScalarGe}, // P.scalar_ge,
  112. {"__bool__", std::string("float_bool")}, // C.float_bool
  113. {"__ms_to_array__", prim::kPrimScalarToArray}, // P.scalar_to_array,
  114. }},
  115. {kObjectTypeTuple,
  116. {
  117. {"__len__", prim::kPrimTupleLen}, // P.tuple_len,
  118. {"__getitem__", prim::kPrimTupleGetItem}, // P.tuple_getitem,
  119. {"__setitem__", prim::kPrimTupleSetItem}, // P.tuple_setitem,
  120. {"__ms_iter__", prim::kPrimIdentity}, // P.identity,
  121. {"__ms_next__", std::string("tuple_next")}, // C.tuple_next,
  122. {"__ms_hasnext__", std::string("tuple_hasnext")}, // C.tuple_hasnext
  123. {"__bool__", std::string("tuple_bool")} // C.tuple_bool
  124. }},
  125. {kObjectTypeList,
  126. {
  127. {"__len__", prim::kPrimListLen}, // P.list_len,
  128. {"__getitem__", prim::kPrimListGetItem}, // P.list_getitem,
  129. {"__setitem__", prim::kPrimListSetItem}, // P.list_setitem,
  130. {"__ms_iter__", prim::kPrimIdentity}, // P.identity
  131. {"__ms_next__", std::string("list_next")}, // C.list_next
  132. {"append", std::string("list_append")}, // C.list_next
  133. {"__bool__", std::string("list_bool")}, // C.list_bool
  134. {"__ms_hasnext__", std::string("list_hasnext")},
  135. }},
  136. {kObjectTypeDictionary,
  137. {
  138. {"__len__", prim::kPrimDictLen}, // P.dict_len
  139. {"__getitem__", prim::kPrimDictGetItem}, // P.dict_getitem
  140. {"__setitem__", prim::kPrimDictSetItem}, // P.dict_setitem,
  141. {"__bool__", std::string("dict_bool")} // C.dict_bool
  142. }},
  143. {kObjectTypeTensorType,
  144. {
  145. {"all", std::string("all_")}, // C.reduce_all
  146. {"any", std::string("any_")}, // C.reduce_any
  147. {"__add__", std::string("add")}, // C.add
  148. {"__sub__", std::string("sub")}, // C.sub
  149. {"__mul__", std::string("mul")}, // C.mul
  150. {"__truediv__", std::string("truediv")}, // C.truediv
  151. {"__floordiv__", std::string("floordiv")}, // C.floordiv
  152. {"__mod__", std::string("mod")}, // C.mod
  153. {"__pow__", std::string("pow_")}, // C.pow
  154. {"__floor__", std::string("array_floor")}, // C.array_floor
  155. {"__trunc__", std::string("array_trunc")}, // C.array_trunc
  156. {"__pos__", std::string("array_uadd")}, // C.array_uadd
  157. {"__neg__", std::string("array_usub")}, // C.array_usub
  158. {"__eq__", std::string("eq")}, // C.eq
  159. {"__ne__", std::string("ne")}, // C.ne
  160. {"__lt__", std::string("lt")}, // C.lt
  161. {"__gt__", std::string("gt")}, // C.gt
  162. {"__le__", std::string("le")}, // C.le
  163. {"__ge__", std::string("ge")}, // C.ge
  164. {"__matmul__", prim::kPrimDot}, // P.dot,
  165. {"__len__", prim::kPrimArrayLen}, // P.array_len,
  166. {"__getitem__", prim::kPrimArrayGetItem}, // P.array_getitem,
  167. {"__setitem__", prim::kPrimArraySetItem}, // P.array_setitem,
  168. {"__ms_iter__", std::string("array_iter")}, // C.array_iter
  169. {"__ms_to_array__", prim::kPrimIdentity}, // P.identity,
  170. {"item", prim::kPrimArrayToScalar}, // P.array_to_scalar,
  171. {"transpose", std::string("transpose")}, // P.transpose
  172. {"__bool__", std::string("tensor_bool")}, // C.tensor_bool
  173. }},
  174. {kObjectTypeJTagged, {}},
  175. {kObjectTypeSymbolicKeyType, {}},
  176. {kObjectTypeEnvType, {}}};
  177. return method_map;
  178. }
  179. BuiltInTypeMap &GetAttrMap() {
  180. static BuiltInTypeMap attr_map = {
  181. {kObjectTypeTensorType,
  182. {
  183. {"shape", std::string("shape_")}, // C.shape_
  184. {"dtype", std::string("dtype_")}, // C.dtype_
  185. }},
  186. {kObjectTypeRowTensorType,
  187. {
  188. {"values", prim::kPrimRowTensorGetValues}, // F.row_tensor_get_values
  189. {"indices", prim::kPrimRowTensorGetIndices}, // F.row_tensor_get_indices
  190. {"dense_shape", prim::kPrimRowTensorGetDenseShape}, // F.row_tensor_get_dense_shape
  191. }},
  192. {kObjectTypeSparseTensorType,
  193. {
  194. {"values", prim::kPrimSparseTensorGetValues}, // F.sparse_tensor_get_values
  195. {"indices", prim::kPrimSparseTensorGetIndices}, // F.sparse_tensor_get_indices
  196. {"dense_shape", prim::kPrimSparseTensorGetDenseShape}, // F.sparse_tensor_get_dense_shape
  197. }},
  198. };
  199. return attr_map;
  200. }
  201. Resource::Resource(const py::object &obj)
  202. : engine_(std::make_shared<abstract::AnalysisEngine>(abstract::GetPrimEvaluatorConstructors(), manager_)),
  203. input_(obj),
  204. is_cleaned_(false) {}
  205. Resource::~Resource() {
  206. MS_LOG(DEBUG) << "Resource clear";
  207. std::unordered_map<std::string, Any>().swap(results_);
  208. // If exit normally, these global variables will be cleaned
  209. // in Resource::Clean call by MsPipeline::Compile, but if exit with MS_LOGEXCEPTION,
  210. // these global variables may not being cleaned, it may
  211. // cause segmentfault when free python object inside these global variables
  212. // after python interpreter got freed, so these global variables
  213. // are cleaned here.
  214. // So if exit normally, these global variable will be cleaned twice,
  215. // care be taken to prevent double free in the following functions.
  216. if (!is_cleaned_) {
  217. try {
  218. Clean();
  219. } catch (const std::exception &e) {
  220. MS_LOG(ERROR) << "Exception when cleaning resource. Error info " << e.what();
  221. } catch (...) {
  222. MS_LOG(ERROR) << "Exception when cleaning resource.";
  223. }
  224. }
  225. }
  226. Any GetMethodOrAttr(const string &name, const TypeId &type_id, const BuiltInTypeMap &method_map) {
  227. auto type_method_map = method_map.find(static_cast<int>(type_id));
  228. if (type_method_map == method_map.end()) {
  229. return Any();
  230. }
  231. auto method = type_method_map->second.find(name);
  232. if (method == type_method_map->second.end()) {
  233. return Any();
  234. }
  235. return method->second;
  236. }
  237. bool Resource::IsTypeInBuiltInMap(const TypeId &type) {
  238. TypeId type_id = NormalizeTypeId(type);
  239. const BuiltInTypeMap &method_map = GetMethodMap();
  240. auto iter = method_map.find(static_cast<int>(type_id));
  241. if (iter == method_map.end()) {
  242. const BuiltInTypeMap &attr_map = GetAttrMap();
  243. iter = attr_map.find(static_cast<int>(type_id));
  244. if (iter == attr_map.end()) {
  245. return false;
  246. }
  247. }
  248. return true;
  249. }
  250. Any Resource::GetMethodPtr(const TypeId &type, const std::string &name) {
  251. TypeId type_id = NormalizeTypeId(type);
  252. const BuiltInTypeMap &method_map = GetMethodMap();
  253. return GetMethodOrAttr(name, type_id, method_map);
  254. }
  255. Any Resource::GetAttrPtr(const TypeId &type, const std::string &name) {
  256. TypeId type_id = NormalizeTypeId(type);
  257. const BuiltInTypeMap &attr_map = GetAttrMap();
  258. return GetMethodOrAttr(name, type_id, attr_map);
  259. }
  260. void Resource::Clean() {
  261. // AbstractTensor->elements() will be saved in AbstractBasePtrList
  262. args_spec_.clear();
  263. input_ = py::none();
  264. // Context with AbstractBasePtrList may be saved in GraphEvaluator
  265. // some Evaluator like ResolveEvaluator may save Python object in cache,
  266. // it should be cleaned before Python Interpreter destructed.
  267. MS_EXCEPTION_IF_NULL(engine_);
  268. engine_->ClearEvaluatorCache();
  269. // clean static variable to prevent from crash. As static variable is released after
  270. // Python threads is released.
  271. parse::data_converter::ClearObjectCache();
  272. parse::Parser::CleanParserResource();
  273. parse::CleanDataClassToClassMap();
  274. trace::ClearTraceStack();
  275. is_cleaned_ = true;
  276. }
  277. } // namespace pipeline
  278. } // namespace mindspore