attribute.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  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. # TODO: define functions to get tensor attributes
  15. import numpy as np
  16. import paddle
  17. from paddle import _C_ops
  18. from ..base.data_feeder import check_type, check_variable_and_dtype
  19. from ..base.framework import in_dynamic_or_pir_mode, use_pir_api
  20. from ..common_ops_import import Variable
  21. from ..framework import LayerHelper, core
  22. from .creation import _complex_to_real_dtype, assign
  23. __all__ = []
  24. def rank(input):
  25. """
  26. Returns the number of dimensions for a tensor, which is a 0-D int32 Tensor.
  27. Args:
  28. input (Tensor): The input Tensor with shape of :math:`[N_1, N_2, ..., N_k]`, the data type is arbitrary.
  29. Returns:
  30. Tensor, the output data type is int32.: The 0-D tensor with the dimensions of the input Tensor.
  31. Examples:
  32. .. code-block:: python
  33. >>> import paddle
  34. >>> input = paddle.rand((3, 100, 100))
  35. >>> rank = paddle.rank(input)
  36. >>> print(rank.numpy())
  37. 3
  38. """
  39. check_type(input, 'input', (Variable, paddle.pir.Value), 'input')
  40. ndims = len(input.shape)
  41. out = assign(np.array(ndims, 'int32'))
  42. return out
  43. def shape(input):
  44. """
  45. Get the shape of the input.
  46. .. code-block:: text
  47. Case1:
  48. Given N-D Tensor:
  49. input = [ [1, 2, 3, 4], [5, 6, 7, 8] ]
  50. Then:
  51. input.shape = [2, 4]
  52. Case2:
  53. Given SelectedRows:
  54. input.rows = [0, 4, 19]
  55. input.height = 20
  56. input.value = [ [1, 2], [3, 4], [5, 6] ] # inner tensor
  57. Then:
  58. input.shape = [3, 2]
  59. Args:
  60. input (Variable): The input can be N-D Tensor or SelectedRows with data type bool, bfloat16, float16, float32, float64, int32, int64.
  61. If input variable is type of SelectedRows, returns the shape of it's inner tensor.
  62. Returns:
  63. Variable (Tensor): The shape of the input variable.
  64. Examples:
  65. .. code-block:: python
  66. >>> import numpy as np
  67. >>> import paddle
  68. >>> paddle.enable_static()
  69. >>> inputs = paddle.static.data(name="x", shape=[3, 100, 100], dtype="float32")
  70. >>> output = paddle.shape(inputs)
  71. >>> exe = paddle.static.Executor(paddle.CPUPlace())
  72. >>> exe.run(paddle.static.default_startup_program())
  73. >>> img = np.ones((3, 100, 100)).astype(np.float32)
  74. >>> res = exe.run(paddle.static.default_main_program(), feed={'x':img}, fetch_list=[output])
  75. >>> print(res)
  76. [array([ 3, 100, 100], dtype=int32)]
  77. """
  78. if in_dynamic_or_pir_mode():
  79. out = _C_ops.shape(input)
  80. out.stop_gradient = True
  81. return out
  82. else:
  83. check_variable_and_dtype(
  84. input,
  85. 'input',
  86. [
  87. 'bool',
  88. 'uint16',
  89. 'float16',
  90. 'float32',
  91. 'float64',
  92. 'int32',
  93. 'int64',
  94. 'complex64',
  95. 'complex128',
  96. 'uint16',
  97. ],
  98. 'shape',
  99. )
  100. helper = LayerHelper('shape', **locals())
  101. out = helper.create_variable_for_type_inference(dtype='int32')
  102. helper.append_op(
  103. type='shape',
  104. inputs={'Input': input},
  105. outputs={'Out': out},
  106. stop_gradient=True,
  107. )
  108. out.stop_gradient = True
  109. return out
  110. def is_complex(x):
  111. """Return whether x is a tensor of complex data type(complex64 or complex128).
  112. Args:
  113. x (Tensor): The input tensor.
  114. Returns:
  115. bool: True if the data type of the input is complex data type, otherwise false.
  116. Examples:
  117. .. code-block:: python
  118. >>> import paddle
  119. >>> x = paddle.to_tensor([1 + 2j, 3 + 4j])
  120. >>> print(paddle.is_complex(x))
  121. True
  122. >>> x = paddle.to_tensor([1.1, 1.2])
  123. >>> print(paddle.is_complex(x))
  124. False
  125. >>> x = paddle.to_tensor([1, 2, 3])
  126. >>> print(paddle.is_complex(x))
  127. False
  128. """
  129. if not isinstance(
  130. x, (paddle.Tensor, paddle.static.Variable, paddle.pir.Value)
  131. ):
  132. raise TypeError(f"Expected Tensor, but received type of x: {type(x)}")
  133. dtype = x.dtype
  134. is_complex_dtype = (
  135. dtype == core.VarDesc.VarType.COMPLEX64
  136. or dtype == core.VarDesc.VarType.COMPLEX128
  137. or dtype == core.DataType.COMPLEX64
  138. or dtype == core.DataType.COMPLEX128
  139. )
  140. return is_complex_dtype
  141. def is_floating_point(x):
  142. """
  143. Returns whether the dtype of `x` is one of paddle.float64, paddle.float32, paddle.float16, and paddle.bfloat16.
  144. Args:
  145. x (Tensor): The input tensor.
  146. Returns:
  147. bool: True if the dtype of `x` is floating type, otherwise false.
  148. Examples:
  149. .. code-block:: python
  150. >>> import paddle
  151. >>> x = paddle.arange(1., 5., dtype='float32')
  152. >>> y = paddle.arange(1, 5, dtype='int32')
  153. >>> print(paddle.is_floating_point(x))
  154. True
  155. >>> print(paddle.is_floating_point(y))
  156. False
  157. """
  158. if not isinstance(
  159. x, (paddle.Tensor, paddle.static.Variable, paddle.pir.Value)
  160. ):
  161. raise TypeError(f"Expected Tensor, but received type of x: {type(x)}")
  162. dtype = x.dtype
  163. is_fp_dtype = (
  164. dtype == core.VarDesc.VarType.FP32
  165. or dtype == core.VarDesc.VarType.FP64
  166. or dtype == core.VarDesc.VarType.FP16
  167. or dtype == core.VarDesc.VarType.BF16
  168. or dtype == core.DataType.FLOAT32
  169. or dtype == core.DataType.FLOAT64
  170. or dtype == core.DataType.FLOAT16
  171. or dtype == core.DataType.BFLOAT16
  172. )
  173. return is_fp_dtype
  174. def is_integer(x):
  175. """Return whether x is a tensor of integral data type.
  176. Args:
  177. x (Tensor): The input tensor.
  178. Returns:
  179. bool: True if the data type of the input is integer data type, otherwise false.
  180. Examples:
  181. .. code-block:: python
  182. >>> import paddle
  183. >>> x = paddle.to_tensor([1 + 2j, 3 + 4j])
  184. >>> print(paddle.is_integer(x))
  185. False
  186. >>> x = paddle.to_tensor([1.1, 1.2])
  187. >>> print(paddle.is_integer(x))
  188. False
  189. >>> x = paddle.to_tensor([1, 2, 3])
  190. >>> print(paddle.is_integer(x))
  191. True
  192. """
  193. if not isinstance(
  194. x, (paddle.Tensor, paddle.static.Variable, paddle.pir.Value)
  195. ):
  196. raise TypeError(f"Expected Tensor, but received type of x: {type(x)}")
  197. dtype = x.dtype
  198. is_int_dtype = False
  199. if not use_pir_api():
  200. is_int_dtype = (
  201. dtype == core.VarDesc.VarType.UINT8
  202. or dtype == core.VarDesc.VarType.INT8
  203. or dtype == core.VarDesc.VarType.INT16
  204. or dtype == core.VarDesc.VarType.INT32
  205. or dtype == core.VarDesc.VarType.INT64
  206. )
  207. else:
  208. is_int_dtype = (
  209. dtype == core.DataType.UINT8
  210. or dtype == core.DataType.INT8
  211. or dtype == core.DataType.INT16
  212. or dtype == core.DataType.INT32
  213. or dtype == core.DataType.INT64
  214. )
  215. return is_int_dtype
  216. def real(x, name=None):
  217. """
  218. Returns a new Tensor containing real values of the input Tensor.
  219. Args:
  220. x (Tensor): the input Tensor, its data type could be complex64 or complex128.
  221. name (str, optional): The default value is None. Normally there is no need for
  222. user to set this property. For more information, please refer to :ref:`api_guide_Name` .
  223. Returns:
  224. Tensor: a Tensor containing real values of the input Tensor.
  225. Examples:
  226. .. code-block:: python
  227. >>> import paddle
  228. >>> x = paddle.to_tensor(
  229. ... [[1 + 6j, 2 + 5j, 3 + 4j], [4 + 3j, 5 + 2j, 6 + 1j]])
  230. >>> print(x)
  231. Tensor(shape=[2, 3], dtype=complex64, place=Place(cpu), stop_gradient=True,
  232. [[(1+6j), (2+5j), (3+4j)],
  233. [(4+3j), (5+2j), (6+1j)]])
  234. >>> real_res = paddle.real(x)
  235. >>> print(real_res)
  236. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  237. [[1., 2., 3.],
  238. [4., 5., 6.]])
  239. >>> real_t = x.real()
  240. >>> print(real_t)
  241. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  242. [[1., 2., 3.],
  243. [4., 5., 6.]])
  244. """
  245. if in_dynamic_or_pir_mode():
  246. return _C_ops.real(x)
  247. else:
  248. check_variable_and_dtype(x, 'x', ['complex64', 'complex128'], 'real')
  249. helper = LayerHelper('real', **locals())
  250. out = helper.create_variable_for_type_inference(
  251. dtype=_complex_to_real_dtype(helper.input_dtype())
  252. )
  253. helper.append_op(type='real', inputs={'X': x}, outputs={'Out': out})
  254. return out
  255. def imag(x, name=None):
  256. """
  257. Returns a new tensor containing imaginary values of input tensor.
  258. Args:
  259. x (Tensor): the input tensor, its data type could be complex64 or complex128.
  260. name (str, optional): The default value is None. Normally there is no need for
  261. user to set this property. For more information, please refer to :ref:`api_guide_Name` .
  262. Returns:
  263. Tensor: a tensor containing imaginary values of the input tensor.
  264. Examples:
  265. .. code-block:: python
  266. >>> import paddle
  267. >>> x = paddle.to_tensor(
  268. ... [[1 + 6j, 2 + 5j, 3 + 4j], [4 + 3j, 5 + 2j, 6 + 1j]])
  269. >>> print(x)
  270. Tensor(shape=[2, 3], dtype=complex64, place=Place(cpu), stop_gradient=True,
  271. [[(1+6j), (2+5j), (3+4j)],
  272. [(4+3j), (5+2j), (6+1j)]])
  273. >>> imag_res = paddle.imag(x)
  274. >>> print(imag_res)
  275. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  276. [[6., 5., 4.],
  277. [3., 2., 1.]])
  278. >>> imag_t = x.imag()
  279. >>> print(imag_t)
  280. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  281. [[6., 5., 4.],
  282. [3., 2., 1.]])
  283. """
  284. if in_dynamic_or_pir_mode():
  285. return _C_ops.imag(x)
  286. else:
  287. check_variable_and_dtype(x, 'x', ['complex64', 'complex128'], 'imag')
  288. helper = LayerHelper('imag', **locals())
  289. out = helper.create_variable_for_type_inference(
  290. dtype=_complex_to_real_dtype(helper.input_dtype())
  291. )
  292. helper.append_op(type='imag', inputs={'X': x}, outputs={'Out': out})
  293. return out