functional.py 87 KB

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