search.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  1. # Copyright (c) 2022 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 searching & indexing functions of a tensor
  15. import numpy as np
  16. import paddle
  17. from paddle import _C_ops
  18. from paddle.common_ops_import import VarDesc, Variable
  19. from paddle.utils.inplace_utils import inplace_apis_in_dygraph_only
  20. from ..base.data_feeder import check_dtype, check_variable_and_dtype
  21. from ..framework import (
  22. LayerHelper,
  23. convert_np_dtype_to_dtype_,
  24. core,
  25. in_dynamic_mode,
  26. in_dynamic_or_pir_mode,
  27. )
  28. # from ..base.layers import has_inf #DEFINE_ALIAS
  29. # from ..base.layers import has_nan #DEFINE_ALIAS
  30. __all__ = []
  31. def argsort(x, axis=-1, descending=False, stable=False, name=None):
  32. """
  33. Sorts the input along the given axis, and returns the corresponding index tensor for the sorted output values. The default sort algorithm is ascending, if you want the sort algorithm to be descending, you must set the :attr:`descending` as True.
  34. Args:
  35. x (Tensor): An input N-D Tensor with type bfloat16, float16, float32, float64, int16,
  36. int32, int64, uint8.
  37. axis (int, optional): Axis to compute indices along. The effective range
  38. is [-R, R), where R is Rank(x). when axis<0, it works the same way
  39. as axis+R. Default is -1.
  40. descending (bool, optional) : Descending is a flag, if set to true,
  41. algorithm will sort by descending order, else sort by
  42. ascending order. Default is false.
  43. stable (bool, optional): Whether to use stable sorting algorithm or not.
  44. When using stable sorting algorithm, the order of equivalent elements
  45. will be preserved. Default is False.
  46. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  47. Returns:
  48. Tensor: sorted indices(with the same shape as ``x``
  49. and with data type int64).
  50. Examples:
  51. .. code-block:: python
  52. >>> import paddle
  53. >>> x = paddle.to_tensor([[[5,8,9,5],
  54. ... [0,0,1,7],
  55. ... [6,9,2,4]],
  56. ... [[5,2,4,2],
  57. ... [4,7,7,9],
  58. ... [1,7,0,6]]],
  59. ... dtype='float32')
  60. >>> out1 = paddle.argsort(x, axis=-1)
  61. >>> out2 = paddle.argsort(x, axis=0)
  62. >>> out3 = paddle.argsort(x, axis=1)
  63. >>> print(out1)
  64. Tensor(shape=[2, 3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  65. [[[0, 3, 1, 2],
  66. [0, 1, 2, 3],
  67. [2, 3, 0, 1]],
  68. [[1, 3, 2, 0],
  69. [0, 1, 2, 3],
  70. [2, 0, 3, 1]]])
  71. >>> print(out2)
  72. Tensor(shape=[2, 3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  73. [[[0, 1, 1, 1],
  74. [0, 0, 0, 0],
  75. [1, 1, 1, 0]],
  76. [[1, 0, 0, 0],
  77. [1, 1, 1, 1],
  78. [0, 0, 0, 1]]])
  79. >>> print(out3)
  80. Tensor(shape=[2, 3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  81. [[[1, 1, 1, 2],
  82. [0, 0, 2, 0],
  83. [2, 2, 0, 1]],
  84. [[2, 0, 2, 0],
  85. [1, 1, 0, 2],
  86. [0, 2, 1, 1]]])
  87. >>> x = paddle.to_tensor([1, 0]*40, dtype='float32')
  88. >>> out1 = paddle.argsort(x, stable=False)
  89. >>> out2 = paddle.argsort(x, stable=True)
  90. >>> print(out1)
  91. Tensor(shape=[80], dtype=int64, place=Place(cpu), stop_gradient=True,
  92. [55, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 1 , 57, 59, 61,
  93. 63, 65, 67, 69, 71, 73, 75, 77, 79, 17, 11, 13, 25, 7 , 3 , 27, 23, 19,
  94. 15, 5 , 21, 9 , 10, 64, 62, 68, 60, 58, 8 , 66, 14, 6 , 70, 72, 4 , 74,
  95. 76, 2 , 78, 0 , 20, 28, 26, 30, 32, 24, 34, 36, 22, 38, 40, 12, 42, 44,
  96. 18, 46, 48, 16, 50, 52, 54, 56])
  97. >>> print(out2)
  98. Tensor(shape=[80], dtype=int64, place=Place(cpu), stop_gradient=True,
  99. [1 , 3 , 5 , 7 , 9 , 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35,
  100. 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71,
  101. 73, 75, 77, 79, 0 , 2 , 4 , 6 , 8 , 10, 12, 14, 16, 18, 20, 22, 24, 26,
  102. 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62,
  103. 64, 66, 68, 70, 72, 74, 76, 78])
  104. """
  105. if in_dynamic_or_pir_mode():
  106. _, ids = _C_ops.argsort(x, axis, descending, stable)
  107. return ids
  108. else:
  109. check_variable_and_dtype(
  110. x,
  111. 'x',
  112. [
  113. 'uint16',
  114. 'float16',
  115. 'float32',
  116. 'float64',
  117. 'int16',
  118. 'int32',
  119. 'int64',
  120. 'uint8',
  121. ],
  122. 'argsort',
  123. )
  124. helper = LayerHelper("argsort", **locals())
  125. out = helper.create_variable_for_type_inference(
  126. dtype=x.dtype, stop_gradient=True
  127. )
  128. ids = helper.create_variable_for_type_inference(
  129. VarDesc.VarType.INT64, stop_gradient=True
  130. )
  131. helper.append_op(
  132. type='argsort',
  133. inputs={'X': x},
  134. outputs={'Out': out, 'Indices': ids},
  135. attrs={'axis': axis, 'descending': descending, 'stable': stable},
  136. )
  137. return ids
  138. def argmax(x, axis=None, keepdim=False, dtype="int64", name=None):
  139. """
  140. Computes the indices of the max elements of the input tensor's
  141. element along the provided axis.
  142. Args:
  143. x (Tensor): An input N-D Tensor with type float16, float32, float64, int16,
  144. int32, int64, uint8.
  145. axis (int, optional): Axis to compute indices along. The effective range
  146. is [-R, R), where R is x.ndim. when axis < 0, it works the same way
  147. as axis + R. Default is None, the input `x` will be into the flatten tensor, and selecting the min value index.
  148. keepdim (bool, optional): Whether to keep the given axis in output. If it is True, the dimensions will be same as input x and with size one in the axis. Otherwise the output dimensions is one fewer than x since the axis is squeezed. Default is False.
  149. dtype (str|np.dtype, optional): Data type of the output tensor which can
  150. be int32, int64. The default value is ``int64`` , and it will
  151. return the int64 indices.
  152. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  153. Returns:
  154. Tensor, return the tensor of int32 if set :attr:`dtype` is int32, otherwise return the tensor of int64.
  155. Examples:
  156. .. code-block:: python
  157. >>> import paddle
  158. >>> x = paddle.to_tensor([[5,8,9,5],
  159. ... [0,0,1,7],
  160. ... [6,9,2,4]])
  161. >>> out1 = paddle.argmax(x)
  162. >>> print(out1.numpy())
  163. 2
  164. >>> out2 = paddle.argmax(x, axis=0)
  165. >>> print(out2.numpy())
  166. [2 2 0 1]
  167. >>> out3 = paddle.argmax(x, axis=-1)
  168. >>> print(out3.numpy())
  169. [2 3 1]
  170. >>> out4 = paddle.argmax(x, axis=0, keepdim=True)
  171. >>> print(out4.numpy())
  172. [[2 2 0 1]]
  173. """
  174. if axis is not None and not isinstance(
  175. axis, (int, Variable, paddle.pir.Value)
  176. ):
  177. raise TypeError(
  178. "The type of 'axis' must be int or Tensor or None in argmax, but received %s."
  179. % (type(axis))
  180. )
  181. if dtype is None:
  182. raise ValueError(
  183. "the value of 'dtype' in argmax could not be None, but received None"
  184. )
  185. var_dtype = convert_np_dtype_to_dtype_(dtype)
  186. flatten = False
  187. if axis is None:
  188. flatten = True
  189. axis = 0
  190. if in_dynamic_or_pir_mode():
  191. return _C_ops.argmax(x, axis, keepdim, flatten, var_dtype)
  192. else:
  193. helper = LayerHelper("argmax", **locals())
  194. check_variable_and_dtype(
  195. x,
  196. 'x',
  197. [
  198. 'uint16',
  199. 'float16',
  200. 'float32',
  201. 'float64',
  202. 'int16',
  203. 'int32',
  204. 'int64',
  205. 'uint8',
  206. ],
  207. 'paddle.argmax',
  208. )
  209. check_dtype(var_dtype, 'dtype', ['int32', 'int64'], 'argmin')
  210. attrs = {}
  211. out = helper.create_variable_for_type_inference(var_dtype)
  212. attrs['keepdims'] = keepdim
  213. attrs['axis'] = axis
  214. attrs['flatten'] = flatten
  215. attrs['dtype'] = var_dtype
  216. helper.append_op(
  217. type='arg_max', inputs={'X': x}, outputs={'Out': [out]}, attrs=attrs
  218. )
  219. out.stop_gradient = True
  220. return out
  221. def argmin(x, axis=None, keepdim=False, dtype="int64", name=None):
  222. """
  223. Computes the indices of the min elements of the input tensor's
  224. element along the provided axis.
  225. Args:
  226. x (Tensor): An input N-D Tensor with type float16, float32, float64, int16,
  227. int32, int64, uint8.
  228. axis (int, optional): Axis to compute indices along. The effective range
  229. is [-R, R), where R is x.ndim. when axis < 0, it works the same way
  230. as axis + R. Default is None, the input `x` will be into the flatten tensor, and selecting the min value index.
  231. keepdim (bool, optional): Whether to keep the given axis in output. If it is True, the dimensions will be same as input x and with size one in the axis. Otherwise the output dimensions is one fewer than x since the axis is squeezed. Default is False.
  232. dtype (str, optional): Data type of the output tensor which can
  233. be int32, int64. The default value is 'int64', and it will
  234. return the int64 indices.
  235. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  236. Returns:
  237. Tensor, return the tensor of `int32` if set :attr:`dtype` is `int32`, otherwise return the tensor of `int64`.
  238. Examples:
  239. .. code-block:: python
  240. >>> import paddle
  241. >>> x = paddle.to_tensor([[5,8,9,5],
  242. ... [0,0,1,7],
  243. ... [6,9,2,4]])
  244. >>> out1 = paddle.argmin(x)
  245. >>> print(out1.numpy())
  246. 4
  247. >>> out2 = paddle.argmin(x, axis=0)
  248. >>> print(out2.numpy())
  249. [1 1 1 2]
  250. >>> out3 = paddle.argmin(x, axis=-1)
  251. >>> print(out3.numpy())
  252. [0 0 2]
  253. >>> out4 = paddle.argmin(x, axis=0, keepdim=True)
  254. >>> print(out4.numpy())
  255. [[1 1 1 2]]
  256. """
  257. if axis is not None and not isinstance(
  258. axis, (int, Variable, paddle.pir.Value)
  259. ):
  260. raise TypeError(
  261. "The type of 'axis' must be int or Tensor or None in argmin, but received %s."
  262. % (type(axis))
  263. )
  264. if dtype is None:
  265. raise ValueError(
  266. "the value of 'dtype' in argmin could not be None, but received None"
  267. )
  268. var_dtype = convert_np_dtype_to_dtype_(dtype)
  269. flatten = False
  270. if axis is None:
  271. flatten = True
  272. axis = 0
  273. if in_dynamic_or_pir_mode():
  274. return _C_ops.argmin(x, axis, keepdim, flatten, var_dtype)
  275. else:
  276. helper = LayerHelper("argmin", **locals())
  277. check_variable_and_dtype(
  278. x,
  279. 'x',
  280. [
  281. 'uint16',
  282. 'float16',
  283. 'float32',
  284. 'float64',
  285. 'int16',
  286. 'int32',
  287. 'int64',
  288. 'uint8',
  289. ],
  290. 'paddle.argmin',
  291. )
  292. check_dtype(var_dtype, 'dtype', ['int32', 'int64'], 'argmin')
  293. out = helper.create_variable_for_type_inference(var_dtype)
  294. attrs = {}
  295. attrs['keepdims'] = keepdim
  296. attrs['axis'] = axis
  297. attrs['flatten'] = flatten
  298. attrs['dtype'] = var_dtype
  299. helper.append_op(
  300. type='arg_min', inputs={'X': x}, outputs={'Out': [out]}, attrs=attrs
  301. )
  302. out.stop_gradient = True
  303. return out
  304. def index_select(x, index, axis=0, name=None):
  305. """
  306. Returns a new tensor which indexes the ``input`` tensor along dimension ``axis`` using
  307. the entries in ``index`` which is a Tensor. The returned tensor has the same number
  308. of dimensions as the original ``x`` tensor. The dim-th dimension has the same
  309. size as the length of ``index``; other dimensions have the same size as in the ``x`` tensor.
  310. Args:
  311. x (Tensor): The input Tensor to be operated. The data of ``x`` can be one of float16, float32, float64, int32, int64, complex64 and complex128.
  312. index (Tensor): The 1-D Tensor containing the indices to index. The data type of ``index`` must be int32 or int64.
  313. axis (int, optional): The dimension in which we index. Default: if None, the ``axis`` is 0.
  314. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  315. Returns:
  316. Tensor: A Tensor with same data type as ``x``.
  317. Examples:
  318. .. code-block:: python
  319. >>> import paddle
  320. >>> x = paddle.to_tensor([[1.0, 2.0, 3.0, 4.0],
  321. ... [5.0, 6.0, 7.0, 8.0],
  322. ... [9.0, 10.0, 11.0, 12.0]])
  323. >>> index = paddle.to_tensor([0, 1, 1], dtype='int32')
  324. >>> out_z1 = paddle.index_select(x=x, index=index)
  325. >>> print(out_z1.numpy())
  326. [[1. 2. 3. 4.]
  327. [5. 6. 7. 8.]
  328. [5. 6. 7. 8.]]
  329. >>> out_z2 = paddle.index_select(x=x, index=index, axis=1)
  330. >>> print(out_z2.numpy())
  331. [[ 1. 2. 2.]
  332. [ 5. 6. 6.]
  333. [ 9. 10. 10.]]
  334. """
  335. if in_dynamic_or_pir_mode():
  336. return _C_ops.index_select(x, index, axis)
  337. else:
  338. helper = LayerHelper("index_select", **locals())
  339. check_variable_and_dtype(
  340. x,
  341. 'x',
  342. [
  343. 'uint16',
  344. 'float16',
  345. 'float32',
  346. 'float64',
  347. 'int32',
  348. 'int64',
  349. 'complex64',
  350. 'complex128',
  351. ],
  352. 'paddle.tensor.search.index_select',
  353. )
  354. check_variable_and_dtype(
  355. index,
  356. 'index',
  357. ['int32', 'int64'],
  358. 'paddle.tensor.search.index_select',
  359. )
  360. out = helper.create_variable_for_type_inference(x.dtype)
  361. helper.append_op(
  362. type='index_select',
  363. inputs={'X': x, 'Index': index},
  364. outputs={'Out': out},
  365. attrs={'dim': axis},
  366. )
  367. return out
  368. def nonzero(x, as_tuple=False):
  369. """
  370. Return a tensor containing the indices of all non-zero elements of the `input`
  371. tensor. If as_tuple is True, return a tuple of 1-D tensors, one for each dimension
  372. in `input`, each containing the indices (in that dimension) of all non-zero elements
  373. of `input`. Given a n-Dimensional `input` tensor with shape [x_1, x_2, ..., x_n], If
  374. as_tuple is False, we can get a output tensor with shape [z, n], where `z` is the
  375. number of all non-zero elements in the `input` tensor. If as_tuple is True, we can get
  376. a 1-D tensor tuple of length `n`, and the shape of each 1-D tensor is [z, 1].
  377. Args:
  378. x (Tensor): The input tensor variable.
  379. as_tuple (bool, optional): Return type, Tensor or tuple of Tensor.
  380. Returns:
  381. Tensor. The data type is int64.
  382. Examples:
  383. .. code-block:: python
  384. >>> import paddle
  385. >>> x1 = paddle.to_tensor([[1.0, 0.0, 0.0],
  386. ... [0.0, 2.0, 0.0],
  387. ... [0.0, 0.0, 3.0]])
  388. >>> x2 = paddle.to_tensor([0.0, 1.0, 0.0, 3.0])
  389. >>> out_z1 = paddle.nonzero(x1)
  390. >>> print(out_z1)
  391. Tensor(shape=[3, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
  392. [[0, 0],
  393. [1, 1],
  394. [2, 2]])
  395. >>> out_z1_tuple = paddle.nonzero(x1, as_tuple=True)
  396. >>> for out in out_z1_tuple:
  397. ... print(out)
  398. Tensor(shape=[3, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
  399. [[0],
  400. [1],
  401. [2]])
  402. Tensor(shape=[3, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
  403. [[0],
  404. [1],
  405. [2]])
  406. >>> out_z2 = paddle.nonzero(x2)
  407. >>> print(out_z2)
  408. Tensor(shape=[2, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
  409. [[1],
  410. [3]])
  411. >>> out_z2_tuple = paddle.nonzero(x2, as_tuple=True)
  412. >>> for out in out_z2_tuple:
  413. ... print(out)
  414. Tensor(shape=[2, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
  415. [[1],
  416. [3]])
  417. """
  418. list_out = []
  419. shape = x.shape
  420. rank = len(shape)
  421. if in_dynamic_or_pir_mode():
  422. outs = _C_ops.nonzero(x)
  423. else:
  424. check_variable_and_dtype(
  425. x,
  426. 'x',
  427. [
  428. 'int16',
  429. 'int32',
  430. 'int64',
  431. 'uint16',
  432. 'float16',
  433. 'float32',
  434. 'float64',
  435. 'bool',
  436. ],
  437. 'where_index',
  438. )
  439. helper = LayerHelper("where_index", **locals())
  440. outs = helper.create_variable_for_type_inference(
  441. dtype=core.VarDesc.VarType.INT64
  442. )
  443. helper.append_op(
  444. type='where_index', inputs={'Condition': x}, outputs={'Out': [outs]}
  445. )
  446. if not as_tuple:
  447. return outs
  448. elif rank == 1:
  449. return (outs,)
  450. else:
  451. for i in range(rank):
  452. list_out.append(
  453. paddle.slice(outs, axes=[1], starts=[i], ends=[i + 1])
  454. )
  455. return tuple(list_out)
  456. def sort(x, axis=-1, descending=False, stable=False, name=None):
  457. """
  458. Sorts the input along the given axis, and returns the sorted output tensor. The default sort algorithm is ascending, if you want the sort algorithm to be descending, you must set the :attr:`descending` as True.
  459. Args:
  460. x (Tensor): An input N-D Tensor with type float32, float64, int16,
  461. int32, int64, uint8.
  462. axis (int, optional): Axis to compute indices along. The effective range
  463. is [-R, R), where R is Rank(x). when axis<0, it works the same way
  464. as axis+R. Default is -1.
  465. descending (bool, optional) : Descending is a flag, if set to true,
  466. algorithm will sort by descending order, else sort by
  467. ascending order. Default is false.
  468. stable (bool, optional): Whether to use stable sorting algorithm or not.
  469. When using stable sorting algorithm, the order of equivalent elements
  470. will be preserved. Default is False.
  471. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  472. Returns:
  473. Tensor: sorted tensor(with the same shape and data type as ``x``).
  474. Examples:
  475. .. code-block:: python
  476. >>> import paddle
  477. >>> x = paddle.to_tensor([[[5,8,9,5],
  478. ... [0,0,1,7],
  479. ... [6,9,2,4]],
  480. ... [[5,2,4,2],
  481. ... [4,7,7,9],
  482. ... [1,7,0,6]]],
  483. ... dtype='float32')
  484. >>> out1 = paddle.sort(x=x, axis=-1)
  485. >>> out2 = paddle.sort(x=x, axis=0)
  486. >>> out3 = paddle.sort(x=x, axis=1)
  487. >>> print(out1.numpy())
  488. [[[5. 5. 8. 9.]
  489. [0. 0. 1. 7.]
  490. [2. 4. 6. 9.]]
  491. [[2. 2. 4. 5.]
  492. [4. 7. 7. 9.]
  493. [0. 1. 6. 7.]]]
  494. >>> print(out2.numpy())
  495. [[[5. 2. 4. 2.]
  496. [0. 0. 1. 7.]
  497. [1. 7. 0. 4.]]
  498. [[5. 8. 9. 5.]
  499. [4. 7. 7. 9.]
  500. [6. 9. 2. 6.]]]
  501. >>> print(out3.numpy())
  502. [[[0. 0. 1. 4.]
  503. [5. 8. 2. 5.]
  504. [6. 9. 9. 7.]]
  505. [[1. 2. 0. 2.]
  506. [4. 7. 4. 6.]
  507. [5. 7. 7. 9.]]]
  508. """
  509. if in_dynamic_or_pir_mode():
  510. outs, _ = _C_ops.argsort(x, axis, descending, stable)
  511. return outs
  512. else:
  513. helper = LayerHelper("sort", **locals())
  514. out = helper.create_variable_for_type_inference(
  515. dtype=x.dtype, stop_gradient=False
  516. )
  517. ids = helper.create_variable_for_type_inference(
  518. VarDesc.VarType.INT64, stop_gradient=True
  519. )
  520. helper.append_op(
  521. type='argsort',
  522. inputs={'X': x},
  523. outputs={'Out': out, 'Indices': ids},
  524. attrs={'axis': axis, 'descending': descending, 'stable': stable},
  525. )
  526. return out
  527. def mode(x, axis=-1, keepdim=False, name=None):
  528. """
  529. Used to find values and indices of the modes at the optional axis.
  530. Args:
  531. x (Tensor): Tensor, an input N-D Tensor with type float32, float64, int32, int64.
  532. axis (int, optional): Axis to compute indices along. The effective range
  533. is [-R, R), where R is x.ndim. when axis < 0, it works the same way
  534. as axis + R. Default is -1.
  535. keepdim (bool, optional): Whether to keep the given axis in output. If it is True, the dimensions will be same as input x and with size one in the axis. Otherwise the output dimensions is one fewer than x since the axis is squeezed. Default is False.
  536. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  537. Returns:
  538. tuple (Tensor), return the values and indices. The value data type is the same as the input `x`. The indices data type is int64.
  539. Examples:
  540. .. code-block:: python
  541. >>> import paddle
  542. >>> tensor = paddle.to_tensor([[[1,2,2],[2,3,3]],[[0,5,5],[9,9,0]]], dtype=paddle.float32)
  543. >>> res = paddle.mode(tensor, 2)
  544. >>> print(res)
  545. (Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  546. [[2., 3.],
  547. [5., 9.]]), Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
  548. [[2, 2],
  549. [2, 1]]))
  550. """
  551. if in_dynamic_or_pir_mode():
  552. return _C_ops.mode(x, axis, keepdim)
  553. else:
  554. helper = LayerHelper("mode", **locals())
  555. inputs = {"X": [x]}
  556. attrs = {}
  557. attrs['axis'] = axis
  558. attrs['keepdim'] = keepdim
  559. values = helper.create_variable_for_type_inference(dtype=x.dtype)
  560. indices = helper.create_variable_for_type_inference(dtype="int64")
  561. helper.append_op(
  562. type="mode",
  563. inputs=inputs,
  564. outputs={"Out": [values], "Indices": [indices]},
  565. attrs=attrs,
  566. )
  567. indices.stop_gradient = True
  568. return values, indices
  569. def where(condition, x=None, y=None, name=None):
  570. r"""
  571. Return a Tensor of elements selected from either :attr:`x` or :attr:`y` according to corresponding elements of :attr:`condition`. Concretely,
  572. .. math::
  573. out_i =
  574. \begin{cases}
  575. x_i, & \text{if} \ condition_i \ \text{is} \ True \\
  576. y_i, & \text{if} \ condition_i \ \text{is} \ False \\
  577. \end{cases}.
  578. Notes:
  579. ``numpy.where(condition)`` is identical to ``paddle.nonzero(condition, as_tuple=True)``, please refer to :ref:`api_paddle_nonzero`.
  580. Args:
  581. condition (Tensor): The condition to choose x or y. When True (nonzero), yield x, otherwise yield y.
  582. x (Tensor|scalar, optional): A Tensor or scalar to choose when the condition is True with data type of bfloat16, float16, float32, float64, int32 or int64. Either both or neither of x and y should be given.
  583. y (Tensor|scalar, optional): A Tensor or scalar to choose when the condition is False with data type of bfloat16, float16, float32, float64, int32 or int64. Either both or neither of x and y should be given.
  584. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  585. Returns:
  586. Tensor: A Tensor with the same shape as :attr:`condition` and same data type as :attr:`x` and :attr:`y`.
  587. Examples:
  588. .. code-block:: python
  589. >>> import paddle
  590. >>> x = paddle.to_tensor([0.9383, 0.1983, 3.2, 1.2])
  591. >>> y = paddle.to_tensor([1.0, 1.0, 1.0, 1.0])
  592. >>> out = paddle.where(x>1, x, y)
  593. >>> print(out)
  594. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  595. [1. , 1. , 3.20000005, 1.20000005])
  596. >>> out = paddle.where(x>1)
  597. >>> print(out)
  598. (Tensor(shape=[2, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
  599. [[2],
  600. [3]]),)
  601. """
  602. if np.isscalar(x):
  603. x = paddle.full([1], x, np.array([x]).dtype.name)
  604. if np.isscalar(y):
  605. y = paddle.full([1], y, np.array([y]).dtype.name)
  606. if x is None and y is None:
  607. return nonzero(condition, as_tuple=True)
  608. if x is None or y is None:
  609. raise ValueError("either both or neither of x and y should be given")
  610. condition_shape = list(condition.shape)
  611. x_shape = list(x.shape)
  612. y_shape = list(y.shape)
  613. if x_shape == y_shape and condition_shape == x_shape:
  614. broadcast_condition = condition
  615. broadcast_x = x
  616. broadcast_y = y
  617. else:
  618. zeros_like_x = paddle.zeros_like(x)
  619. zeros_like_y = paddle.zeros_like(y)
  620. zeros_like_condition = paddle.zeros_like(condition)
  621. zeros_like_condition = paddle.cast(zeros_like_condition, x.dtype)
  622. cast_cond = paddle.cast(condition, x.dtype)
  623. broadcast_zeros = paddle.add(zeros_like_x, zeros_like_y)
  624. broadcast_zeros = paddle.add(broadcast_zeros, zeros_like_condition)
  625. broadcast_x = paddle.add(x, broadcast_zeros)
  626. broadcast_y = paddle.add(y, broadcast_zeros)
  627. broadcast_condition = paddle.add(cast_cond, broadcast_zeros)
  628. broadcast_condition = paddle.cast(broadcast_condition, 'bool')
  629. if in_dynamic_or_pir_mode():
  630. return _C_ops.where(broadcast_condition, broadcast_x, broadcast_y)
  631. else:
  632. check_variable_and_dtype(condition, 'condition', ['bool'], 'where')
  633. check_variable_and_dtype(
  634. x,
  635. 'x',
  636. ['uint16', 'float16', 'float32', 'float64', 'int32', 'int64'],
  637. 'where',
  638. )
  639. check_variable_and_dtype(
  640. y,
  641. 'y',
  642. ['uint16', 'float16', 'float32', 'float64', 'int32', 'int64'],
  643. 'where',
  644. )
  645. helper = LayerHelper("where", **locals())
  646. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  647. helper.append_op(
  648. type='where',
  649. inputs={
  650. 'Condition': broadcast_condition,
  651. 'X': broadcast_x,
  652. 'Y': broadcast_y,
  653. },
  654. outputs={'Out': [out]},
  655. )
  656. return out
  657. @inplace_apis_in_dygraph_only
  658. def where_(condition, x=None, y=None, name=None):
  659. r"""
  660. Inplace version of ``where`` API, the output Tensor will be inplaced with input ``x``.
  661. Please refer to :ref:`api_paddle_where`.
  662. """
  663. if np.isscalar(x) or np.isscalar(y):
  664. raise ValueError("either both or neither of x and y should be given")
  665. if x is None or y is None:
  666. raise ValueError("either both or neither of x and y should be given")
  667. condition_shape = list(condition.shape)
  668. x_shape = list(x.shape)
  669. y_shape = list(y.shape)
  670. if x_shape == y_shape and condition_shape == x_shape:
  671. broadcast_condition = condition
  672. broadcast_x = x
  673. broadcast_y = y
  674. else:
  675. zeros_like_x = paddle.zeros_like(x)
  676. zeros_like_y = paddle.zeros_like(y)
  677. zeros_like_condition = paddle.zeros_like(condition)
  678. zeros_like_condition = paddle.cast(zeros_like_condition, x.dtype)
  679. cast_cond = paddle.cast(condition, x.dtype)
  680. broadcast_zeros = paddle.add(zeros_like_x, zeros_like_y)
  681. broadcast_zeros = paddle.add(broadcast_zeros, zeros_like_condition)
  682. broadcast_x = x.add_(broadcast_zeros)
  683. broadcast_y = paddle.add(y, broadcast_zeros)
  684. broadcast_condition = paddle.add(cast_cond, broadcast_zeros)
  685. broadcast_condition = paddle.cast(broadcast_condition, 'bool')
  686. if in_dynamic_mode():
  687. return _C_ops.where_(broadcast_condition, broadcast_x, broadcast_y)
  688. def index_sample(x, index):
  689. """
  690. **IndexSample Layer**
  691. IndexSample OP returns the element of the specified location of X,
  692. and the location is specified by Index.
  693. .. code-block:: text
  694. Given:
  695. X = [[1, 2, 3, 4, 5],
  696. [6, 7, 8, 9, 10]]
  697. Index = [[0, 1, 3],
  698. [0, 2, 4]]
  699. Then:
  700. Out = [[1, 2, 4],
  701. [6, 8, 10]]
  702. Args:
  703. x (Tensor): The source input tensor with 2-D shape. Supported data type is
  704. int32, int64, bfloat16, float16, float32, float64, complex64, complex128.
  705. index (Tensor): The index input tensor with 2-D shape, first dimension should be same with X.
  706. Data type is int32 or int64.
  707. Returns:
  708. output (Tensor): The output is a tensor with the same shape as index.
  709. Examples:
  710. .. code-block:: python
  711. >>> import paddle
  712. >>> x = paddle.to_tensor([[1.0, 2.0, 3.0, 4.0],
  713. ... [5.0, 6.0, 7.0, 8.0],
  714. ... [9.0, 10.0, 11.0, 12.0]], dtype='float32')
  715. >>> index = paddle.to_tensor([[0, 1, 2],
  716. ... [1, 2, 3],
  717. ... [0, 0, 0]], dtype='int32')
  718. >>> target = paddle.to_tensor([[100, 200, 300, 400],
  719. ... [500, 600, 700, 800],
  720. ... [900, 1000, 1100, 1200]], dtype='int32')
  721. >>> out_z1 = paddle.index_sample(x, index)
  722. >>> print(out_z1.numpy())
  723. [[1. 2. 3.]
  724. [6. 7. 8.]
  725. [9. 9. 9.]]
  726. >>> # Use the index of the maximum value by topk op
  727. >>> # get the value of the element of the corresponding index in other tensors
  728. >>> top_value, top_index = paddle.topk(x, k=2)
  729. >>> out_z2 = paddle.index_sample(target, top_index)
  730. >>> print(top_value.numpy())
  731. [[ 4. 3.]
  732. [ 8. 7.]
  733. [12. 11.]]
  734. >>> print(top_index.numpy())
  735. [[3 2]
  736. [3 2]
  737. [3 2]]
  738. >>> print(out_z2.numpy())
  739. [[ 400 300]
  740. [ 800 700]
  741. [1200 1100]]
  742. """
  743. if in_dynamic_or_pir_mode():
  744. return _C_ops.index_sample(x, index)
  745. else:
  746. helper = LayerHelper("index_sample", **locals())
  747. check_variable_and_dtype(
  748. x,
  749. 'x',
  750. [
  751. 'uint16',
  752. 'float16',
  753. 'float32',
  754. 'float64',
  755. 'int32',
  756. 'int64',
  757. 'complex64',
  758. 'complex128',
  759. ],
  760. 'paddle.tensor.search.index_sample',
  761. )
  762. check_variable_and_dtype(
  763. index,
  764. 'index',
  765. ['int32', 'int64'],
  766. 'paddle.tensor.search.index_sample',
  767. )
  768. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  769. helper.append_op(
  770. type='index_sample',
  771. inputs={'X': x, 'Index': index},
  772. outputs={'Out': out},
  773. )
  774. return out
  775. def masked_select(x, mask, name=None):
  776. """
  777. Returns a new 1-D tensor which indexes the input tensor according to the ``mask``
  778. which is a tensor with data type of bool.
  779. Args:
  780. x (Tensor): The input Tensor, the data type can be int32, int64, uint16, float16, float32, float64.
  781. mask (Tensor): The Tensor containing the binary mask to index with, it's data type is bool.
  782. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  783. Returns:
  784. A 1-D Tensor which is the same data type as ``x``.
  785. Examples:
  786. .. code-block:: python
  787. >>> import paddle
  788. >>> x = paddle.to_tensor([[1.0, 2.0, 3.0, 4.0],
  789. ... [5.0, 6.0, 7.0, 8.0],
  790. ... [9.0, 10.0, 11.0, 12.0]])
  791. >>> mask = paddle.to_tensor([[True, False, False, False],
  792. ... [True, True, False, False],
  793. ... [True, False, False, False]])
  794. >>> out = paddle.masked_select(x, mask)
  795. >>> print(out.numpy())
  796. [1. 5. 6. 9.]
  797. """
  798. if in_dynamic_or_pir_mode():
  799. return _C_ops.masked_select(x, mask)
  800. else:
  801. check_variable_and_dtype(
  802. x,
  803. 'x',
  804. ['float16', 'float32', 'float64', 'int32', 'int64', 'uint16'],
  805. 'paddle.tensor.search.mask_select',
  806. )
  807. check_variable_and_dtype(
  808. mask, 'mask', ['bool'], 'paddle.tensor.search.masked_select'
  809. )
  810. helper = LayerHelper("masked_select", **locals())
  811. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  812. helper.append_op(
  813. type='masked_select',
  814. inputs={'X': x, 'Mask': mask},
  815. outputs={'Y': out},
  816. )
  817. return out
  818. def topk(x, k, axis=None, largest=True, sorted=True, name=None):
  819. """
  820. Return values and indices of the k largest or smallest at the optional axis.
  821. If the input is a 1-D Tensor, finds the k largest or smallest values and indices.
  822. If the input is a Tensor with higher rank, this operator computes the top k values and indices along the :attr:`axis`.
  823. Args:
  824. x (Tensor): Tensor, an input N-D Tensor with type float32, float64, int32, int64.
  825. k (int, Tensor): The number of top elements to look for along the axis.
  826. axis (int, optional): Axis to compute indices along. The effective range
  827. is [-R, R), where R is x.ndim. when axis < 0, it works the same way
  828. as axis + R. Default is -1.
  829. largest (bool, optional) : largest is a flag, if set to true,
  830. algorithm will sort by descending order, otherwise sort by
  831. ascending order. Default is True.
  832. sorted (bool, optional): controls whether to return the elements in sorted order, default value is True. In gpu device, it always return the sorted value.
  833. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  834. Returns:
  835. tuple(Tensor), return the values and indices. The value data type is the same as the input `x`. The indices data type is int64.
  836. Examples:
  837. .. code-block:: python
  838. >>> import paddle
  839. >>> data_1 = paddle.to_tensor([1, 4, 5, 7])
  840. >>> value_1, indices_1 = paddle.topk(data_1, k=1)
  841. >>> print(value_1)
  842. Tensor(shape=[1], dtype=int64, place=Place(cpu), stop_gradient=True,
  843. [7])
  844. >>> print(indices_1)
  845. Tensor(shape=[1], dtype=int64, place=Place(cpu), stop_gradient=True,
  846. [3])
  847. >>> data_2 = paddle.to_tensor([[1, 4, 5, 7], [2, 6, 2, 5]])
  848. >>> value_2, indices_2 = paddle.topk(data_2, k=1)
  849. >>> print(value_2)
  850. Tensor(shape=[2, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
  851. [[7],
  852. [6]])
  853. >>> print(indices_2)
  854. Tensor(shape=[2, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
  855. [[3],
  856. [1]])
  857. >>> value_3, indices_3 = paddle.topk(data_2, k=1, axis=-1)
  858. >>> print(value_3)
  859. Tensor(shape=[2, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
  860. [[7],
  861. [6]])
  862. >>> print(indices_3)
  863. Tensor(shape=[2, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
  864. [[3],
  865. [1]])
  866. >>> value_4, indices_4 = paddle.topk(data_2, k=1, axis=0)
  867. >>> print(value_4)
  868. Tensor(shape=[1, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  869. [[2, 6, 5, 7]])
  870. >>> print(indices_4)
  871. Tensor(shape=[1, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  872. [[1, 1, 0, 0]])
  873. """
  874. if in_dynamic_or_pir_mode():
  875. if axis is None:
  876. axis = -1
  877. out, indices = _C_ops.topk(x, k, axis, largest, sorted)
  878. return out, indices
  879. else:
  880. helper = LayerHelper("top_k_v2", **locals())
  881. inputs = {"X": [x]}
  882. attrs = {}
  883. if isinstance(k, Variable):
  884. inputs['K'] = [k]
  885. else:
  886. attrs = {'k': k}
  887. attrs['largest'] = largest
  888. attrs['sorted'] = sorted
  889. if axis is not None:
  890. attrs['axis'] = axis
  891. values = helper.create_variable_for_type_inference(dtype=x.dtype)
  892. indices = helper.create_variable_for_type_inference(dtype="int64")
  893. helper.append_op(
  894. type="top_k_v2",
  895. inputs=inputs,
  896. outputs={"Out": [values], "Indices": [indices]},
  897. attrs=attrs,
  898. )
  899. indices.stop_gradient = True
  900. return values, indices
  901. def bucketize(x, sorted_sequence, out_int32=False, right=False, name=None):
  902. """
  903. This API is used to find the index of the corresponding 1D tensor `sorted_sequence` in the innermost dimension based on the given `x`.
  904. Args:
  905. x (Tensor): An input N-D tensor value with type int32, int64, float32, float64.
  906. sorted_sequence (Tensor): An input 1-D tensor with type int32, int64, float32, float64. The value of the tensor monotonically increases in the innermost dimension.
  907. out_int32 (bool, optional): Data type of the output tensor which can be int32, int64. The default value is False, and it indicates that the output data type is int64.
  908. right (bool, optional): Find the upper or lower bounds of the sorted_sequence range in the innermost dimension based on the given `x`. If the value of the sorted_sequence is nan or inf, return the size of the innermost dimension.
  909. The default value is False and it shows the lower bounds.
  910. name (str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`.
  911. Returns:
  912. Tensor (the same sizes of the `x`), return the tensor of int32 if set :attr:`out_int32` is True, otherwise return the tensor of int64.
  913. Examples:
  914. .. code-block:: python
  915. >>> import paddle
  916. >>> sorted_sequence = paddle.to_tensor([2, 4, 8, 16], dtype='int32')
  917. >>> x = paddle.to_tensor([[0, 8, 4, 16], [-1, 2, 8, 4]], dtype='int32')
  918. >>> out1 = paddle.bucketize(x, sorted_sequence)
  919. >>> print(out1)
  920. Tensor(shape=[2, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  921. [[0, 2, 1, 3],
  922. [0, 0, 2, 1]])
  923. >>> out2 = paddle.bucketize(x, sorted_sequence, right=True)
  924. >>> print(out2)
  925. Tensor(shape=[2, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  926. [[0, 3, 2, 4],
  927. [0, 1, 3, 2]])
  928. >>> out3 = x.bucketize(sorted_sequence)
  929. >>> print(out3)
  930. Tensor(shape=[2, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  931. [[0, 2, 1, 3],
  932. [0, 0, 2, 1]])
  933. >>> out4 = x.bucketize(sorted_sequence, right=True)
  934. >>> print(out4)
  935. Tensor(shape=[2, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  936. [[0, 3, 2, 4],
  937. [0, 1, 3, 2]])
  938. """
  939. check_variable_and_dtype(
  940. sorted_sequence,
  941. 'SortedSequence',
  942. ['float32', 'float64', 'int32', 'int64'],
  943. 'paddle.searchsorted',
  944. )
  945. if sorted_sequence.dim() != 1:
  946. raise ValueError(
  947. f"sorted_sequence tensor must be 1 dimension, but got dim {sorted_sequence.dim()}"
  948. )
  949. return searchsorted(sorted_sequence, x, out_int32, right, name)
  950. def searchsorted(
  951. sorted_sequence, values, out_int32=False, right=False, name=None
  952. ):
  953. """
  954. Find the index of the corresponding `sorted_sequence` in the innermost dimension based on the given `values`.
  955. Args:
  956. sorted_sequence (Tensor): An input N-D or 1-D tensor with type int32, int64, float16, float32, float64, bfloat16. The value of the tensor monotonically increases in the innermost dimension.
  957. values (Tensor): An input N-D tensor value with type int32, int64, float16, float32, float64, bfloat16.
  958. out_int32 (bool, optional): Data type of the output tensor which can be int32, int64. The default value is False, and it indicates that the output data type is int64.
  959. right (bool, optional): Find the upper or lower bounds of the sorted_sequence range in the innermost dimension based on the given `values`. If the value of the sorted_sequence is nan or inf, return the size of the innermost dimension.
  960. The default value is False and it shows the lower bounds.
  961. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  962. Returns:
  963. Tensor (the same sizes of the `values`), return the tensor of int32 if set :attr:`out_int32` is True, otherwise return the tensor of int64.
  964. Examples:
  965. .. code-block:: python
  966. >>> import paddle
  967. >>> sorted_sequence = paddle.to_tensor([[1, 3, 5, 7, 9, 11],
  968. ... [2, 4, 6, 8, 10, 12]], dtype='int32')
  969. >>> values = paddle.to_tensor([[3, 6, 9, 10], [3, 6, 9, 10]], dtype='int32')
  970. >>> out1 = paddle.searchsorted(sorted_sequence, values)
  971. >>> print(out1)
  972. Tensor(shape=[2, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  973. [[1, 3, 4, 5],
  974. [1, 2, 4, 4]])
  975. >>> out2 = paddle.searchsorted(sorted_sequence, values, right=True)
  976. >>> print(out2)
  977. Tensor(shape=[2, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  978. [[2, 3, 5, 5],
  979. [1, 3, 4, 5]])
  980. >>> sorted_sequence_1d = paddle.to_tensor([1, 3, 5, 7, 9, 11, 13])
  981. >>> out3 = paddle.searchsorted(sorted_sequence_1d, values)
  982. >>> print(out3)
  983. Tensor(shape=[2, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  984. [[1, 3, 4, 5],
  985. [1, 3, 4, 5]])
  986. """
  987. if in_dynamic_or_pir_mode():
  988. return _C_ops.searchsorted(sorted_sequence, values, out_int32, right)
  989. else:
  990. check_variable_and_dtype(
  991. sorted_sequence,
  992. 'SortedSequence',
  993. ['uint16', 'float16', 'float32', 'float64', 'int32', 'int64'],
  994. 'paddle.searchsorted',
  995. )
  996. check_variable_and_dtype(
  997. values,
  998. 'Values',
  999. ['uint16', 'float16', 'float32', 'float64', 'int32', 'int64'],
  1000. 'paddle.searchsorted',
  1001. )
  1002. helper = LayerHelper('searchsorted', **locals())
  1003. out_type = 'int32' if out_int32 else 'int64'
  1004. out = helper.create_variable_for_type_inference(dtype=out_type)
  1005. helper.append_op(
  1006. type='searchsorted',
  1007. inputs={'SortedSequence': sorted_sequence, "Values": values},
  1008. outputs={'Out': out},
  1009. attrs={"out_int32": out_int32, "right": right},
  1010. )
  1011. return out
  1012. def kthvalue(x, k, axis=None, keepdim=False, name=None):
  1013. """
  1014. Find values and indices of the k-th smallest at the axis.
  1015. Args:
  1016. x (Tensor): A N-D Tensor with type float16, float32, float64, int32, int64.
  1017. k (int): The k for the k-th smallest number to look for along the axis.
  1018. axis (int, optional): Axis to compute indices along. The effective range
  1019. is [-R, R), where R is x.ndim. when axis < 0, it works the same way
  1020. as axis + R. The default is None. And if the axis is None, it will computed as -1 by default.
  1021. keepdim (bool, optional): Whether to keep the given axis in output. If it is True, the dimensions will be same as input x and with size one in the axis. Otherwise the output dimensions is one fewer than x since the axis is squeezed. Default is False.
  1022. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  1023. Returns:
  1024. tuple(Tensor), return the values and indices. The value data type is the same as the input `x`. The indices data type is int64.
  1025. Examples:
  1026. .. code-block:: python
  1027. >>> import paddle
  1028. >>> x = paddle.randn((2,3,2))
  1029. >>> print(x)
  1030. >>> # doctest: +SKIP('Different environments yield different output.')
  1031. Tensor(shape=[2, 3, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  1032. [[[ 0.11855337, -0.30557564],
  1033. [-0.09968963, 0.41220093],
  1034. [ 1.24004936, 1.50014710]],
  1035. [[ 0.08612321, -0.92485696],
  1036. [-0.09276631, 1.15149164],
  1037. [-1.46587241, 1.22873247]]])
  1038. >>> # doctest: -SKIP
  1039. >>> y = paddle.kthvalue(x, 2, 1)
  1040. >>> print(y)
  1041. >>> # doctest: +SKIP('Different environments yield different output.')
  1042. (Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  1043. [[ 0.11855337, 0.41220093],
  1044. [-0.09276631, 1.15149164]]), Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
  1045. [[0, 1],
  1046. [1, 1]]))
  1047. >>> # doctest: -SKIP
  1048. """
  1049. if in_dynamic_or_pir_mode():
  1050. if axis is not None:
  1051. return _C_ops.kthvalue(x, k, axis, keepdim)
  1052. else:
  1053. return _C_ops.kthvalue(x, k, -1, keepdim)
  1054. helper = LayerHelper("kthvalue", **locals())
  1055. inputs = {"X": [x]}
  1056. attrs = {'k': k}
  1057. if axis is not None:
  1058. attrs['axis'] = axis
  1059. values = helper.create_variable_for_type_inference(dtype=x.dtype)
  1060. indices = helper.create_variable_for_type_inference(dtype="int64")
  1061. helper.append_op(
  1062. type="kthvalue",
  1063. inputs=inputs,
  1064. outputs={"Out": [values], "Indices": [indices]},
  1065. attrs=attrs,
  1066. )
  1067. indices.stop_gradient = True
  1068. return values, indices
  1069. def top_p_sampling(x, ps, threshold=None, seed=None, name=None):
  1070. """
  1071. Get the TopP scores and ids according to the cumulative threshold `ps`.
  1072. Args:
  1073. x(Tensor): A N-D Tensor with type float32, float16 and bfloat16.
  1074. ps(Tensor): A 1-D Tensor with type float32, float16 and bfloat16.
  1075. it is the cumulative probability threshold to limit low probability input.
  1076. threshold(Tensor): A 1-D Tensor with type float32, float16 and bfloat16.
  1077. it is the absolute probability threshold to limit input, it will take effect simultaneously with `ps`, if not set, the default value is 0.f.
  1078. seed(int, optional): the random seed,
  1079. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  1080. Returns:
  1081. tuple(Tensor), return the values and indices. The value data type is the same as the input `x`. The indices data type is int64.
  1082. Examples:
  1083. .. code-block:: python
  1084. >>> # doctest: +REQUIRES(env:GPU)
  1085. >>> import paddle
  1086. >>> paddle.device.set_device('gpu')
  1087. >>> paddle.seed(2023)
  1088. >>> x = paddle.randn([2,3])
  1089. >>> print(x)
  1090. Tensor(shape=[2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True,
  1091. [[-0.32012719, -0.07942779, 0.26011357],
  1092. [ 0.79003978, -0.39958701, 1.42184138]])
  1093. >>> paddle.seed(2023)
  1094. >>> ps = paddle.randn([2])
  1095. >>> print(ps)
  1096. Tensor(shape=[2], dtype=float32, place=Place(gpu:0), stop_gradient=True,
  1097. [-0.32012719, -0.07942779])
  1098. >>> value, index = paddle.tensor.top_p_sampling(x, ps)
  1099. >>> print(value)
  1100. Tensor(shape=[2, 1], dtype=float32, place=Place(gpu:0), stop_gradient=True,
  1101. [[0.26011357],
  1102. [1.42184138]])
  1103. >>> print(index)
  1104. Tensor(shape=[2, 1], dtype=int64, place=Place(gpu:0), stop_gradient=True,
  1105. [[2],
  1106. [2]])
  1107. """
  1108. if seed is None:
  1109. seed = -1
  1110. if in_dynamic_or_pir_mode():
  1111. return _C_ops.top_p_sampling(x, ps, threshold, seed)
  1112. inputs = {"x": x, "ps": ps, "threshold": threshold}
  1113. attrs = {"random_seed": seed}
  1114. helper = LayerHelper('top_p_sampling', **locals())
  1115. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  1116. ids = helper.create_variable_for_type_inference(dtype="int64")
  1117. helper.append_op(
  1118. type='top_p_sampling',
  1119. inputs=inputs,
  1120. outputs={'out': out, 'ids': ids},
  1121. attrs=attrs,
  1122. )
  1123. return out, ids