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

5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """primitive"""
  16. import inspect
  17. import copy
  18. from mindspore.common.api import _wrap_func
  19. from mindspore import context
  20. from .._c_expression import Primitive_, real_run_op, prim_type
  21. from . import signature as sig
  22. class Primitive(Primitive_):
  23. """
  24. Primitive is the base class of primitives in python.
  25. Args:
  26. name (str): Name for the current Primitive.
  27. Examples:
  28. >>> add = Primitive('add')
  29. >>>
  30. >>> # or work with prim_attr_register:
  31. >>> # init a Primitive class with attr1 and attr2
  32. >>> class Add(Primitive):
  33. ... @prim_attr_register
  34. ... def __init__(self, attr1, attr2):
  35. ... # check attr1 and attr2 or do some initializations
  36. >>> # init a Primitive obj with attr1=1 and attr2=2
  37. >>> add = Add(attr1=1, attr2=2)
  38. """
  39. _repr_ignore_list = ['input_names', 'output_names']
  40. def __init__(self, name):
  41. self.name = name
  42. self.attrs = {}
  43. self.init_attrs = {"name": name}
  44. self._update_parameter = False
  45. Primitive_.__init__(self, name, self)
  46. if hasattr(self.__class__, '__mindspore_signature__'):
  47. out = self._fill_signature(self.__class__.__mindspore_signature__)
  48. self.set_signatures(out)
  49. def _fill_signature(self, signatures):
  50. """fills signature."""
  51. signatures_new = []
  52. for signature in signatures:
  53. if isinstance(signature, sig.Signature):
  54. signatures_new.append(signature)
  55. elif isinstance(signature, sig.sig_dtype):
  56. signatures_new.append(sig.make_sig(dtype=signature))
  57. else:
  58. if len(signature) < 3:
  59. raise ValueError(f"[Internal Error]Signature for one parameter len must > 3, but {signature}")
  60. signatures_new.append(sig.make_sig(*signature))
  61. return tuple(signatures_new)
  62. def _clone(self):
  63. """
  64. Deeply clones the primitive object.
  65. Calls the __init__() method with the same arguments. This method is called in parser if the
  66. flag self.__setattr_flag__ is True.
  67. """
  68. cloned = copy.deepcopy(self)
  69. init_params = inspect.getfullargspec(cloned.__init__.decorated_func).args[1:]
  70. init_args = {}
  71. for name in init_params:
  72. value = self.attrs[name]
  73. init_args[name] = value
  74. # __init__ should be called to construct cpp object.
  75. cloned.__init__(**init_args)
  76. for name in self.attrs:
  77. value = self.attrs[name]
  78. cloned.add_prim_attr(name, value)
  79. if hasattr(self, 'instance_name'):
  80. cloned.set_prim_instance_name(self.instance_name)
  81. return cloned
  82. def add_prim_attr(self, name, value):
  83. """
  84. Adds primitive attribute.
  85. Args:
  86. name (str): Attribute Name.
  87. value (Any): Attribute value.
  88. """
  89. self.__dict__[name] = value
  90. self.attrs[name] = value
  91. self.add_attr(name, value)
  92. return self
  93. def set_stage(self, stage):
  94. """
  95. Add stage id to primitive attribute.
  96. Note:
  97. It is valid only in semi auto parallel.
  98. In other parallel modes, please set it to be 0.
  99. Args:
  100. stage (int): The stage id for the current operation
  101. """
  102. self.add_prim_attr("stage", stage)
  103. return self
  104. def shard(self, strategy):
  105. """
  106. Add strategies to primitive attribute.
  107. Note:
  108. It is valid only in semi auto parallel or auto parallel mode.
  109. In other parallel modes, strategies set here will be ignored.
  110. Args:
  111. strategy (tuple): Strategy describes the distributed parallel mode of the current primitive.
  112. """
  113. self.add_prim_attr("strategy", strategy)
  114. return self
  115. def set_prim_instance_name(self, instance_name):
  116. """
  117. Set instance name to primitive operator.
  118. Note:
  119. It will be called by default when user defines primitive operator.
  120. Args:
  121. instance_name (str): Instance name of primitive operator set by user.
  122. """
  123. self.set_instance_name(instance_name)
  124. self.instance_name = instance_name
  125. return self
  126. def __getattr__(self, item):
  127. if item == 'infer_dynamic_shape':
  128. return None
  129. if item in super().get_attr_dict():
  130. return super().get_attr_dict()[item]
  131. if item in self.attrs:
  132. return self.attrs[item]
  133. raise AttributeError(item)
  134. def check_elim(self, *args):
  135. """
  136. Check if certain inputs should go to the backend. Subclass in need should override this method.
  137. Args:
  138. args(Primitive args): Same as arguments of current Primitive.
  139. Returns:
  140. A tuple consisting of two elements. The first element indicates whether we should filter out current
  141. arguments; the seconde element is the output if we need to filter out the arguments.
  142. """
  143. return (False, None)
  144. def __call__(self, *args):
  145. should_elim, output = self.check_elim(*args)
  146. if should_elim:
  147. return output
  148. return _run_op(self, self.name, args)
  149. def __getstate__(self):
  150. return self.__dict__
  151. def __setstate__(self, d):
  152. self.__dict__.update(d)
  153. def __deepcopy__(self, memo):
  154. return type(self)(**self.init_attrs)
  155. def __repr__(self):
  156. attr = ', '.join([f'{k}={self.attrs[k]}' for k in self.attrs if not k in Primitive._repr_ignore_list])
  157. info_str = f'Prim[{self.name}]'
  158. if attr:
  159. info_str += f'<{attr}>'
  160. return info_str
  161. def init_prim_io_names(self, inputs, outputs):
  162. """
  163. Initializes the name of inputs and outpus of Tensor or attributes.
  164. Args:
  165. inputs (list[str]): list of inputs names.
  166. outputs (list[str]): list of outputs names.
  167. """
  168. # for checking para names with kernel implementation
  169. self.add_prim_attr("input_names", inputs)
  170. # for checking output number with kernel implementation
  171. self.add_prim_attr("output_names", outputs)
  172. @property
  173. def update_parameter(self):
  174. """ Whether the primitive will update the value of parameter."""
  175. return self._update_parameter
  176. class PrimitiveWithCheck(Primitive):
  177. """
  178. PrimitiveWithCheck is the base class of primitives in python defines functions for checking operator input arguments
  179. but used the infer method registed in c++ source codes.
  180. There are three methods can be overide to define the check logic of the primitive: __check__(), check_shape(),
  181. check_dtype(). If __check__() is defined in primitive, the __check__() has highest priority to be called.
  182. If __check__() is not defined, check_shape() and check_dtype() can be defined to describe the check logic of
  183. the shape and type. Method infer_value() can also be defined (such as PrimitiveWithInfer) for constant propagation.
  184. Args:
  185. name (str): Name of the current Primitive.
  186. Examples:
  187. >>> # init a Primitive class with check
  188. >>> class Flatten(PrimitiveWithCheck):
  189. >>> @prim_attr_register
  190. >>> def __init__(self):
  191. >>> pass
  192. >>> def check_shape(self, input_x):
  193. >>> validator.check_int(len(input_x), 1, Rel.GE, 'input_x rank', self.name)
  194. >>>
  195. >>> def check_dtype(self, input_x):
  196. >>> validator.check_subclass("input_x", input_x, mstype.tensor, self.name)
  197. >>>
  198. >>> # init a Primitive obj
  199. >>> add = Flatten()
  200. """
  201. def __init__(self, name):
  202. Primitive.__init__(self, name)
  203. self.set_prim_type(prim_type.py_infer_check)
  204. def _clone(self):
  205. """
  206. Deeply clones the primitive object.
  207. Calls the __init__() method with the same arguments. This method is called in parser if the
  208. flag self.__setattr_flag__ is True.
  209. """
  210. cloned_prim = Primitive._clone(self)
  211. return cloned_prim
  212. def check_shape(self, *args):
  213. """
  214. Check shapes of input args.
  215. Note:
  216. The shape of scalar is an empty tuple.
  217. Args:
  218. args (tuple(int)): shapes of input tensors.
  219. Return:
  220. None.
  221. """
  222. return None
  223. def check_dtype(self, *args):
  224. """
  225. Check data types of input args.
  226. Args:
  227. args (:class:`mindspore.dtype`): data type of inputs.
  228. Return:
  229. None.
  230. """
  231. return None
  232. def __check__(self, *args):
  233. """Check shape, type, and value at the same time by using dictionary as arguments."""
  234. tracks = ['dtype', 'shape']
  235. for track in tracks:
  236. fn = getattr(self, 'check_' + track)
  237. fn(*(x[track] for x in args))
  238. class PrimitiveWithInfer(Primitive):
  239. """
  240. PrimitiveWithInfer is the base class of primitives in python and defines functions for tracking inference in python.
  241. There are four method can be overide to define the infer logic of the primitive: __infer__(), infer_shape(),
  242. infer_dtype(), and infer_value(). If __infer__() is defined in primitive, the __infer__() has highest priority
  243. to be called. If __infer__() is not defined, infer_shape() and infer_dtype() can be defined to describe the infer
  244. logic of the shape and type. The infer_value() is used for constant propagation.
  245. Args:
  246. name (str): Name of the current Primitive.
  247. Examples:
  248. >>> # init a Primitive class with infer
  249. >>> class Add(PrimitiveWithInfer):
  250. >>> @prim_attr_register
  251. >>> def __init__(self):
  252. >>> pass
  253. >>>
  254. >>> def infer_shape(self, x, y):
  255. >>> return x # output shape same as first input 'x'
  256. >>>
  257. >>> def infer_dtype(self, x, y):
  258. >>> return x # output type same as first input 'x'
  259. >>>
  260. >>> # init a Primitive obj
  261. >>> add = Add()
  262. """
  263. def __init__(self, name):
  264. Primitive.__init__(self, name)
  265. self.set_prim_type(prim_type.py_infer_shape)
  266. def _clone(self):
  267. """
  268. Deeply clones the primitive object.
  269. Calls the __init__() method with the same arguments. This method is called in parser if the
  270. flag self.__setattr_flag__ is True.
  271. """
  272. cloned_prim = Primitive._clone(self)
  273. return cloned_prim
  274. def infer_shape(self, *args):
  275. """
  276. Infer output shape based on input shape.
  277. Note:
  278. The shape of scalar is an empty tuple.
  279. Args:
  280. args (tuple(int)): shapes of input tensors.
  281. Return:
  282. `tuple(int)`, shapes of output tensors.
  283. """
  284. return None
  285. def infer_dtype(self, *args):
  286. """
  287. Infer output dtype based on input dtype.
  288. Args:
  289. args (:class:`mindspore.dtype`): data type of inputs.
  290. Return:
  291. :class:`mindspore.dtype`, data type of outputs.
  292. """
  293. return None
  294. def infer_value(self, *args):
  295. """
  296. Infer output value based on input value at compile time.
  297. Args:
  298. args (Any): value of inputs.
  299. Return:
  300. Value of outputs. Return `None`, the value can not be inferred at compile time in this case.
  301. """
  302. return None
  303. def __infer__(self, *args):
  304. """Infer shape, type, and value at the same time by using dictionary as arguments."""
  305. is_graph_mode = context.get_context("mode") == context.GRAPH_MODE
  306. fn_infer_dynamic_shape = getattr(self, 'infer_dynamic_shape', None)
  307. if is_graph_mode and fn_infer_dynamic_shape is not None:
  308. out = fn_infer_dynamic_shape(*args)
  309. tracks = ['dtype', 'value']
  310. for track in tracks:
  311. fn = getattr(self, 'infer_' + track)
  312. # fn may return None
  313. out[track] = fn(*(x[track] for x in args))
  314. return out
  315. tracks = ['dtype', 'shape', 'value']
  316. out = {}
  317. for track in tracks:
  318. fn = getattr(self, 'infer_' + track)
  319. # fn may return None
  320. out[track] = fn(*(x[track] for x in args))
  321. # in non-graph_mode, it is not necessary to infer min/max shape
  322. if not is_graph_mode:
  323. return out
  324. # output does not contain dynamic shape, no need to calculate min/max shape
  325. def has_dynamic_shape(shp):
  326. if isinstance(shp, int):
  327. return shp < 0
  328. if isinstance(shp, (list, tuple)):
  329. return any(has_dynamic_shape(e) for e in shp)
  330. return False
  331. if not has_dynamic_shape(out['shape']):
  332. return out
  333. # calculate min/max shape for output
  334. def get_specified_shape(elems, attr):
  335. has_specified_shape = False
  336. ret_vals = []
  337. for elem in elems:
  338. if attr in elem:
  339. has_specified_shape = True
  340. ret_vals.append(elem[attr])
  341. else:
  342. ret_vals.append(elem['shape'])
  343. return has_specified_shape, tuple(ret_vals)
  344. has_min_shape, min_shapes = get_specified_shape(args, 'min_shape')
  345. has_max_shape, max_shapes = get_specified_shape(args, 'max_shape')
  346. if not (has_min_shape or has_max_shape):
  347. return out
  348. if has_min_shape and has_max_shape:
  349. fn_infer_shape = getattr(self, 'infer_shape')
  350. out['min_shape'] = fn_infer_shape(*min_shapes)
  351. out['max_shape'] = fn_infer_shape(*max_shapes)
  352. return out
  353. raise ValueError('Input args has invalid dynamic shape, args info: {args}')
  354. def prim_attr_register(fn):
  355. """
  356. Primitive attributes register.
  357. Register the decorator of the built-in operator primitive '__init__'.
  358. The function will add all the parameters of '__init__' as operator attributes.
  359. Args:
  360. fn (function): __init__ function of primitive.
  361. Returns:
  362. function, original function.
  363. """
  364. def deco(self, *args, **kwargs):
  365. if isinstance(self, PrimitiveWithInfer):
  366. PrimitiveWithInfer.__init__(self, self.__class__.__name__)
  367. elif isinstance(self, PrimitiveWithCheck):
  368. PrimitiveWithCheck.__init__(self, self.__class__.__name__)
  369. else:
  370. Primitive.__init__(self, self.__class__.__name__)
  371. bound_args = inspect.signature(fn).bind(self, *args, **kwargs)
  372. bound_args.apply_defaults()
  373. arguments = bound_args.arguments
  374. del arguments['self']
  375. del self.init_attrs['name']
  376. for name in arguments:
  377. value = arguments[name]
  378. self.add_prim_attr(name, value)
  379. self.init_attrs[name] = value
  380. fn(self, *args, **kwargs)
  381. deco.decorated_func = fn
  382. return deco
  383. def constexpr(fn=None, get_instance=True, name=None):
  384. """
  385. Creates a PrimitiveWithInfer operator that can infer the value at compile time. We can use it to define a function
  386. to compute constant value using the constants in the constructor.
  387. Args:
  388. fn (function): A `fn` use as the infer_value of the output operator.
  389. get_instance (bool): If true, return the instance of operator, otherwise return the operator class.
  390. name (str): Defines the operator name. If `name` is None, use the function name as op name.
  391. Examples:
  392. >>> a = (1, 2)
  393. >>> # make an operator to calculate tuple len
  394. >>> @constexpr
  395. >>> def tuple_len(x):
  396. ... return len(x)
  397. >>> assert tuple_len(a) == 2
  398. ...
  399. >>> # make a operator class to calculate tuple len
  400. >>> @constexpr(get_instance=False, name="TupleLen")
  401. >>> def tuple_len_class(x):
  402. ... return len(x)
  403. >>> assert tuple_len_class()(a) == 2
  404. """
  405. def deco(fn):
  406. class CompileOp(PrimitiveWithInfer):
  407. def __init__(self):
  408. op_name = name if name else fn.__name__
  409. PrimitiveWithInfer.__init__(self, op_name)
  410. self.set_const_prim(True)
  411. def infer_value(self, *args):
  412. return fn(*args)
  413. if get_instance:
  414. return CompileOp()
  415. return CompileOp
  416. if fn is not None:
  417. return deco(fn)
  418. return deco
  419. @_wrap_func
  420. def _run_op(obj, op_name, args):
  421. """Single op execution function supported by ge in PyNative mode."""
  422. output = real_run_op(obj, op_name, args)
  423. if not output:
  424. raise RuntimeError("Pynative run op %s failed!" % op_name)
  425. if len(output) == 1:
  426. output = output[0]
  427. return output