functional.py 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788
  1. from typing import (
  2. List, Tuple, Optional, Union, Any, Sequence, TYPE_CHECKING
  3. )
  4. import torch
  5. from torch._C import _add_docstr
  6. import torch.backends.opt_einsum as opt_einsum
  7. import torch.nn.functional as F
  8. from ._lowrank import svd_lowrank, pca_lowrank
  9. from .overrides import (
  10. has_torch_function, has_torch_function_unary, has_torch_function_variadic,
  11. handle_torch_function)
  12. from ._jit_internal import boolean_dispatch
  13. from ._jit_internal import _overload as overload
  14. Tensor = torch.Tensor
  15. from torch import _VF
  16. __all__ = [
  17. 'atleast_1d',
  18. 'atleast_2d',
  19. 'atleast_3d',
  20. 'align_tensors',
  21. 'broadcast_shapes',
  22. 'broadcast_tensors',
  23. 'cartesian_prod',
  24. 'block_diag',
  25. 'cdist',
  26. 'chain_matmul',
  27. 'einsum',
  28. 'istft',
  29. 'lu',
  30. 'norm',
  31. 'meshgrid',
  32. 'pca_lowrank',
  33. 'split',
  34. 'stft',
  35. 'svd_lowrank',
  36. 'tensordot',
  37. 'unique',
  38. 'unique_consecutive',
  39. ]
  40. def broadcast_tensors(*tensors):
  41. r"""broadcast_tensors(*tensors) -> List of Tensors
  42. Broadcasts the given tensors according to :ref:`broadcasting-semantics`.
  43. Args:
  44. *tensors: any number of tensors of the same type
  45. .. warning::
  46. More than one element of a broadcasted tensor may refer to a single
  47. memory location. As a result, in-place operations (especially ones that
  48. are vectorized) may result in incorrect behavior. If you need to write
  49. to the tensors, please clone them first.
  50. Example::
  51. >>> x = torch.arange(3).view(1, 3)
  52. >>> y = torch.arange(2).view(2, 1)
  53. >>> a, b = torch.broadcast_tensors(x, y)
  54. >>> a.size()
  55. torch.Size([2, 3])
  56. >>> a
  57. tensor([[0, 1, 2],
  58. [0, 1, 2]])
  59. """
  60. # This wrapper exists to support variadic args.
  61. if has_torch_function(tensors):
  62. return handle_torch_function(broadcast_tensors, tensors, *tensors)
  63. return _VF.broadcast_tensors(tensors) # type: ignore[attr-defined]
  64. def broadcast_shapes(*shapes):
  65. r"""broadcast_shapes(*shapes) -> Size
  66. Similar to :func:`broadcast_tensors` but for shapes.
  67. This is equivalent to
  68. ``torch.broadcast_tensors(*map(torch.empty, shapes))[0].shape``
  69. but avoids the need create to intermediate tensors. This is useful for
  70. broadcasting tensors of common batch shape but different rightmost shape,
  71. e.g. to broadcast mean vectors with covariance matrices.
  72. Example::
  73. >>> torch.broadcast_shapes((2,), (3, 1), (1, 1, 1))
  74. torch.Size([1, 3, 2])
  75. Args:
  76. \*shapes (torch.Size): Shapes of tensors.
  77. Returns:
  78. shape (torch.Size): A shape compatible with all input shapes.
  79. Raises:
  80. RuntimeError: If shapes are incompatible.
  81. """
  82. # This wrapper exists to support variadic args.
  83. # TODO Move this to C++ once the jit has better support for torch.Size.
  84. if not torch.jit.is_tracing():
  85. max_len = 0
  86. for shape in shapes:
  87. if isinstance(shape, int):
  88. if max_len < 1:
  89. max_len = 1
  90. elif isinstance(shape, (tuple, list)):
  91. s = len(shape)
  92. if max_len < s:
  93. max_len = s
  94. result = [1] * max_len
  95. for shape in shapes:
  96. if isinstance(shape, int):
  97. shape = (shape,)
  98. if isinstance(shape, (tuple, list)):
  99. for i in range(-1, -1 - len(shape), -1):
  100. if shape[i] < 0:
  101. raise RuntimeError("Trying to create tensor with negative dimension ({}): ({})"
  102. .format(shape[i], shape[i]))
  103. if shape[i] == 1 or shape[i] == result[i]:
  104. continue
  105. if result[i] != 1:
  106. raise RuntimeError("Shape mismatch: objects cannot be broadcast to a single shape")
  107. result[i] = shape[i]
  108. else:
  109. raise RuntimeError("Input shapes should be of type ints, a tuple of ints, or a list of ints, got ", shape)
  110. return torch.Size(result)
  111. else:
  112. # with implementation above, torch.jit.trace hardcodes the sizes which makes subsequent replays fail
  113. with torch.no_grad():
  114. scalar = torch.zeros((), device="cpu")
  115. tensors = [scalar.expand(shape) for shape in shapes]
  116. tensors = broadcast_tensors(*tensors)
  117. return tensors[0].shape
  118. def split(
  119. tensor: Tensor, split_size_or_sections: Union[int, List[int]], dim: int = 0
  120. ) -> List[Tensor]:
  121. r"""Splits the tensor into chunks. Each chunk is a view of the original tensor.
  122. If :attr:`split_size_or_sections` is an integer type, then :attr:`tensor` will
  123. be split into equally sized chunks (if possible). Last chunk will be smaller if
  124. the tensor size along the given dimension :attr:`dim` is not divisible by
  125. :attr:`split_size`.
  126. If :attr:`split_size_or_sections` is a list, then :attr:`tensor` will be split
  127. into ``len(split_size_or_sections)`` chunks with sizes in :attr:`dim` according
  128. to :attr:`split_size_or_sections`.
  129. Args:
  130. tensor (Tensor): tensor to split.
  131. split_size_or_sections (int) or (list(int)): size of a single chunk or
  132. list of sizes for each chunk
  133. dim (int): dimension along which to split the tensor.
  134. Example::
  135. >>> a = torch.arange(10).reshape(5, 2)
  136. >>> a
  137. tensor([[0, 1],
  138. [2, 3],
  139. [4, 5],
  140. [6, 7],
  141. [8, 9]])
  142. >>> torch.split(a, 2)
  143. (tensor([[0, 1],
  144. [2, 3]]),
  145. tensor([[4, 5],
  146. [6, 7]]),
  147. tensor([[8, 9]]))
  148. >>> torch.split(a, [1, 4])
  149. (tensor([[0, 1]]),
  150. tensor([[2, 3],
  151. [4, 5],
  152. [6, 7],
  153. [8, 9]]))
  154. """
  155. if has_torch_function_unary(tensor):
  156. return handle_torch_function(
  157. split, (tensor,), tensor, split_size_or_sections, dim=dim)
  158. # Overwriting reason:
  159. # This dispatches to two ATen functions depending on the type of
  160. # split_size_or_sections. The branching code is in _tensor.py, which we
  161. # call here.
  162. return tensor.split(split_size_or_sections, dim)
  163. def einsum(*args: Any) -> Tensor:
  164. r"""einsum(equation, *operands) -> Tensor
  165. Sums the product of the elements of the input :attr:`operands` along dimensions specified using a notation
  166. based on the Einstein summation convention.
  167. Einsum allows computing many common multi-dimensional linear algebraic array operations by representing them
  168. in a short-hand format based on the Einstein summation convention, given by :attr:`equation`. The details of
  169. this format are described below, but the general idea is to label every dimension of the input :attr:`operands`
  170. with some subscript and define which subscripts are part of the output. The output is then computed by summing
  171. the product of the elements of the :attr:`operands` along the dimensions whose subscripts are not part of the
  172. output. For example, matrix multiplication can be computed using einsum as `torch.einsum("ij,jk->ik", A, B)`.
  173. Here, j is the summation subscript and i and k the output subscripts (see section below for more details on why).
  174. Equation:
  175. The :attr:`equation` string specifies the subscripts (letters in `[a-zA-Z]`) for each dimension of
  176. the input :attr:`operands` in the same order as the dimensions, separating subscripts for each operand by a
  177. comma (','), e.g. `'ij,jk'` specify subscripts for two 2D operands. The dimensions labeled with the same subscript
  178. must be broadcastable, that is, their size must either match or be `1`. The exception is if a subscript is
  179. repeated for the same input operand, in which case the dimensions labeled with this subscript for this operand
  180. must match in size and the operand will be replaced by its diagonal along these dimensions. The subscripts that
  181. appear exactly once in the :attr:`equation` will be part of the output, sorted in increasing alphabetical order.
  182. The output is computed by multiplying the input :attr:`operands` element-wise, with their dimensions aligned based
  183. on the subscripts, and then summing out the dimensions whose subscripts are not part of the output.
  184. Optionally, the output subscripts can be explicitly defined by adding an arrow ('->') at the end of the equation
  185. followed by the subscripts for the output. For instance, the following equation computes the transpose of a
  186. matrix multiplication: 'ij,jk->ki'. The output subscripts must appear at least once for some input operand and
  187. at most once for the output.
  188. Ellipsis ('...') can be used in place of subscripts to broadcast the dimensions covered by the ellipsis.
  189. Each input operand may contain at most one ellipsis which will cover the dimensions not covered by subscripts,
  190. e.g. for an input operand with 5 dimensions, the ellipsis in the equation `'ab...c'` cover the third and fourth
  191. dimensions. The ellipsis does not need to cover the same number of dimensions across the :attr:`operands` but the
  192. 'shape' of the ellipsis (the size of the dimensions covered by them) must broadcast together. If the output is not
  193. explicitly defined with the arrow ('->') notation, the ellipsis will come first in the output (left-most dimensions),
  194. before the subscript labels that appear exactly once for the input operands. e.g. the following equation implements
  195. batch matrix multiplication `'...ij,...jk'`.
  196. A few final notes: the equation may contain whitespaces between the different elements (subscripts, ellipsis,
  197. arrow and comma) but something like `'. . .'` is not valid. An empty string `''` is valid for scalar operands.
  198. .. note::
  199. ``torch.einsum`` handles ellipsis ('...') differently from NumPy in that it allows dimensions
  200. covered by the ellipsis to be summed over, that is, ellipsis are not required to be part of the output.
  201. .. note::
  202. This function uses opt_einsum (https://optimized-einsum.readthedocs.io/en/stable/) to speed up computation or to
  203. consume less memory by optimizing contraction order. This optimization occurs when there are at least three
  204. inputs, since the order does not matter otherwise. Note that finding _the_ optimal path is an NP-hard problem,
  205. thus, opt_einsum relies on different heuristics to achieve near-optimal results. If opt_einsum is not available,
  206. the default order is to contract from left to right.
  207. To bypass this default behavior, add the following line to disable the usage of opt_einsum and skip path
  208. calculation: `torch.backends.opt_einsum.enabled = False`
  209. To specify which strategy you'd like for opt_einsum to compute the contraction path, add the following line:
  210. `torch.backends.opt_einsum.strategy = 'auto'`. The default strategy is 'auto', and we also support 'greedy' and
  211. 'optimal'. Disclaimer that the runtime of 'optimal' is factorial in the number of inputs! See more details in
  212. the opt_einsum documentation (https://optimized-einsum.readthedocs.io/en/stable/path_finding.html).
  213. .. note::
  214. As of PyTorch 1.10 :func:`torch.einsum` also supports the sublist format (see examples below). In this format,
  215. subscripts for each operand are specified by sublists, list of integers in the range [0, 52). These sublists
  216. follow their operands, and an extra sublist can appear at the end of the input to specify the output's
  217. subscripts., e.g. `torch.einsum(op1, sublist1, op2, sublist2, ..., [subslist_out])`. Python's `Ellipsis` object
  218. may be provided in a sublist to enable broadcasting as described in the Equation section above.
  219. Args:
  220. equation (str): The subscripts for the Einstein summation.
  221. operands (List[Tensor]): The tensors to compute the Einstein summation of.
  222. Examples::
  223. >>> # xdoctest: +IGNORE_WANT("non-deterministic")
  224. >>> # trace
  225. >>> torch.einsum('ii', torch.randn(4, 4))
  226. tensor(-1.2104)
  227. >>> # xdoctest: +IGNORE_WANT("non-deterministic")
  228. >>> # diagonal
  229. >>> torch.einsum('ii->i', torch.randn(4, 4))
  230. tensor([-0.1034, 0.7952, -0.2433, 0.4545])
  231. >>> # xdoctest: +IGNORE_WANT("non-deterministic")
  232. >>> # outer product
  233. >>> x = torch.randn(5)
  234. >>> y = torch.randn(4)
  235. >>> torch.einsum('i,j->ij', x, y)
  236. tensor([[ 0.1156, -0.2897, -0.3918, 0.4963],
  237. [-0.3744, 0.9381, 1.2685, -1.6070],
  238. [ 0.7208, -1.8058, -2.4419, 3.0936],
  239. [ 0.1713, -0.4291, -0.5802, 0.7350],
  240. [ 0.5704, -1.4290, -1.9323, 2.4480]])
  241. >>> # xdoctest: +IGNORE_WANT("non-deterministic")
  242. >>> # batch matrix multiplication
  243. >>> As = torch.randn(3, 2, 5)
  244. >>> Bs = torch.randn(3, 5, 4)
  245. >>> torch.einsum('bij,bjk->bik', As, Bs)
  246. tensor([[[-1.0564, -1.5904, 3.2023, 3.1271],
  247. [-1.6706, -0.8097, -0.8025, -2.1183]],
  248. [[ 4.2239, 0.3107, -0.5756, -0.2354],
  249. [-1.4558, -0.3460, 1.5087, -0.8530]],
  250. [[ 2.8153, 1.8787, -4.3839, -1.2112],
  251. [ 0.3728, -2.1131, 0.0921, 0.8305]]])
  252. >>> # xdoctest: +IGNORE_WANT("non-deterministic")
  253. >>> # with sublist format and ellipsis
  254. >>> torch.einsum(As, [..., 0, 1], Bs, [..., 1, 2], [..., 0, 2])
  255. tensor([[[-1.0564, -1.5904, 3.2023, 3.1271],
  256. [-1.6706, -0.8097, -0.8025, -2.1183]],
  257. [[ 4.2239, 0.3107, -0.5756, -0.2354],
  258. [-1.4558, -0.3460, 1.5087, -0.8530]],
  259. [[ 2.8153, 1.8787, -4.3839, -1.2112],
  260. [ 0.3728, -2.1131, 0.0921, 0.8305]]])
  261. >>> # batch permute
  262. >>> A = torch.randn(2, 3, 4, 5)
  263. >>> torch.einsum('...ij->...ji', A).shape
  264. torch.Size([2, 3, 5, 4])
  265. >>> # equivalent to torch.nn.functional.bilinear
  266. >>> A = torch.randn(3, 5, 4)
  267. >>> l = torch.randn(2, 5)
  268. >>> r = torch.randn(2, 4)
  269. >>> torch.einsum('bn,anm,bm->ba', l, A, r)
  270. tensor([[-0.3430, -5.2405, 0.4494],
  271. [ 0.3311, 5.5201, -3.0356]])
  272. """
  273. # This wrapper exists to support variadic args.
  274. if len(args) < 2:
  275. raise ValueError('einsum(): must specify the equation string and at least one operand, '
  276. 'or at least one operand and its subscripts list')
  277. equation = None
  278. operands = None
  279. if isinstance(args[0], torch.Tensor):
  280. # Convert the subscript list format which is an interleaving of operand and its subscripts
  281. # list with an optional output subscripts list at the end (see documentation for more details on this)
  282. # to the equation string format by creating the equation string from the subscripts list and grouping the
  283. # input operands into a tensorlist (List[Tensor]).
  284. def parse_subscript(n: int) -> str:
  285. if n == Ellipsis:
  286. return '...'
  287. if n >= 0 and n < 26:
  288. return chr(ord('A') + n)
  289. if n >= 26 and n < 52:
  290. return chr(ord('a') + n - 26)
  291. raise ValueError('einsum(): subscript in subscript list is not within the valid range [0, 52)')
  292. # Parse subscripts for input operands
  293. equation = ','.join(''.join(parse_subscript(s) for s in l) for l in args[1::2])
  294. # Parse optional output subscripts (provided when the number of arguments is odd)
  295. if len(args) % 2 == 1:
  296. equation += '->' + ''.join(parse_subscript(s) for s in args[-1])
  297. operands = args[:-1:2]
  298. else:
  299. operands = args[::2]
  300. else:
  301. equation = args[0]
  302. operands = args[1:]
  303. if has_torch_function(operands):
  304. return handle_torch_function(einsum, operands, equation, *operands)
  305. if len(operands) == 1 and isinstance(operands[0], (list, tuple)):
  306. # the old interface of passing the operands as one list argument
  307. _operands = operands[0]
  308. # recurse incase operands contains value that has torch function
  309. # in the original implementation this line is omitted
  310. return einsum(equation, *_operands)
  311. if len(operands) <= 2 or not opt_einsum.enabled:
  312. # the path for contracting 0 or 1 time(s) is already optimized
  313. # or the user has disabled using opt_einsum
  314. return _VF.einsum(equation, operands) # type: ignore[attr-defined]
  315. path = None
  316. if opt_einsum.is_available():
  317. _opt_einsum = opt_einsum.get_opt_einsum()
  318. tupled_path = _opt_einsum.contract_path(equation, *operands, optimize=opt_einsum.strategy)[0]
  319. # flatten path for dispatching to C++
  320. path = [item for pair in tupled_path for item in pair]
  321. return _VF.einsum(equation, operands, path=path) # type: ignore[attr-defined]
  322. # This wrapper exists to support variadic args.
  323. if TYPE_CHECKING:
  324. # The JIT doesn't understand Union, so only add type annotation for mypy
  325. def meshgrid(*tensors: Union[Tensor, List[Tensor]],
  326. indexing: Optional[str] = None) -> Tuple[Tensor, ...]:
  327. return _meshgrid(*tensors, indexing=indexing)
  328. else:
  329. def meshgrid(*tensors, indexing: Optional[str] = None) -> Tuple[Tensor, ...]:
  330. r"""Creates grids of coordinates specified by the 1D inputs in `attr`:tensors.
  331. This is helpful when you want to visualize data over some
  332. range of inputs. See below for a plotting example.
  333. Given :math:`N` 1D tensors :math:`T_0 \ldots T_{N-1}` as
  334. inputs with corresponding sizes :math:`S_0 \ldots S_{N-1}`,
  335. this creates :math:`N` N-dimensional tensors :math:`G_0 \ldots
  336. G_{N-1}`, each with shape :math:`(S_0, ..., S_{N-1})` where
  337. the output :math:`G_i` is constructed by expanding :math:`T_i`
  338. to the result shape.
  339. .. note::
  340. 0D inputs are treated equivalently to 1D inputs of a
  341. single element.
  342. .. warning::
  343. `torch.meshgrid(*tensors)` currently has the same behavior
  344. as calling `numpy.meshgrid(*arrays, indexing='ij')`.
  345. In the future `torch.meshgrid` will transition to
  346. `indexing='xy'` as the default.
  347. https://github.com/pytorch/pytorch/issues/50276 tracks
  348. this issue with the goal of migrating to NumPy's behavior.
  349. .. seealso::
  350. :func:`torch.cartesian_prod` has the same effect but it
  351. collects the data in a tensor of vectors.
  352. Args:
  353. tensors (list of Tensor): list of scalars or 1 dimensional tensors. Scalars will be
  354. treated as tensors of size :math:`(1,)` automatically
  355. indexing: (str, optional): the indexing mode, either "xy"
  356. or "ij", defaults to "ij". See warning for future changes.
  357. If "xy" is selected, the first dimension corresponds
  358. to the cardinality of the second input and the second
  359. dimension corresponds to the cardinality of the first
  360. input.
  361. If "ij" is selected, the dimensions are in the same
  362. order as the cardinality of the inputs.
  363. Returns:
  364. seq (sequence of Tensors): If the input has :math:`N`
  365. tensors of size :math:`S_0 \ldots S_{N-1}``, then the
  366. output will also have :math:`N` tensors, where each tensor
  367. is of shape :math:`(S_0, ..., S_{N-1})`.
  368. Example::
  369. >>> x = torch.tensor([1, 2, 3])
  370. >>> y = torch.tensor([4, 5, 6])
  371. Observe the element-wise pairings across the grid, (1, 4),
  372. (1, 5), ..., (3, 6). This is the same thing as the
  373. cartesian product.
  374. >>> grid_x, grid_y = torch.meshgrid(x, y, indexing='ij')
  375. >>> grid_x
  376. tensor([[1, 1, 1],
  377. [2, 2, 2],
  378. [3, 3, 3]])
  379. >>> grid_y
  380. tensor([[4, 5, 6],
  381. [4, 5, 6],
  382. [4, 5, 6]])
  383. This correspondence can be seen when these grids are
  384. stacked properly.
  385. >>> torch.equal(torch.cat(tuple(torch.dstack([grid_x, grid_y]))),
  386. ... torch.cartesian_prod(x, y))
  387. True
  388. `torch.meshgrid` is commonly used to produce a grid for
  389. plotting.
  390. >>> # xdoctest: +REQUIRES(module:matplotlib)
  391. >>> import matplotlib.pyplot as plt
  392. >>> xs = torch.linspace(-5, 5, steps=100)
  393. >>> ys = torch.linspace(-5, 5, steps=100)
  394. >>> x, y = torch.meshgrid(xs, ys, indexing='xy')
  395. >>> z = torch.sin(torch.sqrt(x * x + y * y))
  396. >>> ax = plt.axes(projection='3d')
  397. >>> ax.plot_surface(x.numpy(), y.numpy(), z.numpy())
  398. >>> plt.show()
  399. .. image:: ../_static/img/meshgrid.png
  400. :width: 512
  401. """
  402. return _meshgrid(*tensors, indexing=indexing)
  403. def _meshgrid(*tensors, indexing: Optional[str]):
  404. if has_torch_function(tensors):
  405. return handle_torch_function(meshgrid, tensors, *tensors, indexing=indexing)
  406. if len(tensors) == 1 and isinstance(tensors[0], (list, tuple)):
  407. # the old interface of passing the operands as one list argument
  408. tensors = tensors[0] # type: ignore[assignment]
  409. # Continue allowing call of old method that takes no indexing
  410. # kwarg for forward compatibility reasons.
  411. #
  412. # Remove this two weeks after landing.
  413. kwargs = {} if indexing is None else {'indexing': indexing}
  414. return _VF.meshgrid(tensors, **kwargs) # type: ignore[attr-defined]
  415. def stft(input: Tensor, n_fft: int, hop_length: Optional[int] = None,
  416. win_length: Optional[int] = None, window: Optional[Tensor] = None,
  417. center: bool = True, pad_mode: str = 'reflect', normalized: bool = False,
  418. onesided: Optional[bool] = None,
  419. return_complex: Optional[bool] = None) -> Tensor:
  420. r"""Short-time Fourier transform (STFT).
  421. .. warning::
  422. From version 1.8.0, :attr:`return_complex` must always be given
  423. explicitly for real inputs and `return_complex=False` has been
  424. deprecated. Strongly prefer `return_complex=True` as in a future
  425. pytorch release, this function will only return complex tensors.
  426. Note that :func:`torch.view_as_real` can be used to recover a real
  427. tensor with an extra last dimension for real and imaginary components.
  428. The STFT computes the Fourier transform of short overlapping windows of the
  429. input. This giving frequency components of the signal as they change over
  430. time. The interface of this function is modeled after (but *not* a drop-in
  431. replacement for) librosa_ stft function.
  432. .. _librosa: https://librosa.org/doc/latest/generated/librosa.stft.html
  433. Ignoring the optional batch dimension, this method computes the following
  434. expression:
  435. .. math::
  436. X[\omega, m] = \sum_{k = 0}^{\text{win\_length-1}}%
  437. \text{window}[k]\ \text{input}[m \times \text{hop\_length} + k]\ %
  438. \exp\left(- j \frac{2 \pi \cdot \omega k}{\text{win\_length}}\right),
  439. where :math:`m` is the index of the sliding window, and :math:`\omega` is
  440. the frequency :math:`0 \leq \omega < \text{n\_fft}` for ``onesided=False``,
  441. or :math:`0 \leq \omega < \lfloor \text{n\_fft} / 2 \rfloor + 1` for ``onesided=True``.
  442. * :attr:`input` must be either a 1-D time sequence or a 2-D batch of time
  443. sequences.
  444. * If :attr:`hop_length` is ``None`` (default), it is treated as equal to
  445. ``floor(n_fft / 4)``.
  446. * If :attr:`win_length` is ``None`` (default), it is treated as equal to
  447. :attr:`n_fft`.
  448. * :attr:`window` can be a 1-D tensor of size :attr:`win_length`, e.g., from
  449. :meth:`torch.hann_window`. If :attr:`window` is ``None`` (default), it is
  450. treated as if having :math:`1` everywhere in the window. If
  451. :math:`\text{win\_length} < \text{n\_fft}`, :attr:`window` will be padded on
  452. both sides to length :attr:`n_fft` before being applied.
  453. * If :attr:`center` is ``True`` (default), :attr:`input` will be padded on
  454. both sides so that the :math:`t`-th frame is centered at time
  455. :math:`t \times \text{hop\_length}`. Otherwise, the :math:`t`-th frame
  456. begins at time :math:`t \times \text{hop\_length}`.
  457. * :attr:`pad_mode` determines the padding method used on :attr:`input` when
  458. :attr:`center` is ``True``. See :meth:`torch.nn.functional.pad` for
  459. all available options. Default is ``"reflect"``.
  460. * If :attr:`onesided` is ``True`` (default for real input), only values for
  461. :math:`\omega` in :math:`\left[0, 1, 2, \dots, \left\lfloor
  462. \frac{\text{n\_fft}}{2} \right\rfloor + 1\right]` are returned because
  463. the real-to-complex Fourier transform satisfies the conjugate symmetry,
  464. i.e., :math:`X[m, \omega] = X[m, \text{n\_fft} - \omega]^*`.
  465. Note if the input or window tensors are complex, then :attr:`onesided`
  466. output is not possible.
  467. * If :attr:`normalized` is ``True`` (default is ``False``), the function
  468. returns the normalized STFT results, i.e., multiplied by :math:`(\text{frame\_length})^{-0.5}`.
  469. * If :attr:`return_complex` is ``True`` (default if input is complex), the
  470. return is a ``input.dim() + 1`` dimensional complex tensor. If ``False``,
  471. the output is a ``input.dim() + 2`` dimensional real tensor where the last
  472. dimension represents the real and imaginary components.
  473. Returns either a complex tensor of size :math:`(* \times N \times T)` if
  474. :attr:`return_complex` is true, or a real tensor of size :math:`(* \times N
  475. \times T \times 2)`. Where :math:`*` is the optional batch size of
  476. :attr:`input`, :math:`N` is the number of frequencies where STFT is applied
  477. and :math:`T` is the total number of frames used.
  478. .. warning::
  479. This function changed signature at version 0.4.1. Calling with the
  480. previous signature may cause error or return incorrect result.
  481. Args:
  482. input (Tensor): the input tensor
  483. n_fft (int): size of Fourier transform
  484. hop_length (int, optional): the distance between neighboring sliding window
  485. frames. Default: ``None`` (treated as equal to ``floor(n_fft / 4)``)
  486. win_length (int, optional): the size of window frame and STFT filter.
  487. Default: ``None`` (treated as equal to :attr:`n_fft`)
  488. window (Tensor, optional): the optional window function.
  489. Default: ``None`` (treated as window of all :math:`1` s)
  490. center (bool, optional): whether to pad :attr:`input` on both sides so
  491. that the :math:`t`-th frame is centered at time :math:`t \times \text{hop\_length}`.
  492. Default: ``True``
  493. pad_mode (str, optional): controls the padding method used when
  494. :attr:`center` is ``True``. Default: ``"reflect"``
  495. normalized (bool, optional): controls whether to return the normalized STFT results
  496. Default: ``False``
  497. onesided (bool, optional): controls whether to return half of results to
  498. avoid redundancy for real inputs.
  499. Default: ``True`` for real :attr:`input` and :attr:`window`, ``False`` otherwise.
  500. return_complex (bool, optional): whether to return a complex tensor, or
  501. a real tensor with an extra last dimension for the real and
  502. imaginary components.
  503. .. versionchanged:: 2.0
  504. ``return_complex`` is now a required argument for real inputs,
  505. as the default is being transitioned to ``True``.
  506. .. deprecated:: 2.0
  507. ``return_complex=False`` is deprecated, instead use ``return_complex=True``
  508. Note that calling :func:`torch.view_as_real` on the output will
  509. recover the deprecated output format.
  510. Returns:
  511. Tensor: A tensor containing the STFT result with shape described above
  512. """
  513. if has_torch_function_unary(input):
  514. return handle_torch_function(
  515. stft, (input,), input, n_fft, hop_length=hop_length, win_length=win_length,
  516. window=window, center=center, pad_mode=pad_mode, normalized=normalized,
  517. onesided=onesided, return_complex=return_complex)
  518. # NOTE: Do not edit. This code will be removed once the forward-compatibility
  519. # period is over for PR #73432
  520. if center:
  521. signal_dim = input.dim()
  522. extended_shape = [1] * (3 - signal_dim) + list(input.size())
  523. pad = int(n_fft // 2)
  524. input = F.pad(input.view(extended_shape), [pad, pad], pad_mode)
  525. input = input.view(input.shape[-signal_dim:])
  526. return _VF.stft(input, n_fft, hop_length, win_length, window, # type: ignore[attr-defined]
  527. normalized, onesided, return_complex)
  528. istft = _add_docstr(
  529. torch.istft,
  530. "istft(input, n_fft, hop_length=None, win_length=None, window=None, center=True, "
  531. "normalized=False, onesided=None, length=None, return_complex=False) -> Tensor:\n"
  532. r"""
  533. Inverse short time Fourier Transform. This is expected to be the inverse of :func:`~torch.stft`.
  534. It has the same parameters (+ additional optional parameter of :attr:`length`) and it should return the
  535. least squares estimation of the original signal. The algorithm will check using the NOLA condition (
  536. nonzero overlap).
  537. Important consideration in the parameters :attr:`window` and :attr:`center` so that the envelop
  538. created by the summation of all the windows is never zero at certain point in time. Specifically,
  539. :math:`\sum_{t=-\infty}^{\infty} |w|^2[n-t\times hop\_length] \cancel{=} 0`.
  540. Since :func:`~torch.stft` discards elements at the end of the signal if they do not fit in a frame,
  541. ``istft`` may return a shorter signal than the original signal (can occur if :attr:`center` is False
  542. since the signal isn't padded). If `length` is given in the arguments and is longer than expected,
  543. ``istft`` will pad zeros to the end of the returned signal.
  544. If :attr:`center` is ``True``, then there will be padding e.g. ``'constant'``, ``'reflect'``, etc.
  545. Left padding can be trimmed off exactly because they can be calculated but right padding cannot be
  546. calculated without additional information.
  547. Example: Suppose the last window is:
  548. ``[17, 18, 0, 0, 0]`` vs ``[18, 0, 0, 0, 0]``
  549. The :attr:`n_fft`, :attr:`hop_length`, :attr:`win_length` are all the same which prevents the calculation
  550. of right padding. These additional values could be zeros or a reflection of the signal so providing
  551. :attr:`length` could be useful. If :attr:`length` is ``None`` then padding will be aggressively removed
  552. (some loss of signal).
  553. [1] D. W. Griffin and J. S. Lim, "Signal estimation from modified short-time Fourier transform,"
  554. IEEE Trans. ASSP, vol.32, no.2, pp.236-243, Apr. 1984.
  555. Args:
  556. input (Tensor): The input tensor. Expected to be in the format of :func:`~torch.stft`,
  557. output. That is a complex tensor of shape (``channel``, ``fft_size``, ``n_frame``),
  558. where the ``channel`` dimension is optional.
  559. .. versionchanged:: 2.0
  560. Real datatype inputs are no longer supported. Input must now have a
  561. complex datatype, as returned by ``stft(..., return_complex=True)``.
  562. n_fft (int): Size of Fourier transform
  563. hop_length (Optional[int]): The distance between neighboring sliding window frames.
  564. (Default: ``n_fft // 4``)
  565. win_length (Optional[int]): The size of window frame and STFT filter. (Default: ``n_fft``)
  566. window (Optional[torch.Tensor]): The optional window function.
  567. (Default: ``torch.ones(win_length)``)
  568. center (bool): Whether :attr:`input` was padded on both sides so that the :math:`t`-th frame is
  569. centered at time :math:`t \times \text{hop\_length}`.
  570. (Default: ``True``)
  571. normalized (bool): Whether the STFT was normalized. (Default: ``False``)
  572. onesided (Optional[bool]): Whether the STFT was onesided.
  573. (Default: ``True`` if ``n_fft != fft_size`` in the input size)
  574. length (Optional[int]): The amount to trim the signal by (i.e. the
  575. original signal length). (Default: whole signal)
  576. return_complex (Optional[bool]):
  577. Whether the output should be complex, or if the input should be
  578. assumed to derive from a real signal and window.
  579. Note that this is incompatible with ``onesided=True``.
  580. (Default: ``False``)
  581. Returns:
  582. Tensor: Least squares estimation of the original signal of size (..., signal_length)
  583. """)
  584. if TYPE_CHECKING:
  585. # These _impl functions return a variable number of tensors as output with
  586. # __torch_function__; tuple unpacking is done already rather than being
  587. # done by the caller of the _impl function
  588. _unique_impl_out = Any
  589. else:
  590. _unique_impl_out = Tuple[Tensor, Tensor, Tensor]
  591. def _unique_impl(input: Tensor, sorted: bool = True,
  592. return_inverse: bool = False, return_counts: bool = False,
  593. dim: Optional[int] = None) -> _unique_impl_out:
  594. r"""unique(input, sorted=True, return_inverse=False, return_counts=False, dim=None) -> Tuple[Tensor, Tensor, Tensor]
  595. Returns the unique elements of the input tensor.
  596. .. note:: This function is different from :func:`torch.unique_consecutive` in the sense that
  597. this function also eliminates non-consecutive duplicate values.
  598. .. note:: Currently in the CUDA implementation and the CPU implementation when dim is specified,
  599. `torch.unique` always sort the tensor at the beginning regardless of the `sort` argument.
  600. Sorting could be slow, so if your input tensor is already sorted, it is recommended to use
  601. :func:`torch.unique_consecutive` which avoids the sorting.
  602. Args:
  603. input (Tensor): the input tensor
  604. sorted (bool): Whether to sort the unique elements in ascending order
  605. before returning as output.
  606. return_inverse (bool): Whether to also return the indices for where
  607. elements in the original input ended up in the returned unique list.
  608. return_counts (bool): Whether to also return the counts for each unique
  609. element.
  610. dim (int): the dimension to apply unique. If ``None``, the unique of the
  611. flattened input is returned. default: ``None``
  612. Returns:
  613. (Tensor, Tensor (optional), Tensor (optional)): A tensor or a tuple of tensors containing
  614. - **output** (*Tensor*): the output list of unique scalar elements.
  615. - **inverse_indices** (*Tensor*): (optional) if
  616. :attr:`return_inverse` is True, there will be an additional
  617. returned tensor (same shape as input) representing the indices
  618. for where elements in the original input map to in the output;
  619. otherwise, this function will only return a single tensor.
  620. - **counts** (*Tensor*): (optional) if
  621. :attr:`return_counts` is True, there will be an additional
  622. returned tensor (same shape as output or output.size(dim),
  623. if dim was specified) representing the number of occurrences
  624. for each unique value or tensor.
  625. Example::
  626. >>> output = torch.unique(torch.tensor([1, 3, 2, 3], dtype=torch.long))
  627. >>> output
  628. tensor([1, 2, 3])
  629. >>> output, inverse_indices = torch.unique(
  630. ... torch.tensor([1, 3, 2, 3], dtype=torch.long), sorted=True, return_inverse=True)
  631. >>> output
  632. tensor([1, 2, 3])
  633. >>> inverse_indices
  634. tensor([0, 2, 1, 2])
  635. >>> output, inverse_indices = torch.unique(
  636. ... torch.tensor([[1, 3], [2, 3]], dtype=torch.long), sorted=True, return_inverse=True)
  637. >>> output
  638. tensor([1, 2, 3])
  639. >>> inverse_indices
  640. tensor([[0, 2],
  641. [1, 2]])
  642. """
  643. if has_torch_function_unary(input):
  644. return handle_torch_function(
  645. unique, (input,), input, sorted=sorted, return_inverse=return_inverse,
  646. return_counts=return_counts, dim=dim)
  647. if dim is not None:
  648. output, inverse_indices, counts = _VF.unique_dim(
  649. input,
  650. dim,
  651. sorted=sorted,
  652. return_inverse=return_inverse,
  653. return_counts=return_counts,
  654. )
  655. else:
  656. output, inverse_indices, counts = torch._unique2(
  657. input,
  658. sorted=sorted,
  659. return_inverse=return_inverse,
  660. return_counts=return_counts,
  661. )
  662. return output, inverse_indices, counts
  663. def _unique_consecutive_impl(input: Tensor, return_inverse: bool = False,
  664. return_counts: bool = False,
  665. dim: Optional[int] = None) -> _unique_impl_out:
  666. r"""Eliminates all but the first element from every consecutive group of equivalent elements.
  667. .. note:: This function is different from :func:`torch.unique` in the sense that this function
  668. only eliminates consecutive duplicate values. This semantics is similar to `std::unique`
  669. in C++.
  670. Args:
  671. input (Tensor): the input tensor
  672. return_inverse (bool): Whether to also return the indices for where
  673. elements in the original input ended up in the returned unique list.
  674. return_counts (bool): Whether to also return the counts for each unique
  675. element.
  676. dim (int): the dimension to apply unique. If ``None``, the unique of the
  677. flattened input is returned. default: ``None``
  678. Returns:
  679. (Tensor, Tensor (optional), Tensor (optional)): A tensor or a tuple of tensors containing
  680. - **output** (*Tensor*): the output list of unique scalar elements.
  681. - **inverse_indices** (*Tensor*): (optional) if
  682. :attr:`return_inverse` is True, there will be an additional
  683. returned tensor (same shape as input) representing the indices
  684. for where elements in the original input map to in the output;
  685. otherwise, this function will only return a single tensor.
  686. - **counts** (*Tensor*): (optional) if
  687. :attr:`return_counts` is True, there will be an additional
  688. returned tensor (same shape as output or output.size(dim),
  689. if dim was specified) representing the number of occurrences
  690. for each unique value or tensor.
  691. Example::
  692. >>> x = torch.tensor([1, 1, 2, 2, 3, 1, 1, 2])
  693. >>> output = torch.unique_consecutive(x)
  694. >>> output
  695. tensor([1, 2, 3, 1, 2])
  696. >>> output, inverse_indices = torch.unique_consecutive(x, return_inverse=True)
  697. >>> output
  698. tensor([1, 2, 3, 1, 2])
  699. >>> inverse_indices
  700. tensor([0, 0, 1, 1, 2, 3, 3, 4])
  701. >>> output, counts = torch.unique_consecutive(x, return_counts=True)
  702. >>> output
  703. tensor([1, 2, 3, 1, 2])
  704. >>> counts
  705. tensor([2, 2, 1, 2, 1])
  706. """
  707. if has_torch_function_unary(input):
  708. return handle_torch_function(
  709. unique_consecutive, (input,), input, return_inverse=return_inverse,
  710. return_counts=return_counts, dim=dim)
  711. output, inverse_indices, counts = _VF.unique_consecutive( # type: ignore[attr-defined]
  712. input, return_inverse=return_inverse, return_counts=return_counts, dim=dim)
  713. return output, inverse_indices, counts
  714. def _return_counts(input, sorted=True, return_inverse=False, return_counts=False, dim=None):
  715. # type: (Tensor, bool, bool, bool, Optional[int]) -> Tuple[Tensor, Tensor]
  716. if has_torch_function_unary(input):
  717. return _unique_impl(input, sorted, return_inverse, return_counts, dim)
  718. output, _, counts = _unique_impl(input, sorted, return_inverse, return_counts, dim)
  719. return output, counts
  720. def _return_output(input, sorted=True, return_inverse=False, return_counts=False, dim=None):
  721. # type: (Tensor, bool, bool, bool, Optional[int]) -> Tensor
  722. if has_torch_function_unary(input):
  723. return _unique_impl(input, sorted, return_inverse, return_counts, dim)
  724. output, _, _ = _unique_impl(input, sorted, return_inverse, return_counts, dim)
  725. return output
  726. def _return_inverse(input, sorted=True, return_inverse=False, return_counts=False, dim=None):
  727. # type: (Tensor, bool, bool, bool, Optional[int]) -> Tuple[Tensor, Tensor]
  728. if has_torch_function_unary(input):
  729. return _unique_impl(input, sorted, return_inverse, return_counts, dim)
  730. output, inverse_indices, _ = _unique_impl(input, sorted, return_inverse, return_counts, dim)
  731. return output, inverse_indices
  732. _return_inverse_false = boolean_dispatch(
  733. arg_name='return_counts',
  734. arg_index=3,
  735. default=False,
  736. if_true=_return_counts,
  737. if_false=_return_output,
  738. module_name=__name__,
  739. func_name='unique')
  740. _return_inverse_true = boolean_dispatch(
  741. arg_name='return_counts',
  742. arg_index=3,
  743. default=False,
  744. if_true=_unique_impl,
  745. if_false=_return_inverse,
  746. module_name=__name__,
  747. func_name='unique')
  748. # The return type of unique depends on `return_inverse`, and `return_counts` so in order to
  749. # resolve the output type in TorchScript we need to statically know the value of both parameters
  750. unique = boolean_dispatch(
  751. arg_name='return_inverse',
  752. arg_index=2,
  753. default=False,
  754. if_true=_return_inverse_true,
  755. if_false=_return_inverse_false,
  756. module_name=__name__,
  757. func_name='unique')
  758. unique.__doc__ = _unique_impl.__doc__
  759. def _consecutive_return_counts(input, return_inverse=False, return_counts=False, dim=None):
  760. # type: (Tensor, bool, bool, Optional[int]) -> Tuple[Tensor, Tensor]
  761. if has_torch_function_unary(input):
  762. return _unique_consecutive_impl(input, return_inverse, return_counts, dim)
  763. output, _, counts = _unique_consecutive_impl(input, return_inverse, return_counts, dim)
  764. return output, counts
  765. def _consecutive_return_output(input, return_inverse=False, return_counts=False, dim=None):
  766. # type: (Tensor, bool, bool, Optional[int]) -> Tensor
  767. if has_torch_function_unary(input):
  768. return _unique_consecutive_impl(input, return_inverse, return_counts, dim)
  769. output, _, _ = _unique_consecutive_impl(input, return_inverse, return_counts, dim)
  770. return output
  771. def _consecutive_return_inverse(input, return_inverse=False, return_counts=False, dim=None):
  772. # type: (Tensor, bool, bool, Optional[int]) -> Tuple[Tensor, Tensor]
  773. if has_torch_function_unary(input):
  774. return _unique_consecutive_impl(input, return_inverse, return_counts, dim)
  775. output, inverse_indices, _ = _unique_consecutive_impl(input, return_inverse, return_counts, dim)
  776. return output, inverse_indices
  777. _consecutive_return_inverse_false = boolean_dispatch(
  778. arg_name='return_counts',
  779. arg_index=1,
  780. default=False,
  781. if_true=_consecutive_return_counts,
  782. if_false=_consecutive_return_output,
  783. module_name=__name__,
  784. func_name='unique_consecutive')
  785. _consecutive_return_inverse_true = boolean_dispatch(
  786. arg_name='return_counts',
  787. arg_index=1,
  788. default=False,
  789. if_true=_unique_consecutive_impl,
  790. if_false=_consecutive_return_inverse,
  791. module_name=__name__,
  792. func_name='unique_consecutive')
  793. # The return type of unique depends on `return_inverse`, and `return_counts` so in order to
  794. # resolve the output type in TorchScript we need to statically know the value of both parameters
  795. unique_consecutive = boolean_dispatch(
  796. arg_name='return_inverse',
  797. arg_index=2,
  798. default=False,
  799. if_true=_consecutive_return_inverse_true,
  800. if_false=_consecutive_return_inverse_false,
  801. module_name=__name__,
  802. func_name='unique_consecutive')
  803. unique_consecutive.__doc__ = _unique_consecutive_impl.__doc__
  804. if TYPE_CHECKING:
  805. pass
  806. # There's no good way to use this type annotation without breaking JIT
  807. # overloads. So leave untyped for mypy for now.
  808. else:
  809. @overload
  810. def tensordot(a, b, dims: int = 2, out: Optional[torch.Tensor] = None):
  811. pass
  812. @overload # noqa: F811
  813. def tensordot(a, b, dims: Tuple[List[int], List[int]], out: Optional[torch.Tensor] = None): # noqa: F811
  814. pass
  815. @overload # noqa: F811
  816. def tensordot(a, b, dims: List[List[int]], out: Optional[torch.Tensor] = None): # noqa: F811
  817. pass
  818. @overload # noqa: F811
  819. def tensordot(a, b, dims: torch.Tensor, out: Optional[torch.Tensor] = None): # noqa: F811
  820. pass
  821. def tensordot(a, b, dims=2, out: Optional[torch.Tensor] = None): # noqa: F811
  822. r"""Returns a contraction of a and b over multiple dimensions.
  823. :attr:`tensordot` implements a generalized matrix product.
  824. Args:
  825. a (Tensor): Left tensor to contract
  826. b (Tensor): Right tensor to contract
  827. dims (int or Tuple[List[int], List[int]] or List[List[int]] containing two lists or Tensor): number of dimensions to
  828. contract or explicit lists of dimensions for :attr:`a` and
  829. :attr:`b` respectively
  830. When called with a non-negative integer argument :attr:`dims` = :math:`d`, and
  831. the number of dimensions of :attr:`a` and :attr:`b` is :math:`m` and :math:`n`,
  832. respectively, :func:`~torch.tensordot` computes
  833. .. math::
  834. r_{i_0,...,i_{m-d}, i_d,...,i_n}
  835. = \sum_{k_0,...,k_{d-1}} a_{i_0,...,i_{m-d},k_0,...,k_{d-1}} \times b_{k_0,...,k_{d-1}, i_d,...,i_n}.
  836. When called with :attr:`dims` of the list form, the given dimensions will be contracted
  837. in place of the last :math:`d` of :attr:`a` and the first :math:`d` of :math:`b`. The sizes
  838. in these dimensions must match, but :func:`~torch.tensordot` will deal with broadcasted
  839. dimensions.
  840. Examples::
  841. >>> a = torch.arange(60.).reshape(3, 4, 5)
  842. >>> b = torch.arange(24.).reshape(4, 3, 2)
  843. >>> torch.tensordot(a, b, dims=([1, 0], [0, 1]))
  844. tensor([[4400., 4730.],
  845. [4532., 4874.],
  846. [4664., 5018.],
  847. [4796., 5162.],
  848. [4928., 5306.]])
  849. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
  850. >>> a = torch.randn(3, 4, 5, device='cuda')
  851. >>> b = torch.randn(4, 5, 6, device='cuda')
  852. >>> c = torch.tensordot(a, b, dims=2).cpu()
  853. tensor([[ 8.3504, -2.5436, 6.2922, 2.7556, -1.0732, 3.2741],
  854. [ 3.3161, 0.0704, 5.0187, -0.4079, -4.3126, 4.8744],
  855. [ 0.8223, 3.9445, 3.2168, -0.2400, 3.4117, 1.7780]])
  856. >>> a = torch.randn(3, 5, 4, 6)
  857. >>> b = torch.randn(6, 4, 5, 3)
  858. >>> torch.tensordot(a, b, dims=([2, 1, 3], [1, 2, 0]))
  859. tensor([[ 7.7193, -2.4867, -10.3204],
  860. [ 1.5513, -14.4737, -6.5113],
  861. [ -0.2850, 4.2573, -3.5997]])
  862. """
  863. if has_torch_function_variadic(a, b):
  864. return handle_torch_function(tensordot, (a, b), a, b, dims=dims, out=out)
  865. if not isinstance(dims, (tuple, list, torch.Tensor, int)):
  866. raise RuntimeError("tensordot expects dims to be int or "
  867. + "Tuple[List[int], List[int]] or "
  868. + "List[List[int]] containing two lists, but got "
  869. + f"dims={dims}")
  870. dims_a: List[int] = []
  871. dims_b: List[int] = []
  872. if isinstance(dims, (tuple, list)):
  873. dims_a, dims_b = dims
  874. if isinstance(dims, torch.Tensor):
  875. num_elements = dims.numel()
  876. if num_elements > 1:
  877. assert dims.size()[0] == 2
  878. dims_a = torch.jit.annotate(List[int], dims[0].tolist())
  879. dims_b = torch.jit.annotate(List[int], dims[1].tolist())
  880. else:
  881. dims_val = int(dims.item())
  882. if dims_val < 0:
  883. raise RuntimeError(f"tensordot expects dims >= 0, but got dims={dims}")
  884. dims_a = list(range(-dims_val, 0))
  885. dims_b = list(range(dims_val))
  886. if isinstance(dims, int):
  887. if dims < 0:
  888. raise RuntimeError(f"tensordot expects dims >= 0, but got dims={dims}")
  889. dims_a = list(range(-dims, 0))
  890. dims_b = list(range(dims))
  891. if out is None:
  892. return _VF.tensordot(a, b, dims_a, dims_b) # type: ignore[attr-defined]
  893. else:
  894. return _VF.tensordot(a, b, dims_a, dims_b, out=out) # type: ignore[attr-defined]
  895. def cartesian_prod(*tensors: Tensor) -> Tensor:
  896. """Do cartesian product of the given sequence of tensors. The behavior is similar to
  897. python's `itertools.product`.
  898. Args:
  899. *tensors: any number of 1 dimensional tensors.
  900. Returns:
  901. Tensor: A tensor equivalent to converting all the input tensors into lists,
  902. do `itertools.product` on these lists, and finally convert the resulting list
  903. into tensor.
  904. Example::
  905. >>> import itertools
  906. >>> a = [1, 2, 3]
  907. >>> b = [4, 5]
  908. >>> list(itertools.product(a, b))
  909. [(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]
  910. >>> tensor_a = torch.tensor(a)
  911. >>> tensor_b = torch.tensor(b)
  912. >>> torch.cartesian_prod(tensor_a, tensor_b)
  913. tensor([[1, 4],
  914. [1, 5],
  915. [2, 4],
  916. [2, 5],
  917. [3, 4],
  918. [3, 5]])
  919. """
  920. # This wrapper exists to support variadic args.
  921. if has_torch_function(tensors):
  922. return handle_torch_function(cartesian_prod, tensors, *tensors)
  923. return _VF.cartesian_prod(tensors) # type: ignore[attr-defined]
  924. def block_diag(*tensors):
  925. """Create a block diagonal matrix from provided tensors.
  926. Args:
  927. *tensors: One or more tensors with 0, 1, or 2 dimensions.
  928. Returns:
  929. Tensor: A 2 dimensional tensor with all the input tensors arranged in
  930. order such that their upper left and lower right corners are
  931. diagonally adjacent. All other elements are set to 0.
  932. Example::
  933. >>> import torch
  934. >>> A = torch.tensor([[0, 1], [1, 0]])
  935. >>> B = torch.tensor([[3, 4, 5], [6, 7, 8]])
  936. >>> C = torch.tensor(7)
  937. >>> D = torch.tensor([1, 2, 3])
  938. >>> E = torch.tensor([[4], [5], [6]])
  939. >>> torch.block_diag(A, B, C, D, E)
  940. tensor([[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
  941. [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  942. [0, 0, 3, 4, 5, 0, 0, 0, 0, 0],
  943. [0, 0, 6, 7, 8, 0, 0, 0, 0, 0],
  944. [0, 0, 0, 0, 0, 7, 0, 0, 0, 0],
  945. [0, 0, 0, 0, 0, 0, 1, 2, 3, 0],
  946. [0, 0, 0, 0, 0, 0, 0, 0, 0, 4],
  947. [0, 0, 0, 0, 0, 0, 0, 0, 0, 5],
  948. [0, 0, 0, 0, 0, 0, 0, 0, 0, 6]])
  949. """
  950. # This wrapper exists to support variadic args.
  951. if has_torch_function(tensors):
  952. return handle_torch_function(block_diag, tensors, *tensors)
  953. return torch._C._VariableFunctions.block_diag(tensors) # type: ignore[attr-defined]
  954. def cdist(x1, x2, p=2., compute_mode='use_mm_for_euclid_dist_if_necessary'):
  955. # type: (Tensor, Tensor, float, str) -> (Tensor)
  956. r"""Computes batched the p-norm distance between each pair of the two collections of row vectors.
  957. Args:
  958. x1 (Tensor): input tensor of shape :math:`B \times P \times M`.
  959. x2 (Tensor): input tensor of shape :math:`B \times R \times M`.
  960. p: p value for the p-norm distance to calculate between each vector pair
  961. :math:`\in [0, \infty]`.
  962. compute_mode:
  963. 'use_mm_for_euclid_dist_if_necessary' - will use matrix multiplication approach to calculate
  964. euclidean distance (p = 2) if P > 25 or R > 25
  965. 'use_mm_for_euclid_dist' - will always use matrix multiplication approach to calculate
  966. euclidean distance (p = 2)
  967. 'donot_use_mm_for_euclid_dist' - will never use matrix multiplication approach to calculate
  968. euclidean distance (p = 2)
  969. Default: use_mm_for_euclid_dist_if_necessary.
  970. If x1 has shape :math:`B \times P \times M` and x2 has shape :math:`B \times R \times M` then the
  971. output will have shape :math:`B \times P \times R`.
  972. This function is equivalent to `scipy.spatial.distance.cdist(input,'minkowski', p=p)`
  973. if :math:`p \in (0, \infty)`. When :math:`p = 0` it is equivalent to
  974. `scipy.spatial.distance.cdist(input, 'hamming') * M`. When :math:`p = \infty`, the closest
  975. scipy function is `scipy.spatial.distance.cdist(xn, lambda x, y: np.abs(x - y).max())`.
  976. Example:
  977. >>> a = torch.tensor([[0.9041, 0.0196], [-0.3108, -2.4423], [-0.4821, 1.059]])
  978. >>> a
  979. tensor([[ 0.9041, 0.0196],
  980. [-0.3108, -2.4423],
  981. [-0.4821, 1.0590]])
  982. >>> b = torch.tensor([[-2.1763, -0.4713], [-0.6986, 1.3702]])
  983. >>> b
  984. tensor([[-2.1763, -0.4713],
  985. [-0.6986, 1.3702]])
  986. >>> torch.cdist(a, b, p=2)
  987. tensor([[3.1193, 2.0959],
  988. [2.7138, 3.8322],
  989. [2.2830, 0.3791]])
  990. """
  991. if has_torch_function_variadic(x1, x2):
  992. return handle_torch_function(
  993. cdist, (x1, x2), x1, x2, p=p, compute_mode=compute_mode)
  994. if compute_mode == 'use_mm_for_euclid_dist_if_necessary':
  995. return _VF.cdist(x1, x2, p, None) # type: ignore[attr-defined]
  996. elif compute_mode == 'use_mm_for_euclid_dist':
  997. return _VF.cdist(x1, x2, p, 1) # type: ignore[attr-defined]
  998. elif compute_mode == 'donot_use_mm_for_euclid_dist':
  999. return _VF.cdist(x1, x2, p, 2) # type: ignore[attr-defined]
  1000. else:
  1001. raise ValueError(f"{compute_mode} is not a valid value for compute_mode")
  1002. def atleast_1d(*tensors):
  1003. r"""
  1004. Returns a 1-dimensional view of each input tensor with zero dimensions.
  1005. Input tensors with one or more dimensions are returned as-is.
  1006. Args:
  1007. input (Tensor or list of Tensors)
  1008. Returns:
  1009. output (Tensor or tuple of Tensors)
  1010. Example::
  1011. >>> x = torch.arange(2)
  1012. >>> x
  1013. tensor([0, 1])
  1014. >>> torch.atleast_1d(x)
  1015. tensor([0, 1])
  1016. >>> x = torch.tensor(1.)
  1017. >>> x
  1018. tensor(1.)
  1019. >>> torch.atleast_1d(x)
  1020. tensor([1.])
  1021. >>> x = torch.tensor(0.5)
  1022. >>> y = torch.tensor(1.)
  1023. >>> torch.atleast_1d((x, y))
  1024. (tensor([0.5000]), tensor([1.]))
  1025. """
  1026. # This wrapper exists to support variadic args.
  1027. if has_torch_function(tensors):
  1028. return handle_torch_function(atleast_1d, tensors, *tensors)
  1029. if len(tensors) == 1:
  1030. tensors = tensors[0]
  1031. return _VF.atleast_1d(tensors) # type: ignore[attr-defined]
  1032. def atleast_2d(*tensors):
  1033. r"""
  1034. Returns a 2-dimensional view of each input tensor with zero dimensions.
  1035. Input tensors with two or more dimensions are returned as-is.
  1036. Args:
  1037. input (Tensor or list of Tensors)
  1038. Returns:
  1039. output (Tensor or tuple of Tensors)
  1040. Example::
  1041. >>> x = torch.tensor(1.)
  1042. >>> x
  1043. tensor(1.)
  1044. >>> torch.atleast_2d(x)
  1045. tensor([[1.]])
  1046. >>> x = torch.arange(4).view(2, 2)
  1047. >>> x
  1048. tensor([[0, 1],
  1049. [2, 3]])
  1050. >>> torch.atleast_2d(x)
  1051. tensor([[0, 1],
  1052. [2, 3]])
  1053. >>> x = torch.tensor(0.5)
  1054. >>> y = torch.tensor(1.)
  1055. >>> torch.atleast_2d((x, y))
  1056. (tensor([[0.5000]]), tensor([[1.]]))
  1057. """
  1058. # This wrapper exists to support variadic args.
  1059. if has_torch_function(tensors):
  1060. return handle_torch_function(atleast_2d, tensors, *tensors)
  1061. if len(tensors) == 1:
  1062. tensors = tensors[0]
  1063. return _VF.atleast_2d(tensors) # type: ignore[attr-defined]
  1064. def atleast_3d(*tensors):
  1065. r"""
  1066. Returns a 3-dimensional view of each input tensor with zero dimensions.
  1067. Input tensors with three or more dimensions are returned as-is.
  1068. Args:
  1069. input (Tensor or list of Tensors)
  1070. Returns:
  1071. output (Tensor or tuple of Tensors)
  1072. Example:
  1073. >>> x = torch.tensor(0.5)
  1074. >>> x
  1075. tensor(0.5000)
  1076. >>> torch.atleast_3d(x)
  1077. tensor([[[0.5000]]])
  1078. >>> y = torch.arange(4).view(2, 2)
  1079. >>> y
  1080. tensor([[0, 1],
  1081. [2, 3]])
  1082. >>> torch.atleast_3d(y)
  1083. tensor([[[0],
  1084. [1]],
  1085. <BLANKLINE>
  1086. [[2],
  1087. [3]]])
  1088. >>> x = torch.tensor(1).view(1, 1, 1)
  1089. >>> x
  1090. tensor([[[1]]])
  1091. >>> torch.atleast_3d(x)
  1092. tensor([[[1]]])
  1093. >>> x = torch.tensor(0.5)
  1094. >>> y = torch.tensor(1.)
  1095. >>> torch.atleast_3d((x, y))
  1096. (tensor([[[0.5000]]]), tensor([[[1.]]]))
  1097. """
  1098. # This wrapper exists to support variadic args.
  1099. if has_torch_function(tensors):
  1100. return handle_torch_function(atleast_3d, tensors, *tensors)
  1101. if len(tensors) == 1:
  1102. tensors = tensors[0]
  1103. return _VF.atleast_3d(tensors) # type: ignore[attr-defined]
  1104. if TYPE_CHECKING:
  1105. pass
  1106. # There's no good way to use this type annotation; cannot rename norm() to
  1107. # _norm_impl() in a way that doesn't break JIT overloads. So leave untyped
  1108. # for mypy for now.
  1109. # def norm(input: Tensor,
  1110. # p: Optional[Union[str, Number]] = "fro",
  1111. # dim: Optional[Union[int, List[int]]] = None,
  1112. # keepdim: bool = False,
  1113. # out: Optional[Tensor] = None,
  1114. # dtype: _dtype = None) -> Tensor:
  1115. # return _norm_impl(input, p, dim, keepdim, out, dtype)
  1116. else:
  1117. # TODO: type dim as BroadcastingList when
  1118. # https://github.com/pytorch/pytorch/issues/33782 is fixed
  1119. @overload
  1120. def norm(input, p="fro", dim=None, keepdim=False, out=None, dtype=None):
  1121. # type: (Tensor, str, Optional[List[int]], bool, Optional[Tensor], Optional[int]) -> Tensor
  1122. pass
  1123. @overload # noqa: F811
  1124. def norm(input, p="fro", dim=None, keepdim=False, out=None, dtype=None): # noqa: F811
  1125. # type: (Tensor, Optional[number], Optional[List[int]], bool, Optional[Tensor], Optional[int]) -> Tensor
  1126. pass
  1127. @overload # noqa: F811
  1128. def norm(input, p="fro", dim=None, keepdim=False, out=None, dtype=None): # noqa: F811
  1129. # type: (Tensor, Optional[number], Optional[int], bool, Optional[Tensor], Optional[int]) -> Tensor
  1130. pass
  1131. @overload # noqa: F811
  1132. def norm(input, p="fro", dim=None, keepdim=False, out=None, dtype=None): # noqa: F811
  1133. # type: (Tensor, str, Optional[int], bool, Optional[Tensor], Optional[int]) -> Tensor
  1134. pass
  1135. def norm(input, p: Optional[Union[float, str]] = "fro", dim=None, keepdim=False, out=None, dtype=None): # noqa: F811
  1136. r"""Returns the matrix norm or vector norm of a given tensor.
  1137. .. warning::
  1138. torch.norm is deprecated and may be removed in a future PyTorch release.
  1139. Its documentation and behavior may be incorrect, and it is no longer
  1140. actively maintained.
  1141. Use :func:`torch.linalg.vector_norm` when computing vector norms and
  1142. :func:`torch.linalg.matrix_norm` when computing matrix norms.
  1143. For a function with a similar behavior as this one see :func:`torch.linalg.norm`.
  1144. Note, however, the signature for these functions is slightly different than the
  1145. signature for ``torch.norm``.
  1146. Args:
  1147. input (Tensor): The input tensor. Its data type must be either a floating
  1148. point or complex type. For complex inputs, the norm is calculated using the
  1149. absolute value of each element. If the input is complex and neither
  1150. :attr:`dtype` nor :attr:`out` is specified, the result's data type will
  1151. be the corresponding floating point type (e.g. float if :attr:`input` is
  1152. complexfloat).
  1153. p (int, float, inf, -inf, 'fro', 'nuc', optional): the order of norm. Default: ``'fro'``
  1154. The following norms can be calculated:
  1155. ====== ============== ==========================
  1156. ord matrix norm vector norm
  1157. ====== ============== ==========================
  1158. 'fro' Frobenius norm --
  1159. 'nuc' nuclear norm --
  1160. Number -- sum(abs(x)**ord)**(1./ord)
  1161. ====== ============== ==========================
  1162. The vector norm can be calculated across any number of dimensions.
  1163. The corresponding dimensions of :attr:`input` are flattened into
  1164. one dimension, and the norm is calculated on the flattened
  1165. dimension.
  1166. Frobenius norm produces the same result as ``p=2`` in all cases
  1167. except when :attr:`dim` is a list of three or more dims, in which
  1168. case Frobenius norm throws an error.
  1169. Nuclear norm can only be calculated across exactly two dimensions.
  1170. dim (int, tuple of ints, list of ints, optional):
  1171. Specifies which dimension or dimensions of :attr:`input` to
  1172. calculate the norm across. If :attr:`dim` is ``None``, the norm will
  1173. be calculated across all dimensions of :attr:`input`. If the norm
  1174. type indicated by :attr:`p` does not support the specified number of
  1175. dimensions, an error will occur.
  1176. keepdim (bool, optional): whether the output tensors have :attr:`dim`
  1177. retained or not. Ignored if :attr:`dim` = ``None`` and
  1178. :attr:`out` = ``None``. Default: ``False``
  1179. out (Tensor, optional): the output tensor. Ignored if
  1180. :attr:`dim` = ``None`` and :attr:`out` = ``None``.
  1181. dtype (:class:`torch.dtype`, optional): the desired data type of
  1182. returned tensor. If specified, the input tensor is casted to
  1183. :attr:`dtype` while performing the operation. Default: None.
  1184. .. note::
  1185. Even though ``p='fro'`` supports any number of dimensions, the true
  1186. mathematical definition of Frobenius norm only applies to tensors with
  1187. exactly two dimensions. :func:`torch.linalg.matrix_norm` with ``ord='fro'``
  1188. aligns with the mathematical definition, since it can only be applied across
  1189. exactly two dimensions.
  1190. Example::
  1191. >>> import torch
  1192. >>> a = torch.arange(9, dtype= torch.float) - 4
  1193. >>> b = a.reshape((3, 3))
  1194. >>> torch.norm(a)
  1195. tensor(7.7460)
  1196. >>> torch.norm(b)
  1197. tensor(7.7460)
  1198. >>> torch.norm(a, float('inf'))
  1199. tensor(4.)
  1200. >>> torch.norm(b, float('inf'))
  1201. tensor(4.)
  1202. >>> c = torch.tensor([[ 1, 2, 3], [-1, 1, 4]] , dtype=torch.float)
  1203. >>> torch.norm(c, dim=0)
  1204. tensor([1.4142, 2.2361, 5.0000])
  1205. >>> torch.norm(c, dim=1)
  1206. tensor([3.7417, 4.2426])
  1207. >>> torch.norm(c, p=1, dim=1)
  1208. tensor([6., 6.])
  1209. >>> d = torch.arange(8, dtype=torch.float).reshape(2, 2, 2)
  1210. >>> torch.norm(d, dim=(1, 2))
  1211. tensor([ 3.7417, 11.2250])
  1212. >>> torch.norm(d[0, :, :]), torch.norm(d[1, :, :])
  1213. (tensor(3.7417), tensor(11.2250))
  1214. """
  1215. if has_torch_function_unary(input):
  1216. return handle_torch_function(
  1217. norm, (input,), input, p=p, dim=dim, keepdim=keepdim, out=out, dtype=dtype)
  1218. # NB. All the repeated code and weird python is to please TorchScript.
  1219. # For a more compact implementation see the relevant function in `_refs/__init__.py`
  1220. # We don't do this for MPS or sparse tensors
  1221. if input.layout == torch.strided and input.device.type in ("cpu", "cuda", "meta"):
  1222. if dim is not None:
  1223. if isinstance(dim, int):
  1224. _dim = [dim]
  1225. else:
  1226. _dim = dim
  1227. else:
  1228. _dim = None # type: ignore[assignment]
  1229. if isinstance(p, str):
  1230. if p == "fro" and (dim is None or isinstance(dim, int) or len(dim) <= 2):
  1231. if out is None:
  1232. return torch.linalg.vector_norm(input, 2, _dim, keepdim, dtype=dtype)
  1233. else:
  1234. return torch.linalg.vector_norm(input, 2, _dim, keepdim, dtype=dtype, out=out)
  1235. # Here we either call the nuclear norm, or we call matrix_norm with some arguments
  1236. # that will throw an error
  1237. if _dim is None:
  1238. _dim = list(range(input.ndim))
  1239. if out is None:
  1240. return torch.linalg.matrix_norm(input, p, _dim, keepdim, dtype=dtype)
  1241. else:
  1242. return torch.linalg.matrix_norm(input, p, _dim, keepdim, dtype=dtype, out=out)
  1243. else:
  1244. # NB. p should be Union[str, number], not Optional!
  1245. _p = 2.0 if p is None else p
  1246. if out is None:
  1247. return torch.linalg.vector_norm(input, _p, _dim, keepdim, dtype=dtype)
  1248. else:
  1249. return torch.linalg.vector_norm(input, _p, _dim, keepdim, dtype=dtype, out=out)
  1250. ndim = input.dim()
  1251. # catch default case
  1252. if dim is None and out is None and dtype is None and p is not None:
  1253. if isinstance(p, str):
  1254. if p == "fro":
  1255. return _VF.frobenius_norm(input, dim=(), keepdim=keepdim)
  1256. if not isinstance(p, str):
  1257. _dim = [i for i in range(ndim)] # noqa: C416 TODO: rewrite as list(range(m))
  1258. return _VF.norm(input, p, dim=_dim, keepdim=keepdim) # type: ignore[attr-defined]
  1259. # TODO: when https://github.com/pytorch/pytorch/issues/33782 is fixed
  1260. # remove the overloads where dim is an int and replace with BraodcastingList1
  1261. # and remove next four lines, replace _dim with dim
  1262. if dim is not None:
  1263. if isinstance(dim, int):
  1264. _dim = [dim]
  1265. else:
  1266. _dim = dim
  1267. else:
  1268. _dim = None # type: ignore[assignment]
  1269. if isinstance(p, str):
  1270. if p == "fro":
  1271. if dtype is not None:
  1272. raise ValueError("dtype argument is not supported in frobenius norm")
  1273. if _dim is None:
  1274. _dim = list(range(ndim))
  1275. if out is None:
  1276. return _VF.frobenius_norm(input, _dim, keepdim=keepdim)
  1277. else:
  1278. return _VF.frobenius_norm(input, _dim, keepdim=keepdim, out=out)
  1279. elif p == "nuc":
  1280. if dtype is not None:
  1281. raise ValueError("dtype argument is not supported in nuclear norm")
  1282. if _dim is None:
  1283. if out is None:
  1284. return _VF.nuclear_norm(input, keepdim=keepdim)
  1285. else:
  1286. return _VF.nuclear_norm(input, keepdim=keepdim, out=out)
  1287. else:
  1288. if out is None:
  1289. return _VF.nuclear_norm(input, _dim, keepdim=keepdim)
  1290. else:
  1291. return _VF.nuclear_norm(input, _dim, keepdim=keepdim, out=out)
  1292. raise RuntimeError(f"only valid string values are 'fro' and 'nuc', found {p}")
  1293. else:
  1294. if _dim is None:
  1295. _dim = list(range(ndim))
  1296. if out is None:
  1297. if dtype is None:
  1298. return _VF.norm(input, p, _dim, keepdim=keepdim) # type: ignore[attr-defined]
  1299. else:
  1300. return _VF.norm(input, p, _dim, keepdim=keepdim, dtype=dtype) # type: ignore[attr-defined]
  1301. else:
  1302. if dtype is None:
  1303. return _VF.norm(input, p, _dim, keepdim=keepdim, out=out) # type: ignore[attr-defined]
  1304. else:
  1305. return _VF.norm(input, p, _dim, keepdim=keepdim, dtype=dtype, out=out) # type: ignore[attr-defined]
  1306. def chain_matmul(*matrices, out=None):
  1307. r"""Returns the matrix product of the :math:`N` 2-D tensors. This product is efficiently computed
  1308. using the matrix chain order algorithm which selects the order in which incurs the lowest cost in terms
  1309. of arithmetic operations (`[CLRS]`_). Note that since this is a function to compute the product, :math:`N`
  1310. needs to be greater than or equal to 2; if equal to 2 then a trivial matrix-matrix product is returned.
  1311. If :math:`N` is 1, then this is a no-op - the original matrix is returned as is.
  1312. .. warning::
  1313. :func:`torch.chain_matmul` is deprecated and will be removed in a future PyTorch release.
  1314. Use :func:`torch.linalg.multi_dot` instead, which accepts a list of two or more tensors
  1315. rather than multiple arguments.
  1316. Args:
  1317. matrices (Tensors...): a sequence of 2 or more 2-D tensors whose product is to be determined.
  1318. out (Tensor, optional): the output tensor. Ignored if :attr:`out` = ``None``.
  1319. Returns:
  1320. Tensor: if the :math:`i^{th}` tensor was of dimensions :math:`p_{i} \times p_{i + 1}`, then the product
  1321. would be of dimensions :math:`p_{1} \times p_{N + 1}`.
  1322. Example::
  1323. >>> # xdoctest: +SKIP
  1324. >>> # xdoctest: +IGNORE_WANT("non-deterministic")
  1325. >>> a = torch.randn(3, 4)
  1326. >>> b = torch.randn(4, 5)
  1327. >>> c = torch.randn(5, 6)
  1328. >>> d = torch.randn(6, 7)
  1329. >>> # will raise a deprecation warning
  1330. >>> torch.chain_matmul(a, b, c, d)
  1331. tensor([[ -2.3375, -3.9790, -4.1119, -6.6577, 9.5609, -11.5095, -3.2614],
  1332. [ 21.4038, 3.3378, -8.4982, -5.2457, -10.2561, -2.4684, 2.7163],
  1333. [ -0.9647, -5.8917, -2.3213, -5.2284, 12.8615, -12.2816, -2.5095]])
  1334. .. _`[CLRS]`: https://mitpress.mit.edu/books/introduction-algorithms-third-edition
  1335. """
  1336. # This wrapper exists to support variadic args.
  1337. if has_torch_function(matrices):
  1338. return handle_torch_function(chain_matmul, matrices, *matrices)
  1339. if out is None:
  1340. return _VF.chain_matmul(matrices) # type: ignore[attr-defined]
  1341. else:
  1342. return _VF.chain_matmul(matrices, out=out) # type: ignore[attr-defined]
  1343. def _lu_impl(A, pivot=True, get_infos=False, out=None):
  1344. # type: (Tensor, bool, bool, Any) -> Tuple[Tensor, Tensor, Tensor]
  1345. r"""Computes the LU factorization of a matrix or batches of matrices
  1346. :attr:`A`. Returns a tuple containing the LU factorization and
  1347. pivots of :attr:`A`. Pivoting is done if :attr:`pivot` is set to
  1348. ``True``.
  1349. .. warning::
  1350. :func:`torch.lu` is deprecated in favor of :func:`torch.linalg.lu_factor`
  1351. and :func:`torch.linalg.lu_factor_ex`. :func:`torch.lu` will be removed in a
  1352. future PyTorch release.
  1353. ``LU, pivots, info = torch.lu(A, compute_pivots)`` should be replaced with
  1354. .. code:: python
  1355. LU, pivots = torch.linalg.lu_factor(A, compute_pivots)
  1356. ``LU, pivots, info = torch.lu(A, compute_pivots, get_infos=True)`` should be replaced with
  1357. .. code:: python
  1358. LU, pivots, info = torch.linalg.lu_factor_ex(A, compute_pivots)
  1359. .. note::
  1360. * The returned permutation matrix for every matrix in the batch is
  1361. represented by a 1-indexed vector of size ``min(A.shape[-2], A.shape[-1])``.
  1362. ``pivots[i] == j`` represents that in the ``i``-th step of the algorithm,
  1363. the ``i``-th row was permuted with the ``j-1``-th row.
  1364. * LU factorization with :attr:`pivot` = ``False`` is not available
  1365. for CPU, and attempting to do so will throw an error. However,
  1366. LU factorization with :attr:`pivot` = ``False`` is available for
  1367. CUDA.
  1368. * This function does not check if the factorization was successful
  1369. or not if :attr:`get_infos` is ``True`` since the status of the
  1370. factorization is present in the third element of the return tuple.
  1371. * In the case of batches of square matrices with size less or equal
  1372. to 32 on a CUDA device, the LU factorization is repeated for
  1373. singular matrices due to the bug in the MAGMA library
  1374. (see magma issue 13).
  1375. * ``L``, ``U``, and ``P`` can be derived using :func:`torch.lu_unpack`.
  1376. .. warning::
  1377. The gradients of this function will only be finite when :attr:`A` is full rank.
  1378. This is because the LU decomposition is just differentiable at full rank matrices.
  1379. Furthermore, if :attr:`A` is close to not being full rank,
  1380. the gradient will be numerically unstable as it depends on the computation of :math:`L^{-1}` and :math:`U^{-1}`.
  1381. Args:
  1382. A (Tensor): the tensor to factor of size :math:`(*, m, n)`
  1383. pivot (bool, optional): controls whether pivoting is done. Default: ``True``
  1384. get_infos (bool, optional): if set to ``True``, returns an info IntTensor.
  1385. Default: ``False``
  1386. out (tuple, optional): optional output tuple. If :attr:`get_infos` is ``True``,
  1387. then the elements in the tuple are Tensor, IntTensor,
  1388. and IntTensor. If :attr:`get_infos` is ``False``, then the
  1389. elements in the tuple are Tensor, IntTensor. Default: ``None``
  1390. Returns:
  1391. (Tensor, IntTensor, IntTensor (optional)): A tuple of tensors containing
  1392. - **factorization** (*Tensor*): the factorization of size :math:`(*, m, n)`
  1393. - **pivots** (*IntTensor*): the pivots of size :math:`(*, \text{min}(m, n))`.
  1394. ``pivots`` stores all the intermediate transpositions of rows.
  1395. The final permutation ``perm`` could be reconstructed by
  1396. applying ``swap(perm[i], perm[pivots[i] - 1])`` for ``i = 0, ..., pivots.size(-1) - 1``,
  1397. where ``perm`` is initially the identity permutation of :math:`m` elements
  1398. (essentially this is what :func:`torch.lu_unpack` is doing).
  1399. - **infos** (*IntTensor*, *optional*): if :attr:`get_infos` is ``True``, this is a tensor of
  1400. size :math:`(*)` where non-zero values indicate whether factorization for the matrix or
  1401. each minibatch has succeeded or failed
  1402. Example::
  1403. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_LAPACK)
  1404. >>> # xdoctest: +IGNORE_WANT("non-determenistic")
  1405. >>> A = torch.randn(2, 3, 3)
  1406. >>> A_LU, pivots = torch.lu(A)
  1407. >>> A_LU
  1408. tensor([[[ 1.3506, 2.5558, -0.0816],
  1409. [ 0.1684, 1.1551, 0.1940],
  1410. [ 0.1193, 0.6189, -0.5497]],
  1411. [[ 0.4526, 1.2526, -0.3285],
  1412. [-0.7988, 0.7175, -0.9701],
  1413. [ 0.2634, -0.9255, -0.3459]]])
  1414. >>> pivots
  1415. tensor([[ 3, 3, 3],
  1416. [ 3, 3, 3]], dtype=torch.int32)
  1417. >>> A_LU, pivots, info = torch.lu(A, get_infos=True)
  1418. >>> if info.nonzero().size(0) == 0:
  1419. ... print('LU factorization succeeded for all samples!')
  1420. LU factorization succeeded for all samples!
  1421. """
  1422. # If get_infos is True, then we don't need to check for errors and vice versa
  1423. return torch._lu_with_info(A, pivot=pivot, check_errors=(not get_infos))
  1424. if TYPE_CHECKING:
  1425. _ListOrSeq = Sequence[Tensor]
  1426. else:
  1427. _ListOrSeq = List[Tensor]
  1428. def _check_list_size(out_len: int, get_infos: bool, out: _ListOrSeq) -> None:
  1429. get_infos_int = 1 if get_infos else 0
  1430. if out_len - get_infos_int != 2:
  1431. raise TypeError(f"expected tuple of {2 + int(get_infos)} elements but got {out_len}")
  1432. if not isinstance(out, (tuple, list)):
  1433. raise TypeError(f"argument 'out' must be tuple of Tensors, not {type(out).__name__}")
  1434. def _lu_with_infos(A, pivot=True, get_infos=False, out=None):
  1435. # type: (Tensor, bool, bool, Optional[Tuple[Tensor, Tensor, Tensor]]) -> Tuple[Tensor, Tensor, Tensor]
  1436. if has_torch_function_unary(A):
  1437. return handle_torch_function(
  1438. lu, (A,), A, pivot=pivot, get_infos=get_infos, out=out)
  1439. result = _lu_impl(A, pivot, get_infos, out)
  1440. if out is not None:
  1441. _check_list_size(len(out), get_infos, out)
  1442. for i in range(len(out)):
  1443. out[i].resize_as_(result[i]).copy_(result[i])
  1444. return out
  1445. else:
  1446. return result # A_LU, pivots, infos
  1447. def _lu_no_infos(A, pivot=True, get_infos=False, out=None):
  1448. # type: (Tensor, bool, bool, Optional[Tuple[Tensor, Tensor]]) -> Tuple[Tensor, Tensor]
  1449. # need to check for torch_function here so that we exit if
  1450. if has_torch_function_unary(A):
  1451. return handle_torch_function(
  1452. lu, (A,), A, pivot=pivot, get_infos=get_infos, out=out)
  1453. result = _lu_impl(A, pivot, get_infos, out)
  1454. if out is not None:
  1455. _check_list_size(len(out), get_infos, out)
  1456. for i in range(len(out)):
  1457. out[i].resize_as_(result[i]).copy_(result[i])
  1458. return out
  1459. else:
  1460. return result[0], result[1] # A_LU, pivots
  1461. # The return type of lu depends on `get_infos`, so in order to resolve the output type
  1462. # of lu in TorchScript we need to statically know the value of `get_infos`
  1463. lu = boolean_dispatch(
  1464. arg_name='get_infos',
  1465. arg_index=2,
  1466. default=False,
  1467. if_true=_lu_with_infos,
  1468. if_false=_lu_no_infos,
  1469. module_name=__name__,
  1470. func_name='lu')
  1471. lu.__doc__ = _lu_impl.__doc__
  1472. def align_tensors(*tensors):
  1473. raise RuntimeError('`align_tensors` not yet implemented.')