__init__.py 114 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058
  1. from torch._C import (
  2. _add_docstr,
  3. _linalg, # pyrefly: ignore [missing-module-attribute]
  4. _LinAlgError as LinAlgError, # pyrefly: ignore # missing-module-attribute
  5. )
  6. common_notes = {
  7. "experimental_warning": """This function is "experimental" and it may change in a future PyTorch release.""",
  8. "sync_note": "When inputs are on a CUDA device, this function synchronizes that device with the CPU.",
  9. "sync_note_ex": r"When the inputs are on a CUDA device, this function synchronizes only when :attr:`check_errors`\ `= True`.",
  10. "sync_note_has_ex": (
  11. "When inputs are on a CUDA device, this function synchronizes that device with the CPU. "
  12. "For a version of this function that does not synchronize, see :func:`{}`."
  13. ),
  14. }
  15. # Note: This not only adds doc strings for functions in the linalg namespace, but
  16. # also connects the torch.linalg Python namespace to the torch._C._linalg builtins.
  17. cross = _add_docstr(
  18. _linalg.linalg_cross,
  19. r"""
  20. linalg.cross(input, other, *, dim=-1, out=None) -> Tensor
  21. Computes the cross product of two 3-dimensional vectors.
  22. Supports input of float, double, cfloat and cdouble dtypes. Also supports batches
  23. of vectors, for which it computes the product along the dimension :attr:`dim`.
  24. It broadcasts over the batch dimensions.
  25. Args:
  26. input (Tensor): the first input tensor.
  27. other (Tensor): the second input tensor.
  28. dim (int, optional): the dimension along which to take the cross-product. Default: `-1`.
  29. Keyword args:
  30. out (Tensor, optional): the output tensor. Ignored if `None`. Default: `None`.
  31. Example:
  32. >>> a = torch.randn(4, 3)
  33. >>> a
  34. tensor([[-0.3956, 1.1455, 1.6895],
  35. [-0.5849, 1.3672, 0.3599],
  36. [-1.1626, 0.7180, -0.0521],
  37. [-0.1339, 0.9902, -2.0225]])
  38. >>> b = torch.randn(4, 3)
  39. >>> b
  40. tensor([[-0.0257, -1.4725, -1.2251],
  41. [-1.1479, -0.7005, -1.9757],
  42. [-1.3904, 0.3726, -1.1836],
  43. [-0.9688, -0.7153, 0.2159]])
  44. >>> torch.linalg.cross(a, b)
  45. tensor([[ 1.0844, -0.5281, 0.6120],
  46. [-2.4490, -1.5687, 1.9792],
  47. [-0.8304, -1.3037, 0.5650],
  48. [-1.2329, 1.9883, 1.0551]])
  49. >>> a = torch.randn(1, 3) # a is broadcast to match shape of b
  50. >>> a
  51. tensor([[-0.9941, -0.5132, 0.5681]])
  52. >>> torch.linalg.cross(a, b)
  53. tensor([[ 1.4653, -1.2325, 1.4507],
  54. [ 1.4119, -2.6163, 0.1073],
  55. [ 0.3957, -1.9666, -1.0840],
  56. [ 0.2956, -0.3357, 0.2139]])
  57. """,
  58. )
  59. cholesky = _add_docstr(
  60. _linalg.linalg_cholesky,
  61. r"""
  62. linalg.cholesky(A, *, upper=False, out=None) -> Tensor
  63. Computes the Cholesky decomposition of a complex Hermitian or real symmetric positive-definite matrix.
  64. Letting :math:`\mathbb{K}` be :math:`\mathbb{R}` or :math:`\mathbb{C}`,
  65. the **Cholesky decomposition** of a complex Hermitian or real symmetric positive-definite matrix
  66. :math:`A \in \mathbb{K}^{n \times n}` is defined as
  67. .. math::
  68. A = LL^{\text{H}}\mathrlap{\qquad L \in \mathbb{K}^{n \times n}}
  69. where :math:`L` is a lower triangular matrix with real positive diagonal (even in the complex case) and
  70. :math:`L^{\text{H}}` is the conjugate transpose when :math:`L` is complex, and the transpose when :math:`L` is real-valued.
  71. Supports input of float, double, cfloat and cdouble dtypes.
  72. Also supports batches of matrices, and if :attr:`A` is a batch of matrices then
  73. the output has the same batch dimensions.
  74. """
  75. + rf"""
  76. .. note:: {common_notes["sync_note_has_ex"].format("torch.linalg.cholesky_ex")}
  77. """
  78. + r"""
  79. .. seealso::
  80. :func:`torch.linalg.cholesky_ex` for a version of this operation that
  81. skips the (slow) error checking by default and instead returns the debug
  82. information. This makes it a faster way to check if a matrix is
  83. positive-definite.
  84. :func:`torch.linalg.eigh` for a different decomposition of a Hermitian matrix.
  85. The eigenvalue decomposition gives more information about the matrix but it
  86. slower to compute than the Cholesky decomposition.
  87. Args:
  88. A (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions
  89. consisting of symmetric or Hermitian positive-definite matrices.
  90. Keyword args:
  91. upper (bool, optional): whether to return an upper triangular matrix.
  92. The tensor returned with upper=True is the conjugate transpose of the tensor
  93. returned with upper=False.
  94. out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.
  95. Raises:
  96. RuntimeError: if the :attr:`A` matrix or any matrix in a batched :attr:`A` is not Hermitian
  97. (resp. symmetric) positive-definite. If :attr:`A` is a batch of matrices,
  98. the error message will include the batch index of the first matrix that fails
  99. to meet this condition.
  100. Examples::
  101. >>> A = torch.randn(2, 2, dtype=torch.complex128)
  102. >>> A = A @ A.T.conj() + torch.eye(2) # creates a Hermitian positive-definite matrix
  103. >>> A
  104. tensor([[2.5266+0.0000j, 1.9586-2.0626j],
  105. [1.9586+2.0626j, 9.4160+0.0000j]], dtype=torch.complex128)
  106. >>> L = torch.linalg.cholesky(A)
  107. >>> L
  108. tensor([[1.5895+0.0000j, 0.0000+0.0000j],
  109. [1.2322+1.2976j, 2.4928+0.0000j]], dtype=torch.complex128)
  110. >>> torch.dist(L @ L.T.conj(), A)
  111. tensor(4.4692e-16, dtype=torch.float64)
  112. >>> A = torch.randn(3, 2, 2, dtype=torch.float64)
  113. >>> A = A @ A.mT + torch.eye(2) # batch of symmetric positive-definite matrices
  114. >>> L = torch.linalg.cholesky(A)
  115. >>> torch.dist(L @ L.mT, A)
  116. tensor(5.8747e-16, dtype=torch.float64)
  117. """,
  118. )
  119. cholesky_ex = _add_docstr(
  120. _linalg.linalg_cholesky_ex,
  121. r"""
  122. linalg.cholesky_ex(A, *, upper=False, check_errors=False, out=None) -> (Tensor, Tensor)
  123. Computes the Cholesky decomposition of a complex Hermitian or real
  124. symmetric positive-definite matrix.
  125. This function skips the (slow) error checking and error message construction
  126. of :func:`torch.linalg.cholesky`, instead directly returning the LAPACK
  127. error codes as part of a named tuple ``(L, info)``. This makes this function
  128. a faster way to check if a matrix is positive-definite, and it provides an
  129. opportunity to handle decomposition errors more gracefully or performantly
  130. than :func:`torch.linalg.cholesky` does.
  131. Supports input of float, double, cfloat and cdouble dtypes.
  132. Also supports batches of matrices, and if :attr:`A` is a batch of matrices then
  133. the output has the same batch dimensions.
  134. If :attr:`A` is not a Hermitian positive-definite matrix, or if it's a batch of matrices
  135. and one or more of them is not a Hermitian positive-definite matrix,
  136. then ``info`` stores a positive integer for the corresponding matrix.
  137. The positive integer indicates the order of the leading minor that is not positive-definite,
  138. and the decomposition could not be completed.
  139. ``info`` filled with zeros indicates that the decomposition was successful.
  140. If ``check_errors=True`` and ``info`` contains positive integers, then a RuntimeError is thrown.
  141. """
  142. + rf"""
  143. .. note:: {common_notes["sync_note_ex"]}
  144. .. warning:: {common_notes["experimental_warning"]}
  145. """
  146. + r"""
  147. .. seealso::
  148. :func:`torch.linalg.cholesky` is a NumPy compatible variant that always checks for errors.
  149. Args:
  150. A (Tensor): the Hermitian `n \times n` matrix or the batch of such matrices of size
  151. `(*, n, n)` where `*` is one or more batch dimensions.
  152. Keyword args:
  153. upper (bool, optional): whether to return an upper triangular matrix.
  154. The tensor returned with upper=True is the conjugate transpose of the tensor
  155. returned with upper=False.
  156. check_errors (bool, optional): controls whether to check the content of ``infos``. Default: `False`.
  157. out (tuple, optional): tuple of two tensors to write the output to. Ignored if `None`. Default: `None`.
  158. Examples::
  159. >>> A = torch.randn(2, 2, dtype=torch.complex128)
  160. >>> A = A @ A.t().conj() # creates a Hermitian positive-definite matrix
  161. >>> L, info = torch.linalg.cholesky_ex(A)
  162. >>> A
  163. tensor([[ 2.3792+0.0000j, -0.9023+0.9831j],
  164. [-0.9023-0.9831j, 0.8757+0.0000j]], dtype=torch.complex128)
  165. >>> L
  166. tensor([[ 1.5425+0.0000j, 0.0000+0.0000j],
  167. [-0.5850-0.6374j, 0.3567+0.0000j]], dtype=torch.complex128)
  168. >>> info
  169. tensor(0, dtype=torch.int32)
  170. """,
  171. )
  172. inv = _add_docstr(
  173. _linalg.linalg_inv,
  174. r"""
  175. linalg.inv(A, *, out=None) -> Tensor
  176. Computes the inverse of a square matrix if it exists.
  177. Throws a `RuntimeError` if the matrix is not invertible.
  178. Letting :math:`\mathbb{K}` be :math:`\mathbb{R}` or :math:`\mathbb{C}`,
  179. for a matrix :math:`A \in \mathbb{K}^{n \times n}`,
  180. its **inverse matrix** :math:`A^{-1} \in \mathbb{K}^{n \times n}` (if it exists) is defined as
  181. .. math::
  182. A^{-1}A = AA^{-1} = \mathrm{I}_n
  183. where :math:`\mathrm{I}_n` is the `n`-dimensional identity matrix.
  184. The inverse matrix exists if and only if :math:`A` is `invertible`_. In this case,
  185. the inverse is unique.
  186. Supports input of float, double, cfloat and cdouble dtypes.
  187. Also supports batches of matrices, and if :attr:`A` is a batch of matrices
  188. then the output has the same batch dimensions.
  189. """
  190. + rf"""
  191. .. note:: {common_notes["sync_note_has_ex"].format("torch.linalg.inv_ex")}
  192. """
  193. + r"""
  194. .. note::
  195. Consider using :func:`torch.linalg.solve` if possible for multiplying a matrix on the left by
  196. the inverse, as::
  197. linalg.solve(A, B) == linalg.inv(A) @ B # When B is a matrix
  198. It is always preferred to use :func:`~solve` when possible, as it is faster and more
  199. numerically stable than computing the inverse explicitly.
  200. .. seealso::
  201. :func:`torch.linalg.pinv` computes the pseudoinverse (Moore-Penrose inverse) of matrices
  202. of any shape.
  203. :func:`torch.linalg.solve` computes :attr:`A`\ `.inv() @ \ `:attr:`B` with a
  204. numerically stable algorithm.
  205. Args:
  206. A (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions
  207. consisting of invertible matrices.
  208. Keyword args:
  209. out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.
  210. Raises:
  211. RuntimeError: if the matrix :attr:`A` or any matrix in the batch of matrices :attr:`A` is not invertible.
  212. Examples::
  213. >>> A = torch.randn(4, 4)
  214. >>> Ainv = torch.linalg.inv(A)
  215. >>> torch.dist(A @ Ainv, torch.eye(4))
  216. tensor(1.1921e-07)
  217. >>> A = torch.randn(2, 3, 4, 4) # Batch of matrices
  218. >>> Ainv = torch.linalg.inv(A)
  219. >>> torch.dist(A @ Ainv, torch.eye(4))
  220. tensor(1.9073e-06)
  221. >>> A = torch.randn(4, 4, dtype=torch.complex128) # Complex matrix
  222. >>> Ainv = torch.linalg.inv(A)
  223. >>> torch.dist(A @ Ainv, torch.eye(4))
  224. tensor(7.5107e-16, dtype=torch.float64)
  225. .. _invertible:
  226. https://en.wikipedia.org/wiki/Invertible_matrix#The_invertible_matrix_theorem
  227. """,
  228. )
  229. solve_ex = _add_docstr(
  230. _linalg.linalg_solve_ex,
  231. r"""
  232. linalg.solve_ex(A, B, *, left=True, check_errors=False, out=None) -> (Tensor, Tensor)
  233. A version of :func:`~solve` that does not perform error checks unless :attr:`check_errors`\ `= True`.
  234. It also returns the :attr:`info` tensor returned by `LAPACK's getrf`_.
  235. """
  236. + rf"""
  237. .. note:: {common_notes["sync_note_ex"]}
  238. .. warning:: {common_notes["experimental_warning"]}
  239. """
  240. + r"""
  241. Args:
  242. A (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions.
  243. Keyword args:
  244. left (bool, optional): whether to solve the system :math:`AX=B` or :math:`XA = B`. Default: `True`.
  245. check_errors (bool, optional): controls whether to check the content of ``infos`` and raise
  246. an error if it is non-zero. Default: `False`.
  247. out (tuple, optional): tuple of two tensors to write the output to. Ignored if `None`. Default: `None`.
  248. Returns:
  249. A named tuple `(result, info)`.
  250. Examples::
  251. >>> A = torch.randn(3, 3)
  252. >>> Ainv, info = torch.linalg.solve_ex(A)
  253. >>> torch.dist(torch.linalg.inv(A), Ainv)
  254. tensor(0.)
  255. >>> info
  256. tensor(0, dtype=torch.int32)
  257. .. _LAPACK's getrf:
  258. https://www.netlib.org/lapack/explore-html-3.6.1/dd/d9a/group__double_g_ecomputational_ga0019443faea08275ca60a734d0593e60.html
  259. """,
  260. )
  261. inv_ex = _add_docstr(
  262. _linalg.linalg_inv_ex,
  263. r"""
  264. linalg.inv_ex(A, *, check_errors=False, out=None) -> (Tensor, Tensor)
  265. Computes the inverse of a square matrix if it is invertible.
  266. Returns a namedtuple ``(inverse, info)``. ``inverse`` contains the result of
  267. inverting :attr:`A` and ``info`` stores the LAPACK error codes.
  268. If :attr:`A` is not an invertible matrix, or if it's a batch of matrices
  269. and one or more of them is not an invertible matrix,
  270. then ``info`` stores a positive integer for the corresponding matrix.
  271. The positive integer indicates the diagonal element of the LU decomposition of
  272. the input matrix that is exactly zero.
  273. ``info`` filled with zeros indicates that the inversion was successful.
  274. If ``check_errors=True`` and ``info`` contains positive integers, then a RuntimeError is thrown.
  275. Supports input of float, double, cfloat and cdouble dtypes.
  276. Also supports batches of matrices, and if :attr:`A` is a batch of matrices then
  277. the output has the same batch dimensions.
  278. """
  279. + rf"""
  280. .. note:: {common_notes["sync_note_ex"]}
  281. .. warning:: {common_notes["experimental_warning"]}
  282. """
  283. + r"""
  284. .. seealso::
  285. :func:`torch.linalg.inv` is a NumPy compatible variant that always checks for errors.
  286. Args:
  287. A (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions
  288. consisting of square matrices.
  289. check_errors (bool, optional): controls whether to check the content of ``info``. Default: `False`.
  290. Keyword args:
  291. out (tuple, optional): tuple of two tensors to write the output to. Ignored if `None`. Default: `None`.
  292. Examples::
  293. >>> A = torch.randn(3, 3)
  294. >>> Ainv, info = torch.linalg.inv_ex(A)
  295. >>> torch.dist(torch.linalg.inv(A), Ainv)
  296. tensor(0.)
  297. >>> info
  298. tensor(0, dtype=torch.int32)
  299. """,
  300. )
  301. det = _add_docstr(
  302. _linalg.linalg_det,
  303. r"""
  304. linalg.det(A, *, out=None) -> Tensor
  305. Computes the determinant of a square matrix.
  306. Supports input of float, double, cfloat and cdouble dtypes.
  307. Also supports batches of matrices, and if :attr:`A` is a batch of matrices then
  308. the output has the same batch dimensions.
  309. .. seealso::
  310. :func:`torch.linalg.slogdet` computes the sign and natural logarithm of the absolute
  311. value of the determinant of square matrices.
  312. Args:
  313. A (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions.
  314. Keyword args:
  315. out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.
  316. Examples::
  317. >>> A = torch.randn(3, 3)
  318. >>> torch.linalg.det(A)
  319. tensor(0.0934)
  320. >>> A = torch.randn(3, 2, 2)
  321. >>> torch.linalg.det(A)
  322. tensor([1.1990, 0.4099, 0.7386])
  323. """,
  324. )
  325. slogdet = _add_docstr(
  326. _linalg.linalg_slogdet,
  327. r"""
  328. linalg.slogdet(A, *, out=None) -> (Tensor, Tensor)
  329. Computes the sign and natural logarithm of the absolute value of the determinant of a square matrix.
  330. For complex :attr:`A`, it returns the sign and the natural logarithm of the modulus of the
  331. determinant, that is, a logarithmic polar decomposition of the determinant.
  332. The determinant can be recovered as `sign * exp(logabsdet)`.
  333. When a matrix has a determinant of zero, it returns `(0, -inf)`.
  334. Supports input of float, double, cfloat and cdouble dtypes.
  335. Also supports batches of matrices, and if :attr:`A` is a batch of matrices then
  336. the output has the same batch dimensions.
  337. .. seealso::
  338. :func:`torch.linalg.det` computes the determinant of square matrices.
  339. Args:
  340. A (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions.
  341. Keyword args:
  342. out (tuple, optional): output tuple of two tensors. Ignored if `None`. Default: `None`.
  343. Returns:
  344. A named tuple `(sign, logabsdet)`.
  345. `sign` will have the same dtype as :attr:`A`.
  346. `logabsdet` will always be real-valued, even when :attr:`A` is complex.
  347. Examples::
  348. >>> A = torch.randn(3, 3)
  349. >>> A
  350. tensor([[ 0.0032, -0.2239, -1.1219],
  351. [-0.6690, 0.1161, 0.4053],
  352. [-1.6218, -0.9273, -0.0082]])
  353. >>> torch.linalg.det(A)
  354. tensor(-0.7576)
  355. >>> torch.logdet(A)
  356. tensor(nan)
  357. >>> torch.linalg.slogdet(A)
  358. torch.return_types.linalg_slogdet(sign=tensor(-1.), logabsdet=tensor(-0.2776))
  359. """,
  360. )
  361. eig = _add_docstr(
  362. _linalg.linalg_eig,
  363. r"""
  364. linalg.eig(A, *, out=None) -> (Tensor, Tensor)
  365. Computes the eigenvalue decomposition of a square matrix if it exists.
  366. Letting :math:`\mathbb{K}` be :math:`\mathbb{R}` or :math:`\mathbb{C}`,
  367. the **eigenvalue decomposition** of a square matrix
  368. :math:`A \in \mathbb{K}^{n \times n}` (if it exists) is defined as
  369. .. math::
  370. A = V \operatorname{diag}(\Lambda) V^{-1}\mathrlap{\qquad V \in \mathbb{C}^{n \times n}, \Lambda \in \mathbb{C}^n}
  371. This decomposition exists if and only if :math:`A` is `diagonalizable`_.
  372. This is the case when all its eigenvalues are different.
  373. Supports input of float, double, cfloat and cdouble dtypes.
  374. Also supports batches of matrices, and if :attr:`A` is a batch of matrices then
  375. the output has the same batch dimensions.
  376. The returned eigenvalues are not guaranteed to be in any specific order.
  377. .. note:: The eigenvalues and eigenvectors of a real matrix may be complex.
  378. """
  379. + rf"""
  380. .. note:: {common_notes["sync_note"]}
  381. """
  382. + r"""
  383. .. warning:: This function assumes that :attr:`A` is `diagonalizable`_ (for example, when all the
  384. eigenvalues are different). If it is not diagonalizable, the returned
  385. eigenvalues will be correct but :math:`A \neq V \operatorname{diag}(\Lambda)V^{-1}`.
  386. .. warning:: The returned eigenvectors are normalized to have norm `1`.
  387. Even then, the eigenvectors of a matrix are not unique, nor are they continuous with respect to
  388. :attr:`A`. Due to this lack of uniqueness, different hardware and software may compute
  389. different eigenvectors.
  390. This non-uniqueness is caused by the fact that multiplying an eigenvector by
  391. by :math:`e^{i \phi}, \phi \in \mathbb{R}` produces another set of valid eigenvectors
  392. of the matrix. For this reason, the loss function shall not depend on the phase of the
  393. eigenvectors, as this quantity is not well-defined.
  394. This is checked when computing the gradients of this function. As such,
  395. when inputs are on a CUDA device, the computation of the gradients
  396. of this function synchronizes that device with the CPU.
  397. .. warning:: Gradients computed using the `eigenvectors` tensor will only be finite when
  398. :attr:`A` has distinct eigenvalues.
  399. Furthermore, if the distance between any two eigenvalues is close to zero,
  400. the gradient will be numerically unstable, as it depends on the eigenvalues
  401. :math:`\lambda_i` through the computation of
  402. :math:`\frac{1}{\min_{i \neq j} \lambda_i - \lambda_j}`.
  403. .. seealso::
  404. :func:`torch.linalg.eigvals` computes only the eigenvalues.
  405. Unlike :func:`torch.linalg.eig`, the gradients of :func:`~eigvals` are always
  406. numerically stable.
  407. :func:`torch.linalg.eigh` for a (faster) function that computes the eigenvalue decomposition
  408. for Hermitian and symmetric matrices.
  409. :func:`torch.linalg.svd` for a function that computes another type of spectral
  410. decomposition that works on matrices of any shape.
  411. :func:`torch.linalg.qr` for another (much faster) decomposition that works on matrices of
  412. any shape.
  413. Args:
  414. A (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions
  415. consisting of diagonalizable matrices.
  416. Keyword args:
  417. out (tuple, optional): output tuple of two tensors. Ignored if `None`. Default: `None`.
  418. Returns:
  419. A named tuple `(eigenvalues, eigenvectors)` which corresponds to :math:`\Lambda` and :math:`V` above.
  420. `eigenvalues` and `eigenvectors` will always be complex-valued, even when :attr:`A` is real. The eigenvectors
  421. will be given by the columns of `eigenvectors`.
  422. Examples::
  423. >>> A = torch.randn(2, 2, dtype=torch.complex128)
  424. >>> A
  425. tensor([[ 0.9828+0.3889j, -0.4617+0.3010j],
  426. [ 0.1662-0.7435j, -0.6139+0.0562j]], dtype=torch.complex128)
  427. >>> L, V = torch.linalg.eig(A)
  428. >>> L
  429. tensor([ 1.1226+0.5738j, -0.7537-0.1286j], dtype=torch.complex128)
  430. >>> V
  431. tensor([[ 0.9218+0.0000j, 0.1882-0.2220j],
  432. [-0.0270-0.3867j, 0.9567+0.0000j]], dtype=torch.complex128)
  433. >>> torch.dist(V @ torch.diag(L) @ torch.linalg.inv(V), A)
  434. tensor(7.7119e-16, dtype=torch.float64)
  435. >>> A = torch.randn(3, 2, 2, dtype=torch.float64)
  436. >>> L, V = torch.linalg.eig(A)
  437. >>> torch.dist(V @ torch.diag_embed(L) @ torch.linalg.inv(V), A)
  438. tensor(3.2841e-16, dtype=torch.float64)
  439. .. _diagonalizable:
  440. https://en.wikipedia.org/wiki/Diagonalizable_matrix#Definition
  441. """,
  442. )
  443. eigvals = _add_docstr(
  444. _linalg.linalg_eigvals,
  445. r"""
  446. linalg.eigvals(A, *, out=None) -> Tensor
  447. Computes the eigenvalues of a square matrix.
  448. Letting :math:`\mathbb{K}` be :math:`\mathbb{R}` or :math:`\mathbb{C}`,
  449. the **eigenvalues** of a square matrix :math:`A \in \mathbb{K}^{n \times n}` are defined
  450. as the roots (counted with multiplicity) of the polynomial `p` of degree `n` given by
  451. .. math::
  452. p(\lambda) = \operatorname{det}(A - \lambda \mathrm{I}_n)\mathrlap{\qquad \lambda \in \mathbb{C}}
  453. where :math:`\mathrm{I}_n` is the `n`-dimensional identity matrix.
  454. Supports input of float, double, cfloat and cdouble dtypes.
  455. Also supports batches of matrices, and if :attr:`A` is a batch of matrices then
  456. the output has the same batch dimensions.
  457. The returned eigenvalues are not guaranteed to be in any specific order.
  458. .. note:: The eigenvalues of a real matrix may be complex, as the roots of a real polynomial may be complex.
  459. The eigenvalues of a matrix are always well-defined, even when the matrix is not diagonalizable.
  460. """
  461. + rf"""
  462. .. note:: {common_notes["sync_note"]}
  463. """
  464. + r"""
  465. .. seealso::
  466. :func:`torch.linalg.eig` computes the full eigenvalue decomposition.
  467. Args:
  468. A (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions.
  469. Keyword args:
  470. out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.
  471. Returns:
  472. A complex-valued tensor containing the eigenvalues even when :attr:`A` is real.
  473. Examples::
  474. >>> A = torch.randn(2, 2, dtype=torch.complex128)
  475. >>> L = torch.linalg.eigvals(A)
  476. >>> L
  477. tensor([ 1.1226+0.5738j, -0.7537-0.1286j], dtype=torch.complex128)
  478. >>> torch.dist(L, torch.linalg.eig(A).eigenvalues)
  479. tensor(2.4576e-07)
  480. """,
  481. )
  482. eigh = _add_docstr(
  483. _linalg.linalg_eigh,
  484. r"""
  485. linalg.eigh(A, UPLO='L', *, out=None) -> (Tensor, Tensor)
  486. Computes the eigenvalue decomposition of a complex Hermitian or real symmetric matrix.
  487. Letting :math:`\mathbb{K}` be :math:`\mathbb{R}` or :math:`\mathbb{C}`,
  488. the **eigenvalue decomposition** of a complex Hermitian or real symmetric matrix
  489. :math:`A \in \mathbb{K}^{n \times n}` is defined as
  490. .. math::
  491. A = Q \operatorname{diag}(\Lambda) Q^{\text{H}}\mathrlap{\qquad Q \in \mathbb{K}^{n \times n}, \Lambda \in \mathbb{R}^n}
  492. where :math:`Q^{\text{H}}` is the conjugate transpose when :math:`Q` is complex, and the transpose when :math:`Q` is real-valued.
  493. :math:`Q` is orthogonal in the real case and unitary in the complex case.
  494. Supports input of float, double, cfloat and cdouble dtypes.
  495. Also supports batches of matrices, and if :attr:`A` is a batch of matrices then
  496. the output has the same batch dimensions.
  497. :attr:`A` is assumed to be Hermitian (resp. symmetric), but this is not checked internally, instead:
  498. - If :attr:`UPLO`\ `= 'L'` (default), only the lower triangular part of the matrix is used in the computation.
  499. - If :attr:`UPLO`\ `= 'U'`, only the upper triangular part of the matrix is used.
  500. The eigenvalues are returned in ascending order.
  501. """
  502. + rf"""
  503. .. note:: {common_notes["sync_note"]}
  504. """
  505. + r"""
  506. .. note:: The eigenvalues of real symmetric or complex Hermitian matrices are always real.
  507. .. warning:: The eigenvectors of a symmetric matrix are not unique, nor are they continuous with
  508. respect to :attr:`A`. Due to this lack of uniqueness, different hardware and
  509. software may compute different eigenvectors.
  510. This non-uniqueness is caused by the fact that multiplying an eigenvector by
  511. `-1` in the real case or by :math:`e^{i \phi}, \phi \in \mathbb{R}` in the complex
  512. case produces another set of valid eigenvectors of the matrix.
  513. For this reason, the loss function shall not depend on the phase of the eigenvectors, as
  514. this quantity is not well-defined.
  515. This is checked for complex inputs when computing the gradients of this function. As such,
  516. when inputs are complex and are on a CUDA device, the computation of the gradients
  517. of this function synchronizes that device with the CPU.
  518. .. warning:: Gradients computed using the `eigenvectors` tensor will only be finite when
  519. :attr:`A` has distinct eigenvalues.
  520. Furthermore, if the distance between any two eigenvalues is close to zero,
  521. the gradient will be numerically unstable, as it depends on the eigenvalues
  522. :math:`\lambda_i` through the computation of
  523. :math:`\frac{1}{\min_{i \neq j} \lambda_i - \lambda_j}`.
  524. .. warning:: User may see pytorch crashes if running `eigh` on CUDA devices with CUDA versions before 12.1 update 1
  525. with large ill-conditioned matrices as inputs.
  526. Refer to :ref:`Linear Algebra Numerical Stability<Linear Algebra Stability>` for more details.
  527. If this is the case, user may (1) tune their matrix inputs to be less ill-conditioned,
  528. or (2) use :func:`torch.backends.cuda.preferred_linalg_library` to
  529. try other supported backends.
  530. .. seealso::
  531. :func:`torch.linalg.eigvalsh` computes only the eigenvalues of a Hermitian matrix.
  532. Unlike :func:`torch.linalg.eigh`, the gradients of :func:`~eigvalsh` are always
  533. numerically stable.
  534. :func:`torch.linalg.cholesky` for a different decomposition of a Hermitian matrix.
  535. The Cholesky decomposition gives less information about the matrix but is much faster
  536. to compute than the eigenvalue decomposition.
  537. :func:`torch.linalg.eig` for a (slower) function that computes the eigenvalue decomposition
  538. of a not necessarily Hermitian square matrix.
  539. :func:`torch.linalg.svd` for a (slower) function that computes the more general SVD
  540. decomposition of matrices of any shape.
  541. :func:`torch.linalg.qr` for another (much faster) decomposition that works on general
  542. matrices.
  543. Args:
  544. A (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions
  545. consisting of symmetric or Hermitian matrices.
  546. UPLO ('L', 'U', optional): controls whether to use the upper or lower triangular part
  547. of :attr:`A` in the computations. Default: `'L'`.
  548. Keyword args:
  549. out (tuple, optional): output tuple of two tensors. Ignored if `None`. Default: `None`.
  550. Returns:
  551. A named tuple `(eigenvalues, eigenvectors)` which corresponds to :math:`\Lambda` and :math:`Q` above.
  552. `eigenvalues` will always be real-valued, even when :attr:`A` is complex.
  553. It will also be ordered in ascending order.
  554. `eigenvectors` will have the same dtype as :attr:`A` and will contain the eigenvectors as its columns.
  555. Examples::
  556. >>> A = torch.randn(2, 2, dtype=torch.complex128)
  557. >>> A = A + A.T.conj() # creates a Hermitian matrix
  558. >>> A
  559. tensor([[2.9228+0.0000j, 0.2029-0.0862j],
  560. [0.2029+0.0862j, 0.3464+0.0000j]], dtype=torch.complex128)
  561. >>> L, Q = torch.linalg.eigh(A)
  562. >>> L
  563. tensor([0.3277, 2.9415], dtype=torch.float64)
  564. >>> Q
  565. tensor([[-0.0846+-0.0000j, -0.9964+0.0000j],
  566. [ 0.9170+0.3898j, -0.0779-0.0331j]], dtype=torch.complex128)
  567. >>> torch.dist(Q @ torch.diag(L.cdouble()) @ Q.T.conj(), A)
  568. tensor(6.1062e-16, dtype=torch.float64)
  569. >>> A = torch.randn(3, 2, 2, dtype=torch.float64)
  570. >>> A = A + A.mT # creates a batch of symmetric matrices
  571. >>> L, Q = torch.linalg.eigh(A)
  572. >>> torch.dist(Q @ torch.diag_embed(L) @ Q.mH, A)
  573. tensor(1.5423e-15, dtype=torch.float64)
  574. """,
  575. )
  576. eigvalsh = _add_docstr(
  577. _linalg.linalg_eigvalsh,
  578. r"""
  579. linalg.eigvalsh(A, UPLO='L', *, out=None) -> Tensor
  580. Computes the eigenvalues of a complex Hermitian or real symmetric matrix.
  581. Letting :math:`\mathbb{K}` be :math:`\mathbb{R}` or :math:`\mathbb{C}`,
  582. the **eigenvalues** of a complex Hermitian or real symmetric matrix :math:`A \in \mathbb{K}^{n \times n}`
  583. are defined as the roots (counted with multiplicity) of the polynomial `p` of degree `n` given by
  584. .. math::
  585. p(\lambda) = \operatorname{det}(A - \lambda \mathrm{I}_n)\mathrlap{\qquad \lambda \in \mathbb{R}}
  586. where :math:`\mathrm{I}_n` is the `n`-dimensional identity matrix.
  587. The eigenvalues of a real symmetric or complex Hermitian matrix are always real.
  588. Supports input of float, double, cfloat and cdouble dtypes.
  589. Also supports batches of matrices, and if :attr:`A` is a batch of matrices then
  590. the output has the same batch dimensions.
  591. The eigenvalues are returned in ascending order.
  592. :attr:`A` is assumed to be Hermitian (resp. symmetric), but this is not checked internally, instead:
  593. - If :attr:`UPLO`\ `= 'L'` (default), only the lower triangular part of the matrix is used in the computation.
  594. - If :attr:`UPLO`\ `= 'U'`, only the upper triangular part of the matrix is used.
  595. """
  596. + rf"""
  597. .. note:: {common_notes["sync_note"]}
  598. """
  599. + r"""
  600. .. seealso::
  601. :func:`torch.linalg.eigh` computes the full eigenvalue decomposition.
  602. Args:
  603. A (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions
  604. consisting of symmetric or Hermitian matrices.
  605. UPLO ('L', 'U', optional): controls whether to use the upper or lower triangular part
  606. of :attr:`A` in the computations. Default: `'L'`.
  607. Keyword args:
  608. out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.
  609. Returns:
  610. A real-valued tensor containing the eigenvalues even when :attr:`A` is complex.
  611. The eigenvalues are returned in ascending order.
  612. Examples::
  613. >>> A = torch.randn(2, 2, dtype=torch.complex128)
  614. >>> A = A + A.T.conj() # creates a Hermitian matrix
  615. >>> A
  616. tensor([[2.9228+0.0000j, 0.2029-0.0862j],
  617. [0.2029+0.0862j, 0.3464+0.0000j]], dtype=torch.complex128)
  618. >>> torch.linalg.eigvalsh(A)
  619. tensor([0.3277, 2.9415], dtype=torch.float64)
  620. >>> A = torch.randn(3, 2, 2, dtype=torch.float64)
  621. >>> A = A + A.mT # creates a batch of symmetric matrices
  622. >>> torch.linalg.eigvalsh(A)
  623. tensor([[ 2.5797, 3.4629],
  624. [-4.1605, 1.3780],
  625. [-3.1113, 2.7381]], dtype=torch.float64)
  626. """,
  627. )
  628. householder_product = _add_docstr(
  629. _linalg.linalg_householder_product,
  630. r"""
  631. householder_product(A, tau, *, out=None) -> Tensor
  632. Computes the first `n` columns of a product of Householder matrices.
  633. Let :math:`\mathbb{K}` be :math:`\mathbb{R}` or :math:`\mathbb{C}`, and
  634. let :math:`A \in \mathbb{K}^{m \times n}` be a matrix with columns :math:`a_i \in \mathbb{K}^m`
  635. for :math:`i=1,\ldots,m` with :math:`m \geq n`. Denote by :math:`b_i` the vector resulting from
  636. zeroing out the first :math:`i-1` components of :math:`a_i` and setting to `1` the :math:`i`-th.
  637. For a vector :math:`\tau \in \mathbb{K}^k` with :math:`k \leq n`, this function computes the
  638. first :math:`n` columns of the matrix
  639. .. math::
  640. H_1H_2 ... H_k \qquad\text{with}\qquad H_i = \mathrm{I}_m - \tau_i b_i b_i^{\text{H}}
  641. where :math:`\mathrm{I}_m` is the `m`-dimensional identity matrix and :math:`b^{\text{H}}` is the
  642. conjugate transpose when :math:`b` is complex, and the transpose when :math:`b` is real-valued.
  643. The output matrix is the same size as the input matrix :attr:`A`.
  644. See `Representation of Orthogonal or Unitary Matrices`_ for further details.
  645. Supports inputs of float, double, cfloat and cdouble dtypes.
  646. Also supports batches of matrices, and if the inputs are batches of matrices then
  647. the output has the same batch dimensions.
  648. .. seealso::
  649. :func:`torch.geqrf` can be used together with this function to form the `Q` from the
  650. :func:`~qr` decomposition.
  651. :func:`torch.ormqr` is a related function that computes the matrix multiplication
  652. of a product of Householder matrices with another matrix.
  653. However, that function is not supported by autograd.
  654. .. warning::
  655. Gradient computations are only well-defined if :math:`\tau_i \neq \frac{1}{||a_i||^2}`.
  656. If this condition is not met, no error will be thrown, but the gradient produced may contain `NaN`.
  657. Args:
  658. A (Tensor): tensor of shape `(*, m, n)` where `*` is zero or more batch dimensions.
  659. tau (Tensor): tensor of shape `(*, k)` where `*` is zero or more batch dimensions.
  660. Keyword args:
  661. out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.
  662. Raises:
  663. RuntimeError: if :attr:`A` doesn't satisfy the requirement `m >= n`,
  664. or :attr:`tau` doesn't satisfy the requirement `n >= k`.
  665. Examples::
  666. >>> A = torch.randn(2, 2)
  667. >>> h, tau = torch.geqrf(A)
  668. >>> Q = torch.linalg.householder_product(h, tau)
  669. >>> torch.dist(Q, torch.linalg.qr(A).Q)
  670. tensor(0.)
  671. >>> h = torch.randn(3, 2, 2, dtype=torch.complex128)
  672. >>> tau = torch.randn(3, 1, dtype=torch.complex128)
  673. >>> Q = torch.linalg.householder_product(h, tau)
  674. >>> Q
  675. tensor([[[ 1.8034+0.4184j, 0.2588-1.0174j],
  676. [-0.6853+0.7953j, 2.0790+0.5620j]],
  677. [[ 1.4581+1.6989j, -1.5360+0.1193j],
  678. [ 1.3877-0.6691j, 1.3512+1.3024j]],
  679. [[ 1.4766+0.5783j, 0.0361+0.6587j],
  680. [ 0.6396+0.1612j, 1.3693+0.4481j]]], dtype=torch.complex128)
  681. .. _Representation of Orthogonal or Unitary Matrices:
  682. https://www.netlib.org/lapack/lug/node128.html
  683. """,
  684. )
  685. ldl_factor = _add_docstr(
  686. _linalg.linalg_ldl_factor,
  687. r"""
  688. linalg.ldl_factor(A, *, hermitian=False, out=None) -> (Tensor, Tensor)
  689. Computes a compact representation of the LDL factorization of a Hermitian or symmetric (possibly indefinite) matrix.
  690. When :attr:`A` is complex valued it can be Hermitian (:attr:`hermitian`\ `= True`)
  691. or symmetric (:attr:`hermitian`\ `= False`).
  692. The factorization is of the form the form :math:`A = L D L^T`.
  693. If :attr:`hermitian` is `True` then transpose operation is the conjugate transpose.
  694. :math:`L` (or :math:`U`) and :math:`D` are stored in compact form in ``LD``.
  695. They follow the format specified by `LAPACK's sytrf`_ function.
  696. These tensors may be used in :func:`torch.linalg.ldl_solve` to solve linear systems.
  697. Supports input of float, double, cfloat and cdouble dtypes.
  698. Also supports batches of matrices, and if :attr:`A` is a batch of matrices then
  699. the output has the same batch dimensions.
  700. """
  701. + rf"""
  702. .. note:: {common_notes["sync_note_has_ex"].format("torch.linalg.ldl_factor_ex")}
  703. """
  704. + r"""
  705. Args:
  706. A (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions
  707. consisting of symmetric or Hermitian matrices.
  708. Keyword args:
  709. hermitian (bool, optional): whether to consider the input to be Hermitian or symmetric.
  710. For real-valued matrices, this switch has no effect. Default: `False`.
  711. out (tuple, optional): tuple of two tensors to write the output to. Ignored if `None`. Default: `None`.
  712. Returns:
  713. A named tuple `(LD, pivots)`.
  714. Examples::
  715. >>> A = torch.randn(3, 3)
  716. >>> A = A @ A.mT # make symmetric
  717. >>> A
  718. tensor([[7.2079, 4.2414, 1.9428],
  719. [4.2414, 3.4554, 0.3264],
  720. [1.9428, 0.3264, 1.3823]])
  721. >>> LD, pivots = torch.linalg.ldl_factor(A)
  722. >>> LD
  723. tensor([[ 7.2079, 0.0000, 0.0000],
  724. [ 0.5884, 0.9595, 0.0000],
  725. [ 0.2695, -0.8513, 0.1633]])
  726. >>> pivots
  727. tensor([1, 2, 3], dtype=torch.int32)
  728. .. _LAPACK's sytrf:
  729. https://www.netlib.org/lapack/explore-html-3.6.1/d3/db6/group__double_s_ycomputational_gad91bde1212277b3e909eb6af7f64858a.html
  730. """,
  731. )
  732. ldl_factor_ex = _add_docstr(
  733. _linalg.linalg_ldl_factor_ex,
  734. r"""
  735. linalg.ldl_factor_ex(A, *, hermitian=False, check_errors=False, out=None) -> (Tensor, Tensor, Tensor)
  736. This is a version of :func:`~ldl_factor` that does not perform error checks unless :attr:`check_errors`\ `= True`.
  737. It also returns the :attr:`info` tensor returned by `LAPACK's sytrf`_.
  738. ``info`` stores integer error codes from the backend library.
  739. A positive integer indicates the diagonal element of :math:`D` that is zero.
  740. Division by 0 will occur if the result is used for solving a system of linear equations.
  741. ``info`` filled with zeros indicates that the factorization was successful.
  742. If ``check_errors=True`` and ``info`` contains positive integers, then a `RuntimeError` is thrown.
  743. """
  744. + rf"""
  745. .. note:: {common_notes["sync_note_ex"]}
  746. .. warning:: {common_notes["experimental_warning"]}
  747. """
  748. + r"""
  749. Args:
  750. A (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions
  751. consisting of symmetric or Hermitian matrices.
  752. Keyword args:
  753. hermitian (bool, optional): whether to consider the input to be Hermitian or symmetric.
  754. For real-valued matrices, this switch has no effect. Default: `False`.
  755. check_errors (bool, optional): controls whether to check the content of ``info`` and raise
  756. an error if it is non-zero. Default: `False`.
  757. out (tuple, optional): tuple of three tensors to write the output to. Ignored if `None`. Default: `None`.
  758. Returns:
  759. A named tuple `(LD, pivots, info)`.
  760. Examples::
  761. >>> A = torch.randn(3, 3)
  762. >>> A = A @ A.mT # make symmetric
  763. >>> A
  764. tensor([[7.2079, 4.2414, 1.9428],
  765. [4.2414, 3.4554, 0.3264],
  766. [1.9428, 0.3264, 1.3823]])
  767. >>> LD, pivots, info = torch.linalg.ldl_factor_ex(A)
  768. >>> LD
  769. tensor([[ 7.2079, 0.0000, 0.0000],
  770. [ 0.5884, 0.9595, 0.0000],
  771. [ 0.2695, -0.8513, 0.1633]])
  772. >>> pivots
  773. tensor([1, 2, 3], dtype=torch.int32)
  774. >>> info
  775. tensor(0, dtype=torch.int32)
  776. .. _LAPACK's sytrf:
  777. https://www.netlib.org/lapack/explore-html-3.6.1/d3/db6/group__double_s_ycomputational_gad91bde1212277b3e909eb6af7f64858a.html
  778. """,
  779. )
  780. ldl_solve = _add_docstr(
  781. _linalg.linalg_ldl_solve,
  782. r"""
  783. linalg.ldl_solve(LD, pivots, B, *, hermitian=False, out=None) -> Tensor
  784. Computes the solution of a system of linear equations using the LDL factorization.
  785. :attr:`LD` and :attr:`pivots` are the compact representation of the LDL factorization and
  786. are expected to be computed by :func:`torch.linalg.ldl_factor_ex`.
  787. :attr:`hermitian` argument to this function should be the same
  788. as the corresponding arguments in :func:`torch.linalg.ldl_factor_ex`.
  789. Supports input of float, double, cfloat and cdouble dtypes.
  790. Also supports batches of matrices, and if :attr:`A` is a batch of matrices then
  791. the output has the same batch dimensions.
  792. """
  793. + rf"""
  794. .. warning:: {common_notes["experimental_warning"]}
  795. """
  796. + r"""
  797. Args:
  798. LD (Tensor): the `n \times n` matrix or the batch of such matrices of size
  799. `(*, n, n)` where `*` is one or more batch dimensions.
  800. pivots (Tensor): the pivots corresponding to the LDL factorization of :attr:`LD`.
  801. B (Tensor): right-hand side tensor of shape `(*, n, k)`.
  802. Keyword args:
  803. hermitian (bool, optional): whether to consider the decomposed matrix to be Hermitian or symmetric.
  804. For real-valued matrices, this switch has no effect. Default: `False`.
  805. out (tuple, optional): output tensor. `B` may be passed as `out` and the result is computed in-place on `B`.
  806. Ignored if `None`. Default: `None`.
  807. Examples::
  808. >>> A = torch.randn(2, 3, 3)
  809. >>> A = A @ A.mT # make symmetric
  810. >>> LD, pivots, info = torch.linalg.ldl_factor_ex(A)
  811. >>> B = torch.randn(2, 3, 4)
  812. >>> X = torch.linalg.ldl_solve(LD, pivots, B)
  813. >>> torch.linalg.norm(A @ X - B)
  814. >>> tensor(0.0001)
  815. """,
  816. )
  817. lstsq = _add_docstr(
  818. _linalg.linalg_lstsq,
  819. r"""
  820. torch.linalg.lstsq(A, B, rcond=None, *, driver=None) -> (Tensor, Tensor, Tensor, Tensor)
  821. Computes a solution to the least squares problem of a system of linear equations.
  822. Letting :math:`\mathbb{K}` be :math:`\mathbb{R}` or :math:`\mathbb{C}`,
  823. the **least squares problem** for a linear system :math:`AX = B` with
  824. :math:`A \in \mathbb{K}^{m \times n}, B \in \mathbb{K}^{m \times k}` is defined as
  825. .. math::
  826. \min_{X \in \mathbb{K}^{n \times k}} \|AX - B\|_F
  827. where :math:`\|-\|_F` denotes the Frobenius norm.
  828. Supports inputs of float, double, cfloat and cdouble dtypes.
  829. Also supports batches of matrices, and if the inputs are batches of matrices then
  830. the output has the same batch dimensions.
  831. :attr:`driver` chooses the backend function that will be used.
  832. For CPU inputs the valid values are `'gels'`, `'gelsy'`, `'gelsd`, `'gelss'`.
  833. To choose the best driver on CPU consider:
  834. - If :attr:`A` is well-conditioned (its `condition number`_ is not too large), or you do not mind some precision loss.
  835. - For a general matrix: `'gelsy'` (QR with pivoting) (default)
  836. - If :attr:`A` is full-rank: `'gels'` (QR)
  837. - If :attr:`A` is not well-conditioned.
  838. - `'gelsd'` (tridiagonal reduction and SVD)
  839. - But if you run into memory issues: `'gelss'` (full SVD).
  840. For CUDA input, the only valid driver is `'gels'`, which assumes that :attr:`A` is full-rank.
  841. See also the `full description of these drivers`_
  842. :attr:`rcond` is used to determine the effective rank of the matrices in :attr:`A`
  843. when :attr:`driver` is one of (`'gelsy'`, `'gelsd'`, `'gelss'`).
  844. In this case, if :math:`\sigma_i` are the singular values of `A` in decreasing order,
  845. :math:`\sigma_i` will be rounded down to zero if :math:`\sigma_i \leq \text{rcond} \cdot \sigma_1`.
  846. If :attr:`rcond`\ `= None` (default), :attr:`rcond` is set to the machine precision of the dtype of :attr:`A` times `max(m, n)`.
  847. This function returns the solution to the problem and some extra information in a named tuple of
  848. four tensors `(solution, residuals, rank, singular_values)`. For inputs :attr:`A`, :attr:`B`
  849. of shape `(*, m, n)`, `(*, m, k)` respectively, it contains
  850. - `solution`: the least squares solution. It has shape `(*, n, k)`.
  851. - `residuals`: the squared residuals of the solutions, that is, :math:`\|AX - B\|_F^2`.
  852. It has shape `(*, k)`.
  853. It is computed when `m > n` and every matrix in :attr:`A` is full-rank,
  854. otherwise, it is an empty tensor.
  855. If :attr:`A` is a batch of matrices and any matrix in the batch is not full rank,
  856. then an empty tensor is returned. This behavior may change in a future PyTorch release.
  857. - `rank`: tensor of ranks of the matrices in :attr:`A`.
  858. It has shape equal to the batch dimensions of :attr:`A`.
  859. It is computed when :attr:`driver` is one of (`'gelsy'`, `'gelsd'`, `'gelss'`),
  860. otherwise it is an empty tensor.
  861. - `singular_values`: tensor of singular values of the matrices in :attr:`A`.
  862. It has shape `(*, min(m, n))`.
  863. It is computed when :attr:`driver` is one of (`'gelsd'`, `'gelss'`),
  864. otherwise it is an empty tensor.
  865. .. note::
  866. This function computes `X = \ `:attr:`A`\ `.pinverse() @ \ `:attr:`B` in a faster and
  867. more numerically stable way than performing the computations separately.
  868. .. warning::
  869. The default value of :attr:`rcond` may change in a future PyTorch release.
  870. It is therefore recommended to use a fixed value to avoid potential
  871. breaking changes.
  872. Args:
  873. A (Tensor): lhs tensor of shape `(*, m, n)` where `*` is zero or more batch dimensions.
  874. B (Tensor): rhs tensor of shape `(*, m, k)` where `*` is zero or more batch dimensions.
  875. rcond (float, optional): used to determine the effective rank of :attr:`A`.
  876. If :attr:`rcond`\ `= None`, :attr:`rcond` is set to the machine
  877. precision of the dtype of :attr:`A` times `max(m, n)`. Default: `None`.
  878. Keyword args:
  879. driver (str, optional): name of the LAPACK/MAGMA method to be used.
  880. If `None`, `'gelsy'` is used for CPU inputs and `'gels'` for CUDA inputs.
  881. Default: `None`.
  882. Returns:
  883. A named tuple `(solution, residuals, rank, singular_values)`.
  884. Examples::
  885. >>> A = torch.randn(1,3,3)
  886. >>> A
  887. tensor([[[-1.0838, 0.0225, 0.2275],
  888. [ 0.2438, 0.3844, 0.5499],
  889. [ 0.1175, -0.9102, 2.0870]]])
  890. >>> B = torch.randn(2,3,3)
  891. >>> B
  892. tensor([[[-0.6772, 0.7758, 0.5109],
  893. [-1.4382, 1.3769, 1.1818],
  894. [-0.3450, 0.0806, 0.3967]],
  895. [[-1.3994, -0.1521, -0.1473],
  896. [ 1.9194, 1.0458, 0.6705],
  897. [-1.1802, -0.9796, 1.4086]]])
  898. >>> X = torch.linalg.lstsq(A, B).solution # A is broadcasted to shape (2, 3, 3)
  899. >>> torch.dist(X, torch.linalg.pinv(A) @ B)
  900. tensor(1.5152e-06)
  901. >>> S = torch.linalg.lstsq(A, B, driver='gelsd').singular_values
  902. >>> torch.dist(S, torch.linalg.svdvals(A))
  903. tensor(2.3842e-07)
  904. >>> A[:, 0].zero_() # Decrease the rank of A
  905. >>> rank = torch.linalg.lstsq(A, B).rank
  906. >>> rank
  907. tensor([2])
  908. .. _condition number:
  909. https://pytorch.org/docs/main/linalg.html#torch.linalg.cond
  910. .. _full description of these drivers:
  911. https://www.netlib.org/lapack/lug/node27.html
  912. """,
  913. )
  914. matrix_power = _add_docstr(
  915. _linalg.linalg_matrix_power,
  916. r"""
  917. matrix_power(A, n, *, out=None) -> Tensor
  918. Computes the `n`-th power of a square matrix for an integer `n`.
  919. Supports input of float, double, cfloat and cdouble dtypes.
  920. Also supports batches of matrices, and if :attr:`A` is a batch of matrices then
  921. the output has the same batch dimensions.
  922. If :attr:`n`\ `= 0`, it returns the identity matrix (or batch) of the same shape
  923. as :attr:`A`. If :attr:`n` is negative, it returns the inverse of each matrix
  924. (if invertible) raised to the power of `abs(n)`.
  925. .. note::
  926. Consider using :func:`torch.linalg.solve` if possible for multiplying a matrix on the left by
  927. a negative power as, if :attr:`n`\ `> 0`::
  928. torch.linalg.solve(matrix_power(A, n), B) == matrix_power(A, -n) @ B
  929. It is always preferred to use :func:`~solve` when possible, as it is faster and more
  930. numerically stable than computing :math:`A^{-n}` explicitly.
  931. .. seealso::
  932. :func:`torch.linalg.solve` computes :attr:`A`\ `.inverse() @ \ `:attr:`B` with a
  933. numerically stable algorithm.
  934. Args:
  935. A (Tensor): tensor of shape `(*, m, m)` where `*` is zero or more batch dimensions.
  936. n (int): the exponent.
  937. Keyword args:
  938. out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.
  939. Raises:
  940. RuntimeError: if :attr:`n`\ `< 0` and the matrix :attr:`A` or any matrix in the
  941. batch of matrices :attr:`A` is not invertible.
  942. Examples::
  943. >>> A = torch.randn(3, 3)
  944. >>> torch.linalg.matrix_power(A, 0)
  945. tensor([[1., 0., 0.],
  946. [0., 1., 0.],
  947. [0., 0., 1.]])
  948. >>> torch.linalg.matrix_power(A, 3)
  949. tensor([[ 1.0756, 0.4980, 0.0100],
  950. [-1.6617, 1.4994, -1.9980],
  951. [-0.4509, 0.2731, 0.8001]])
  952. >>> torch.linalg.matrix_power(A.expand(2, -1, -1), -2)
  953. tensor([[[ 0.2640, 0.4571, -0.5511],
  954. [-1.0163, 0.3491, -1.5292],
  955. [-0.4899, 0.0822, 0.2773]],
  956. [[ 0.2640, 0.4571, -0.5511],
  957. [-1.0163, 0.3491, -1.5292],
  958. [-0.4899, 0.0822, 0.2773]]])
  959. """,
  960. )
  961. matrix_rank = _add_docstr(
  962. _linalg.linalg_matrix_rank,
  963. r"""
  964. linalg.matrix_rank(A, *, atol=None, rtol=None, hermitian=False, out=None) -> Tensor
  965. Computes the numerical rank of a matrix.
  966. The matrix rank is computed as the number of singular values
  967. (or eigenvalues in absolute value when :attr:`hermitian`\ `= True`)
  968. that are greater than :math:`\max(\text{atol}, \sigma_1 * \text{rtol})` threshold,
  969. where :math:`\sigma_1` is the largest singular value (or eigenvalue).
  970. Supports input of float, double, cfloat and cdouble dtypes.
  971. Also supports batches of matrices, and if :attr:`A` is a batch of matrices then
  972. the output has the same batch dimensions.
  973. If :attr:`hermitian`\ `= True`, :attr:`A` is assumed to be Hermitian if complex or
  974. symmetric if real, but this is not checked internally. Instead, just the lower
  975. triangular part of the matrix is used in the computations.
  976. If :attr:`rtol` is not specified and :attr:`A` is a matrix of dimensions `(m, n)`,
  977. the relative tolerance is set to be :math:`\text{rtol} = \max(m, n) \varepsilon`
  978. and :math:`\varepsilon` is the epsilon value for the dtype of :attr:`A` (see :class:`.finfo`).
  979. If :attr:`rtol` is not specified and :attr:`atol` is specified to be larger than zero then
  980. :attr:`rtol` is set to zero.
  981. If :attr:`atol` or :attr:`rtol` is a :class:`torch.Tensor`, its shape must be broadcastable to that
  982. of the singular values of :attr:`A` as returned by :func:`torch.linalg.svdvals`.
  983. .. note::
  984. This function has NumPy compatible variant `linalg.matrix_rank(A, tol, hermitian=False)`.
  985. However, use of the positional argument :attr:`tol` is deprecated in favor of :attr:`atol` and :attr:`rtol`.
  986. """
  987. + rf"""
  988. .. note:: The matrix rank is computed using a singular value decomposition
  989. :func:`torch.linalg.svdvals` if :attr:`hermitian`\ `= False` (default) and the eigenvalue
  990. decomposition :func:`torch.linalg.eigvalsh` when :attr:`hermitian`\ `= True`.
  991. {common_notes["sync_note"]}
  992. """
  993. + r"""
  994. Args:
  995. A (Tensor): tensor of shape `(*, m, n)` where `*` is zero or more batch dimensions.
  996. tol (float, Tensor, optional): [NumPy Compat] Alias for :attr:`atol`. Default: `None`.
  997. Keyword args:
  998. atol (float, Tensor, optional): the absolute tolerance value. When `None` it's considered to be zero.
  999. Default: `None`.
  1000. rtol (float, Tensor, optional): the relative tolerance value. See above for the value it takes when `None`.
  1001. Default: `None`.
  1002. hermitian(bool): indicates whether :attr:`A` is Hermitian if complex
  1003. or symmetric if real. Default: `False`.
  1004. out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.
  1005. Examples::
  1006. >>> A = torch.eye(10)
  1007. >>> torch.linalg.matrix_rank(A)
  1008. tensor(10)
  1009. >>> B = torch.eye(10)
  1010. >>> B[0, 0] = 0
  1011. >>> torch.linalg.matrix_rank(B)
  1012. tensor(9)
  1013. >>> A = torch.randn(4, 3, 2)
  1014. >>> torch.linalg.matrix_rank(A)
  1015. tensor([2, 2, 2, 2])
  1016. >>> A = torch.randn(2, 4, 2, 3)
  1017. >>> torch.linalg.matrix_rank(A)
  1018. tensor([[2, 2, 2, 2],
  1019. [2, 2, 2, 2]])
  1020. >>> A = torch.randn(2, 4, 3, 3, dtype=torch.complex64)
  1021. >>> torch.linalg.matrix_rank(A)
  1022. tensor([[3, 3, 3, 3],
  1023. [3, 3, 3, 3]])
  1024. >>> torch.linalg.matrix_rank(A, hermitian=True)
  1025. tensor([[3, 3, 3, 3],
  1026. [3, 3, 3, 3]])
  1027. >>> torch.linalg.matrix_rank(A, atol=1.0, rtol=0.0)
  1028. tensor([[3, 2, 2, 2],
  1029. [1, 2, 1, 2]])
  1030. >>> torch.linalg.matrix_rank(A, atol=1.0, rtol=0.0, hermitian=True)
  1031. tensor([[2, 2, 2, 1],
  1032. [1, 2, 2, 2]])
  1033. """,
  1034. )
  1035. norm = _add_docstr(
  1036. _linalg.linalg_norm,
  1037. r"""
  1038. linalg.norm(A, ord=None, dim=None, keepdim=False, *, out=None, dtype=None) -> Tensor
  1039. Computes a vector or matrix norm.
  1040. Supports input of float, double, cfloat and cdouble dtypes.
  1041. Whether this function computes a vector or matrix norm is determined as follows:
  1042. - If :attr:`dim` is an `int`, the vector norm will be computed.
  1043. - If :attr:`dim` is a `2`-`tuple`, the matrix norm will be computed.
  1044. - If :attr:`dim`\ `= None` and :attr:`ord`\ `= None`,
  1045. :attr:`A` will be flattened to 1D and the `2`-norm of the resulting vector will be computed.
  1046. - If :attr:`dim`\ `= None` and :attr:`ord` `!= None`, :attr:`A` must be 1D or 2D.
  1047. :attr:`ord` defines the norm that is computed. The following norms are supported:
  1048. ====================== ========================== ======================================================
  1049. :attr:`ord` norm for matrices norm for vectors
  1050. ====================== ========================== ======================================================
  1051. `None` (default) Frobenius norm `2`-norm (see below)
  1052. `'fro'` Frobenius norm -- not supported --
  1053. `'nuc'` nuclear norm -- not supported --
  1054. `inf` `max(sum(abs(x), dim=1))` `max(abs(x))`
  1055. `-inf` `min(sum(abs(x), dim=1))` `min(abs(x))`
  1056. `0` -- not supported -- `sum(x != 0)`
  1057. `1` `max(sum(abs(x), dim=0))` as below
  1058. `-1` `min(sum(abs(x), dim=0))` as below
  1059. `2` largest `singular value`_ as below
  1060. `-2` smallest `singular value`_ as below
  1061. other `int` or `float` -- not supported -- `sum(abs(x)^{ord})^{(1 / ord)}`
  1062. ====================== ========================== ======================================================
  1063. where `inf` refers to `float('inf')`, NumPy's `inf` object, or any equivalent object.
  1064. .. seealso::
  1065. :func:`torch.linalg.vector_norm` computes a vector norm.
  1066. :func:`torch.linalg.matrix_norm` computes a matrix norm.
  1067. The above functions are often clearer and more flexible than using :func:`torch.linalg.norm`.
  1068. For example, `torch.linalg.norm(A, ord=1, dim=(0, 1))` always
  1069. computes a matrix norm, but with `torch.linalg.vector_norm(A, ord=1, dim=(0, 1))` it is possible
  1070. to compute a vector norm over the two dimensions.
  1071. Args:
  1072. A (Tensor): tensor of shape `(*, n)` or `(*, m, n)` where `*` is zero or more batch dimensions
  1073. ord (int, float, inf, -inf, 'fro', 'nuc', optional): order of norm. Default: `None`
  1074. dim (int, Tuple[int], optional): dimensions over which to compute
  1075. the vector or matrix norm. See above for the behavior when :attr:`dim`\ `= None`.
  1076. Default: `None`
  1077. keepdim (bool, optional): If set to `True`, the reduced dimensions are retained
  1078. in the result as dimensions with size one. Default: `False`
  1079. Keyword args:
  1080. out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.
  1081. dtype (:class:`torch.dtype`, optional): If specified, the input tensor is cast to
  1082. :attr:`dtype` before performing the operation, and the returned tensor's type
  1083. will be :attr:`dtype`. Default: `None`
  1084. Returns:
  1085. A real-valued tensor, even when :attr:`A` is complex.
  1086. Examples::
  1087. >>> from torch import linalg as LA
  1088. >>> a = torch.arange(9, dtype=torch.float) - 4
  1089. >>> a
  1090. tensor([-4., -3., -2., -1., 0., 1., 2., 3., 4.])
  1091. >>> B = a.reshape((3, 3))
  1092. >>> B
  1093. tensor([[-4., -3., -2.],
  1094. [-1., 0., 1.],
  1095. [ 2., 3., 4.]])
  1096. >>> LA.norm(a)
  1097. tensor(7.7460)
  1098. >>> LA.norm(B)
  1099. tensor(7.7460)
  1100. >>> LA.norm(B, 'fro')
  1101. tensor(7.7460)
  1102. >>> LA.norm(a, float('inf'))
  1103. tensor(4.)
  1104. >>> LA.norm(B, float('inf'))
  1105. tensor(9.)
  1106. >>> LA.norm(a, -float('inf'))
  1107. tensor(0.)
  1108. >>> LA.norm(B, -float('inf'))
  1109. tensor(2.)
  1110. >>> LA.norm(a, 1)
  1111. tensor(20.)
  1112. >>> LA.norm(B, 1)
  1113. tensor(7.)
  1114. >>> LA.norm(a, -1)
  1115. tensor(0.)
  1116. >>> LA.norm(B, -1)
  1117. tensor(6.)
  1118. >>> LA.norm(a, 2)
  1119. tensor(7.7460)
  1120. >>> LA.norm(B, 2)
  1121. tensor(7.3485)
  1122. >>> LA.norm(a, -2)
  1123. tensor(0.)
  1124. >>> LA.norm(B.double(), -2)
  1125. tensor(1.8570e-16, dtype=torch.float64)
  1126. >>> LA.norm(a, 3)
  1127. tensor(5.8480)
  1128. >>> LA.norm(a, -3)
  1129. tensor(0.)
  1130. Using the :attr:`dim` argument to compute vector norms::
  1131. >>> c = torch.tensor([[1., 2., 3.],
  1132. ... [-1, 1, 4]])
  1133. >>> LA.norm(c, dim=0)
  1134. tensor([1.4142, 2.2361, 5.0000])
  1135. >>> LA.norm(c, dim=1)
  1136. tensor([3.7417, 4.2426])
  1137. >>> LA.norm(c, ord=1, dim=1)
  1138. tensor([6., 6.])
  1139. Using the :attr:`dim` argument to compute matrix norms::
  1140. >>> A = torch.arange(8, dtype=torch.float).reshape(2, 2, 2)
  1141. >>> LA.norm(A, dim=(1,2))
  1142. tensor([ 3.7417, 11.2250])
  1143. >>> LA.norm(A[0, :, :]), LA.norm(A[1, :, :])
  1144. (tensor(3.7417), tensor(11.2250))
  1145. .. _singular value:
  1146. https://en.wikipedia.org/wiki/Singular_value_decomposition#Singular_values,_singular_vectors,_and_their_relation_to_the_SVD
  1147. """,
  1148. )
  1149. vector_norm = _add_docstr(
  1150. _linalg.linalg_vector_norm,
  1151. r"""
  1152. linalg.vector_norm(x, ord=2, dim=None, keepdim=False, *, dtype=None, out=None) -> Tensor
  1153. Computes a vector norm.
  1154. If :attr:`x` is complex valued, it computes the norm of :attr:`x`\ `.abs()`
  1155. Supports input of float, double, cfloat and cdouble dtypes.
  1156. This function does not necessarily treat multidimensional :attr:`x` as a batch of
  1157. vectors, instead:
  1158. - If :attr:`dim`\ `= None`, :attr:`x` will be flattened before the norm is computed.
  1159. - If :attr:`dim` is an `int` or a `tuple`, the norm will be computed over these dimensions
  1160. and the other dimensions will be treated as batch dimensions.
  1161. This behavior is for consistency with :func:`torch.linalg.norm`.
  1162. :attr:`ord` defines the vector norm that is computed. The following norms are supported:
  1163. ====================== ===============================
  1164. :attr:`ord` vector norm
  1165. ====================== ===============================
  1166. `2` (default) `2`-norm (see below)
  1167. `inf` `max(abs(x))`
  1168. `-inf` `min(abs(x))`
  1169. `0` `sum(x != 0)`
  1170. other `int` or `float` `sum(abs(x)^{ord})^{(1 / ord)}`
  1171. ====================== ===============================
  1172. where `inf` refers to `float('inf')`, NumPy's `inf` object, or any equivalent object.
  1173. :attr:`dtype` may be used to perform the computation in a more precise dtype.
  1174. It is semantically equivalent to calling ``linalg.vector_norm(x.to(dtype))``
  1175. but it is faster in some cases.
  1176. .. seealso::
  1177. :func:`torch.linalg.matrix_norm` computes a matrix norm.
  1178. Args:
  1179. x (Tensor): tensor, flattened by default, but this behavior can be
  1180. controlled using :attr:`dim`. (Note: the keyword argument
  1181. `input` can also be used as an alias for `x`.)
  1182. ord (int, float, inf, -inf, 'fro', 'nuc', optional): order of norm. Default: `2`
  1183. dim (int, Tuple[int], optional): dimensions over which to compute
  1184. the norm. See above for the behavior when :attr:`dim`\ `= None`.
  1185. Default: `None`
  1186. keepdim (bool, optional): If set to `True`, the reduced dimensions are retained
  1187. in the result as dimensions with size one. Default: `False`
  1188. Keyword args:
  1189. out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.
  1190. dtype (:class:`torch.dtype`, optional): type used to perform the accumulation and the return.
  1191. If specified, :attr:`x` is cast to :attr:`dtype` before performing the operation,
  1192. and the returned tensor's type will be :attr:`dtype` if real and of its real counterpart if complex.
  1193. :attr:`dtype` may be complex if :attr:`x` is complex, otherwise it must be real.
  1194. :attr:`x` should be convertible without narrowing to :attr:`dtype`. Default: None
  1195. Returns:
  1196. A real-valued tensor, even when :attr:`x` is complex.
  1197. Examples::
  1198. >>> from torch import linalg as LA
  1199. >>> a = torch.arange(9, dtype=torch.float) - 4
  1200. >>> a
  1201. tensor([-4., -3., -2., -1., 0., 1., 2., 3., 4.])
  1202. >>> B = a.reshape((3, 3))
  1203. >>> B
  1204. tensor([[-4., -3., -2.],
  1205. [-1., 0., 1.],
  1206. [ 2., 3., 4.]])
  1207. >>> LA.vector_norm(a, ord=3.5)
  1208. tensor(5.4345)
  1209. >>> LA.vector_norm(B, ord=3.5)
  1210. tensor(5.4345)
  1211. """,
  1212. )
  1213. matrix_norm = _add_docstr(
  1214. _linalg.linalg_matrix_norm,
  1215. r"""
  1216. linalg.matrix_norm(A, ord='fro', dim=(-2, -1), keepdim=False, *, dtype=None, out=None) -> Tensor
  1217. Computes a matrix norm.
  1218. If :attr:`A` is complex valued, it computes the norm of :attr:`A`\ `.abs()`
  1219. Support input of float, double, cfloat and cdouble dtypes.
  1220. Also supports batches of matrices: the norm will be computed over the
  1221. dimensions specified by the 2-tuple :attr:`dim` and the other dimensions will
  1222. be treated as batch dimensions. The output will have the same batch dimensions.
  1223. :attr:`ord` defines the matrix norm that is computed. The following norms are supported:
  1224. ====================== ========================================================
  1225. :attr:`ord` matrix norm
  1226. ====================== ========================================================
  1227. `'fro'` (default) Frobenius norm
  1228. `'nuc'` nuclear norm
  1229. `inf` `max(sum(abs(x), dim=1))`
  1230. `-inf` `min(sum(abs(x), dim=1))`
  1231. `1` `max(sum(abs(x), dim=0))`
  1232. `-1` `min(sum(abs(x), dim=0))`
  1233. `2` largest singular value
  1234. `-2` smallest singular value
  1235. ====================== ========================================================
  1236. where `inf` refers to `float('inf')`, NumPy's `inf` object, or any equivalent object.
  1237. Args:
  1238. A (Tensor): tensor with two or more dimensions. By default its
  1239. shape is interpreted as `(*, m, n)` where `*` is zero or more
  1240. batch dimensions, but this behavior can be controlled using :attr:`dim`.
  1241. ord (int, inf, -inf, 'fro', 'nuc', optional): order of norm. Default: `'fro'`
  1242. dim (Tuple[int, int], optional): dimensions over which to compute the norm. Default: `(-2, -1)`
  1243. keepdim (bool, optional): If set to `True`, the reduced dimensions are retained
  1244. in the result as dimensions with size one. Default: `False`
  1245. Keyword args:
  1246. out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.
  1247. dtype (:class:`torch.dtype`, optional): If specified, the input tensor is cast to
  1248. :attr:`dtype` before performing the operation, and the returned tensor's type
  1249. will be :attr:`dtype`. Default: `None`
  1250. Returns:
  1251. A real-valued tensor, even when :attr:`A` is complex.
  1252. Examples::
  1253. >>> from torch import linalg as LA
  1254. >>> A = torch.arange(9, dtype=torch.float).reshape(3, 3)
  1255. >>> A
  1256. tensor([[0., 1., 2.],
  1257. [3., 4., 5.],
  1258. [6., 7., 8.]])
  1259. >>> LA.matrix_norm(A)
  1260. tensor(14.2829)
  1261. >>> LA.matrix_norm(A, ord=-1)
  1262. tensor(9.)
  1263. >>> B = A.expand(2, -1, -1)
  1264. >>> B
  1265. tensor([[[0., 1., 2.],
  1266. [3., 4., 5.],
  1267. [6., 7., 8.]],
  1268. [[0., 1., 2.],
  1269. [3., 4., 5.],
  1270. [6., 7., 8.]]])
  1271. >>> LA.matrix_norm(B)
  1272. tensor([14.2829, 14.2829])
  1273. >>> LA.matrix_norm(B, dim=(0, 2))
  1274. tensor([ 3.1623, 10.0000, 17.2627])
  1275. """,
  1276. )
  1277. matmul = _add_docstr(
  1278. _linalg.linalg_matmul,
  1279. r"""
  1280. linalg.matmul(input, other, *, out=None) -> Tensor
  1281. Alias for :func:`torch.matmul`
  1282. """,
  1283. )
  1284. diagonal = _add_docstr(
  1285. _linalg.linalg_diagonal,
  1286. r"""
  1287. linalg.diagonal(A, *, offset=0, dim1=-2, dim2=-1) -> Tensor
  1288. Alias for :func:`torch.diagonal` with defaults :attr:`dim1`\ `= -2`, :attr:`dim2`\ `= -1`.
  1289. """,
  1290. )
  1291. multi_dot = _add_docstr(
  1292. _linalg.linalg_multi_dot,
  1293. r"""
  1294. linalg.multi_dot(tensors, *, out=None)
  1295. Efficiently multiplies two or more matrices by reordering the multiplications so that
  1296. the fewest arithmetic operations are performed.
  1297. Supports inputs of float, double, cfloat and cdouble dtypes.
  1298. This function does not support batched inputs.
  1299. Every tensor in :attr:`tensors` must be 2D, except for the first and last which
  1300. may be 1D. If the first tensor is a 1D vector of shape `(n,)` it is treated as a row vector
  1301. of shape `(1, n)`, similarly if the last tensor is a 1D vector of shape `(n,)` it is treated
  1302. as a column vector of shape `(n, 1)`.
  1303. If the first and last tensors are matrices, the output will be a matrix.
  1304. However, if either is a 1D vector, then the output will be a 1D vector.
  1305. Differences with `numpy.linalg.multi_dot`:
  1306. - Unlike `numpy.linalg.multi_dot`, the first and last tensors must either be 1D or 2D
  1307. whereas NumPy allows them to be nD
  1308. .. warning:: This function does not broadcast.
  1309. .. note:: This function is implemented by chaining :func:`torch.mm` calls after
  1310. computing the optimal matrix multiplication order.
  1311. .. note:: The cost of multiplying two matrices with shapes `(a, b)` and `(b, c)` is
  1312. `a * b * c`. Given matrices `A`, `B`, `C` with shapes `(10, 100)`,
  1313. `(100, 5)`, `(5, 50)` respectively, we can calculate the cost of different
  1314. multiplication orders as follows:
  1315. .. math::
  1316. \begin{align*}
  1317. \operatorname{cost}((AB)C) &= 10 \times 100 \times 5 + 10 \times 5 \times 50 = 7500 \\
  1318. \operatorname{cost}(A(BC)) &= 10 \times 100 \times 50 + 100 \times 5 \times 50 = 75000
  1319. \end{align*}
  1320. In this case, multiplying `A` and `B` first followed by `C` is 10 times faster.
  1321. Args:
  1322. tensors (Sequence[Tensor]): two or more tensors to multiply. The first and last
  1323. tensors may be 1D or 2D. Every other tensor must be 2D.
  1324. Keyword args:
  1325. out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.
  1326. Examples::
  1327. >>> from torch.linalg import multi_dot
  1328. >>> multi_dot([torch.tensor([1, 2]), torch.tensor([2, 3])])
  1329. tensor(8)
  1330. >>> multi_dot([torch.tensor([[1, 2]]), torch.tensor([2, 3])])
  1331. tensor([8])
  1332. >>> multi_dot([torch.tensor([[1, 2]]), torch.tensor([[2], [3]])])
  1333. tensor([[8]])
  1334. >>> A = torch.arange(2 * 3).view(2, 3)
  1335. >>> B = torch.arange(3 * 2).view(3, 2)
  1336. >>> C = torch.arange(2 * 2).view(2, 2)
  1337. >>> multi_dot((A, B, C))
  1338. tensor([[ 26, 49],
  1339. [ 80, 148]])
  1340. """,
  1341. )
  1342. svd = _add_docstr(
  1343. _linalg.linalg_svd,
  1344. r"""
  1345. linalg.svd(A, full_matrices=True, *, driver=None, out=None) -> (Tensor, Tensor, Tensor)
  1346. Computes the singular value decomposition (SVD) of a matrix.
  1347. Letting :math:`\mathbb{K}` be :math:`\mathbb{R}` or :math:`\mathbb{C}`,
  1348. the **full SVD** of a matrix
  1349. :math:`A \in \mathbb{K}^{m \times n}`, if `k = min(m,n)`, is defined as
  1350. .. math::
  1351. A = U \operatorname{diag}(S) V^{\text{H}}
  1352. \mathrlap{\qquad U \in \mathbb{K}^{m \times m}, S \in \mathbb{R}^k, V \in \mathbb{K}^{n \times n}}
  1353. where :math:`\operatorname{diag}(S) \in \mathbb{K}^{m \times n}`,
  1354. :math:`V^{\text{H}}` is the conjugate transpose when :math:`V` is complex, and the transpose when :math:`V` is real-valued.
  1355. The matrices :math:`U`, :math:`V` (and thus :math:`V^{\text{H}}`) are orthogonal in the real case, and unitary in the complex case.
  1356. When `m > n` (resp. `m < n`) we can drop the last `m - n` (resp. `n - m`) columns of `U` (resp. `V`) to form the **reduced SVD**:
  1357. .. math::
  1358. A = U \operatorname{diag}(S) V^{\text{H}}
  1359. \mathrlap{\qquad U \in \mathbb{K}^{m \times k}, S \in \mathbb{R}^k, V \in \mathbb{K}^{n \times k}}
  1360. where :math:`\operatorname{diag}(S) \in \mathbb{K}^{k \times k}`.
  1361. In this case, :math:`U` and :math:`V` also have orthonormal columns.
  1362. Supports input of float, double, cfloat and cdouble dtypes.
  1363. Also supports batches of matrices, and if :attr:`A` is a batch of matrices then
  1364. the output has the same batch dimensions.
  1365. The returned decomposition is a named tuple `(U, S, Vh)`
  1366. which corresponds to :math:`U`, :math:`S`, :math:`V^{\text{H}}` above.
  1367. The singular values are returned in descending order.
  1368. The parameter :attr:`full_matrices` chooses between the full (default) and reduced SVD.
  1369. The :attr:`driver` kwarg may be used in CUDA with a cuSOLVER backend to choose the algorithm used to compute the SVD.
  1370. The choice of a driver is a trade-off between accuracy and speed.
  1371. - If :attr:`A` is well-conditioned (its `condition number`_ is not too large), or you do not mind some precision loss.
  1372. - For a general matrix: `'gesvdj'` (Jacobi method)
  1373. - If :attr:`A` is tall or wide (`m >> n` or `m << n`): `'gesvda'` (Approximate method)
  1374. - If :attr:`A` is not well-conditioned or precision is relevant: `'gesvd'` (QR based)
  1375. By default (:attr:`driver`\ `= None`), we call `'gesvdj'` and, if it fails, we fallback to `'gesvd'`.
  1376. Differences with `numpy.linalg.svd`:
  1377. - Unlike `numpy.linalg.svd`, this function always returns a tuple of three tensors
  1378. and it doesn't support `compute_uv` argument.
  1379. Please use :func:`torch.linalg.svdvals`, which computes only the singular values,
  1380. instead of `compute_uv=False`.
  1381. .. note:: When :attr:`full_matrices`\ `= True`, the gradients with respect to `U[..., :, min(m, n):]`
  1382. and `Vh[..., min(m, n):, :]` will be ignored, as those vectors can be arbitrary bases
  1383. of the corresponding subspaces.
  1384. .. warning:: The returned tensors `U` and `V` are not unique, nor are they continuous with
  1385. respect to :attr:`A`.
  1386. Due to this lack of uniqueness, different hardware and software may compute
  1387. different singular vectors.
  1388. This non-uniqueness is caused by the fact that multiplying any pair of singular
  1389. vectors :math:`u_k, v_k` by `-1` in the real case or by
  1390. :math:`e^{i \phi}, \phi \in \mathbb{R}` in the complex case produces another two
  1391. valid singular vectors of the matrix.
  1392. For this reason, the loss function shall not depend on this :math:`e^{i \phi}` quantity,
  1393. as it is not well-defined.
  1394. This is checked for complex inputs when computing the gradients of this function. As such,
  1395. when inputs are complex and are on a CUDA device, the computation of the gradients
  1396. of this function synchronizes that device with the CPU.
  1397. .. warning:: Gradients computed using `U` or `Vh` will only be finite when
  1398. :attr:`A` does not have repeated singular values. If :attr:`A` is rectangular,
  1399. additionally, zero must also not be one of its singular values.
  1400. Furthermore, if the distance between any two singular values is close to zero,
  1401. the gradient will be numerically unstable, as it depends on the singular values
  1402. :math:`\sigma_i` through the computation of
  1403. :math:`\frac{1}{\min_{i \neq j} \sigma_i^2 - \sigma_j^2}`.
  1404. In the rectangular case, the gradient will also be numerically unstable when
  1405. :attr:`A` has small singular values, as it also depends on the computation of
  1406. :math:`\frac{1}{\sigma_i}`.
  1407. .. seealso::
  1408. :func:`torch.linalg.svdvals` computes only the singular values.
  1409. Unlike :func:`torch.linalg.svd`, the gradients of :func:`~svdvals` are always
  1410. numerically stable.
  1411. :func:`torch.linalg.eig` for a function that computes another type of spectral
  1412. decomposition of a matrix. The eigendecomposition works just on square matrices.
  1413. :func:`torch.linalg.eigh` for a (faster) function that computes the eigenvalue decomposition
  1414. for Hermitian and symmetric matrices.
  1415. :func:`torch.linalg.qr` for another (much faster) decomposition that works on general
  1416. matrices.
  1417. Args:
  1418. A (Tensor): tensor of shape `(*, m, n)` where `*` is zero or more batch dimensions.
  1419. full_matrices (bool, optional): controls whether to compute the full or reduced
  1420. SVD, and consequently,
  1421. the shape of the returned tensors
  1422. `U` and `Vh`. Default: `True`.
  1423. Keyword args:
  1424. driver (str, optional): name of the cuSOLVER method to be used. This keyword argument only works on CUDA inputs.
  1425. Available options are: `None`, `gesvd`, `gesvdj`, and `gesvda`.
  1426. Default: `None`.
  1427. out (tuple, optional): output tuple of three tensors. Ignored if `None`.
  1428. Returns:
  1429. A named tuple `(U, S, Vh)` which corresponds to :math:`U`, :math:`S`, :math:`V^{\text{H}}` above.
  1430. `S` will always be real-valued, even when :attr:`A` is complex.
  1431. It will also be ordered in descending order.
  1432. `U` and `Vh` will have the same dtype as :attr:`A`. The left / right singular vectors will be given by
  1433. the columns of `U` and the rows of `Vh` respectively.
  1434. Examples::
  1435. >>> A = torch.randn(5, 3)
  1436. >>> U, S, Vh = torch.linalg.svd(A, full_matrices=False)
  1437. >>> U.shape, S.shape, Vh.shape
  1438. (torch.Size([5, 3]), torch.Size([3]), torch.Size([3, 3]))
  1439. >>> torch.dist(A, U @ torch.diag(S) @ Vh)
  1440. tensor(1.0486e-06)
  1441. >>> U, S, Vh = torch.linalg.svd(A)
  1442. >>> U.shape, S.shape, Vh.shape
  1443. (torch.Size([5, 5]), torch.Size([3]), torch.Size([3, 3]))
  1444. >>> torch.dist(A, U[:, :3] @ torch.diag(S) @ Vh)
  1445. tensor(1.0486e-06)
  1446. >>> A = torch.randn(7, 5, 3)
  1447. >>> U, S, Vh = torch.linalg.svd(A, full_matrices=False)
  1448. >>> torch.dist(A, U @ torch.diag_embed(S) @ Vh)
  1449. tensor(3.0957e-06)
  1450. .. _condition number:
  1451. https://pytorch.org/docs/main/linalg.html#torch.linalg.cond
  1452. .. _the resulting vectors will span the same subspace:
  1453. https://en.wikipedia.org/wiki/Singular_value_decomposition#Singular_values,_singular_vectors,_and_their_relation_to_the_SVD
  1454. """,
  1455. )
  1456. svdvals = _add_docstr(
  1457. _linalg.linalg_svdvals,
  1458. r"""
  1459. linalg.svdvals(A, *, driver=None, out=None) -> Tensor
  1460. Computes the singular values of a matrix.
  1461. Supports input of float, double, cfloat and cdouble dtypes.
  1462. Also supports batches of matrices, and if :attr:`A` is a batch of matrices then
  1463. the output has the same batch dimensions.
  1464. The singular values are returned in descending order.
  1465. .. note:: This function is equivalent to NumPy's `linalg.svd(A, compute_uv=False)`.
  1466. """
  1467. + rf"""
  1468. .. note:: {common_notes["sync_note"]}
  1469. """
  1470. + r"""
  1471. .. seealso::
  1472. :func:`torch.linalg.svd` computes the full singular value decomposition.
  1473. Args:
  1474. A (Tensor): tensor of shape `(*, m, n)` where `*` is zero or more batch dimensions.
  1475. Keyword args:
  1476. driver (str, optional): name of the cuSOLVER method to be used. This keyword argument only works on CUDA inputs.
  1477. Available options are: `None`, `gesvd`, `gesvdj`, and `gesvda`.
  1478. Check :func:`torch.linalg.svd` for details.
  1479. Default: `None`.
  1480. out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.
  1481. Returns:
  1482. A real-valued tensor, even when :attr:`A` is complex.
  1483. Examples::
  1484. >>> A = torch.randn(5, 3)
  1485. >>> S = torch.linalg.svdvals(A)
  1486. >>> S
  1487. tensor([2.5139, 2.1087, 1.1066])
  1488. >>> torch.dist(S, torch.linalg.svd(A, full_matrices=False).S)
  1489. tensor(2.4576e-07)
  1490. """,
  1491. )
  1492. cond = _add_docstr(
  1493. _linalg.linalg_cond,
  1494. r"""
  1495. linalg.cond(A, p=None, *, out=None) -> Tensor
  1496. Computes the condition number of a matrix with respect to a matrix norm.
  1497. Letting :math:`\mathbb{K}` be :math:`\mathbb{R}` or :math:`\mathbb{C}`,
  1498. the **condition number** :math:`\kappa` of a matrix
  1499. :math:`A \in \mathbb{K}^{n \times n}` is defined as
  1500. .. math::
  1501. \kappa(A) = \|A\|_p\|A^{-1}\|_p
  1502. The condition number of :attr:`A` measures the numerical stability of the linear system `AX = B`
  1503. with respect to a matrix norm.
  1504. Supports input of float, double, cfloat and cdouble dtypes.
  1505. Also supports batches of matrices, and if :attr:`A` is a batch of matrices then
  1506. the output has the same batch dimensions.
  1507. :attr:`p` defines the matrix norm that is computed. The following norms are supported:
  1508. ========= =================================
  1509. :attr:`p` matrix norm
  1510. ========= =================================
  1511. `None` `2`-norm (largest singular value)
  1512. `'fro'` Frobenius norm
  1513. `'nuc'` nuclear norm
  1514. `inf` `max(sum(abs(x), dim=1))`
  1515. `-inf` `min(sum(abs(x), dim=1))`
  1516. `1` `max(sum(abs(x), dim=0))`
  1517. `-1` `min(sum(abs(x), dim=0))`
  1518. `2` largest singular value
  1519. `-2` smallest singular value
  1520. ========= =================================
  1521. where `inf` refers to `float('inf')`, NumPy's `inf` object, or any equivalent object.
  1522. For :attr:`p` is one of `('fro', 'nuc', inf, -inf, 1, -1)`, this function uses
  1523. :func:`torch.linalg.norm` and :func:`torch.linalg.inv`.
  1524. As such, in this case, the matrix (or every matrix in the batch) :attr:`A` has to be square
  1525. and invertible.
  1526. For :attr:`p` in `(2, -2)`, this function can be computed in terms of the singular values
  1527. :math:`\sigma_1 \geq \ldots \geq \sigma_n`
  1528. .. math::
  1529. \kappa_2(A) = \frac{\sigma_1}{\sigma_n}\qquad \kappa_{-2}(A) = \frac{\sigma_n}{\sigma_1}
  1530. In these cases, it is computed using :func:`torch.linalg.svdvals`. For these norms, the matrix
  1531. (or every matrix in the batch) :attr:`A` may have any shape.
  1532. .. note :: When inputs are on a CUDA device, this function synchronizes that device with the CPU
  1533. if :attr:`p` is one of `('fro', 'nuc', inf, -inf, 1, -1)`.
  1534. .. seealso::
  1535. :func:`torch.linalg.solve` for a function that solves linear systems of square matrices.
  1536. :func:`torch.linalg.lstsq` for a function that solves linear systems of general matrices.
  1537. Args:
  1538. A (Tensor): tensor of shape `(*, m, n)` where `*` is zero or more batch dimensions
  1539. for :attr:`p` in `(2, -2)`, and of shape `(*, n, n)` where every matrix
  1540. is invertible for :attr:`p` in `('fro', 'nuc', inf, -inf, 1, -1)`.
  1541. p (int, inf, -inf, 'fro', 'nuc', optional):
  1542. the type of the matrix norm to use in the computations (see above). Default: `None`
  1543. Keyword args:
  1544. out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.
  1545. Returns:
  1546. A real-valued tensor, even when :attr:`A` is complex.
  1547. Raises:
  1548. RuntimeError:
  1549. if :attr:`p` is one of `('fro', 'nuc', inf, -inf, 1, -1)`
  1550. and the :attr:`A` matrix or any matrix in the batch :attr:`A` is not square
  1551. or invertible.
  1552. Examples::
  1553. >>> A = torch.randn(3, 4, 4, dtype=torch.complex64)
  1554. >>> torch.linalg.cond(A)
  1555. >>> A = torch.tensor([[1., 0, -1], [0, 1, 0], [1, 0, 1]])
  1556. >>> torch.linalg.cond(A)
  1557. tensor([1.4142])
  1558. >>> torch.linalg.cond(A, 'fro')
  1559. tensor(3.1623)
  1560. >>> torch.linalg.cond(A, 'nuc')
  1561. tensor(9.2426)
  1562. >>> torch.linalg.cond(A, float('inf'))
  1563. tensor(2.)
  1564. >>> torch.linalg.cond(A, float('-inf'))
  1565. tensor(1.)
  1566. >>> torch.linalg.cond(A, 1)
  1567. tensor(2.)
  1568. >>> torch.linalg.cond(A, -1)
  1569. tensor(1.)
  1570. >>> torch.linalg.cond(A, 2)
  1571. tensor([1.4142])
  1572. >>> torch.linalg.cond(A, -2)
  1573. tensor([0.7071])
  1574. >>> A = torch.randn(2, 3, 3)
  1575. >>> torch.linalg.cond(A)
  1576. tensor([[9.5917],
  1577. [3.2538]])
  1578. >>> A = torch.randn(2, 3, 3, dtype=torch.complex64)
  1579. >>> torch.linalg.cond(A)
  1580. tensor([[4.6245],
  1581. [4.5671]])
  1582. """,
  1583. )
  1584. pinv = _add_docstr(
  1585. _linalg.linalg_pinv,
  1586. r"""
  1587. linalg.pinv(A, *, atol=None, rtol=None, hermitian=False, out=None) -> Tensor
  1588. Computes the pseudoinverse (Moore-Penrose inverse) of a matrix.
  1589. The pseudoinverse may be `defined algebraically`_
  1590. but it is more computationally convenient to understand it `through the SVD`_
  1591. Supports input of float, double, cfloat and cdouble dtypes.
  1592. Also supports batches of matrices, and if :attr:`A` is a batch of matrices then
  1593. the output has the same batch dimensions.
  1594. If :attr:`hermitian`\ `= True`, :attr:`A` is assumed to be Hermitian if complex or
  1595. symmetric if real, but this is not checked internally. Instead, just the lower
  1596. triangular part of the matrix is used in the computations.
  1597. The singular values (or the norm of the eigenvalues when :attr:`hermitian`\ `= True`)
  1598. that are below :math:`\max(\text{atol}, \sigma_1 \cdot \text{rtol})` threshold are
  1599. treated as zero and discarded in the computation,
  1600. where :math:`\sigma_1` is the largest singular value (or eigenvalue).
  1601. If :attr:`rtol` is not specified and :attr:`A` is a matrix of dimensions `(m, n)`,
  1602. the relative tolerance is set to be :math:`\text{rtol} = \max(m, n) \varepsilon`
  1603. and :math:`\varepsilon` is the epsilon value for the dtype of :attr:`A` (see :class:`.finfo`).
  1604. If :attr:`rtol` is not specified and :attr:`atol` is specified to be larger than zero then
  1605. :attr:`rtol` is set to zero.
  1606. If :attr:`atol` or :attr:`rtol` is a :class:`torch.Tensor`, its shape must be broadcastable to that
  1607. of the singular values of :attr:`A` as returned by :func:`torch.linalg.svd`.
  1608. .. note:: This function uses :func:`torch.linalg.svd` if :attr:`hermitian`\ `= False` and
  1609. :func:`torch.linalg.eigh` if :attr:`hermitian`\ `= True`.
  1610. For CUDA inputs, this function synchronizes that device with the CPU.
  1611. .. note::
  1612. Consider using :func:`torch.linalg.lstsq` if possible for multiplying a matrix on the left by
  1613. the pseudoinverse, as::
  1614. torch.linalg.lstsq(A, B).solution == A.pinv() @ B
  1615. It is always preferred to use :func:`~lstsq` when possible, as it is faster and more
  1616. numerically stable than computing the pseudoinverse explicitly.
  1617. .. note::
  1618. This function has NumPy compatible variant `linalg.pinv(A, rcond, hermitian=False)`.
  1619. However, use of the positional argument :attr:`rcond` is deprecated in favor of :attr:`rtol`.
  1620. .. warning::
  1621. This function uses internally :func:`torch.linalg.svd` (or :func:`torch.linalg.eigh`
  1622. when :attr:`hermitian`\ `= True`), so its derivative has the same problems as those of these
  1623. functions. See the warnings in :func:`torch.linalg.svd` and :func:`torch.linalg.eigh` for
  1624. more details.
  1625. .. seealso::
  1626. :func:`torch.linalg.inv` computes the inverse of a square matrix.
  1627. :func:`torch.linalg.lstsq` computes :attr:`A`\ `.pinv() @ \ `:attr:`B` with a
  1628. numerically stable algorithm.
  1629. Args:
  1630. A (Tensor): tensor of shape `(*, m, n)` where `*` is zero or more batch dimensions.
  1631. rcond (float, Tensor, optional): [NumPy Compat]. Alias for :attr:`rtol`. Default: `None`.
  1632. Keyword args:
  1633. atol (float, Tensor, optional): the absolute tolerance value. When `None` it's considered to be zero.
  1634. Default: `None`.
  1635. rtol (float, Tensor, optional): the relative tolerance value. See above for the value it takes when `None`.
  1636. Default: `None`.
  1637. hermitian(bool, optional): indicates whether :attr:`A` is Hermitian if complex
  1638. or symmetric if real. Default: `False`.
  1639. out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.
  1640. Examples::
  1641. >>> A = torch.randn(3, 5)
  1642. >>> A
  1643. tensor([[ 0.5495, 0.0979, -1.4092, -0.1128, 0.4132],
  1644. [-1.1143, -0.3662, 0.3042, 1.6374, -0.9294],
  1645. [-0.3269, -0.5745, -0.0382, -0.5922, -0.6759]])
  1646. >>> torch.linalg.pinv(A)
  1647. tensor([[ 0.0600, -0.1933, -0.2090],
  1648. [-0.0903, -0.0817, -0.4752],
  1649. [-0.7124, -0.1631, -0.2272],
  1650. [ 0.1356, 0.3933, -0.5023],
  1651. [-0.0308, -0.1725, -0.5216]])
  1652. >>> A = torch.randn(2, 6, 3)
  1653. >>> Apinv = torch.linalg.pinv(A)
  1654. >>> torch.dist(Apinv @ A, torch.eye(3))
  1655. tensor(8.5633e-07)
  1656. >>> A = torch.randn(3, 3, dtype=torch.complex64)
  1657. >>> A = A + A.T.conj() # creates a Hermitian matrix
  1658. >>> Apinv = torch.linalg.pinv(A, hermitian=True)
  1659. >>> torch.dist(Apinv @ A, torch.eye(3))
  1660. tensor(1.0830e-06)
  1661. .. _defined algebraically:
  1662. https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_inverse#Existence_and_uniqueness
  1663. .. _through the SVD:
  1664. https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_inverse#Singular_value_decomposition_(SVD)
  1665. """,
  1666. )
  1667. matrix_exp = _add_docstr(
  1668. _linalg.linalg_matrix_exp,
  1669. r"""
  1670. linalg.matrix_exp(A) -> Tensor
  1671. Computes the matrix exponential of a square matrix.
  1672. Letting :math:`\mathbb{K}` be :math:`\mathbb{R}` or :math:`\mathbb{C}`,
  1673. this function computes the **matrix exponential** of :math:`A \in \mathbb{K}^{n \times n}`, which is defined as
  1674. .. math::
  1675. \mathrm{matrix\_exp}(A) = \sum_{k=0}^\infty \frac{1}{k!}A^k \in \mathbb{K}^{n \times n}.
  1676. If the matrix :math:`A` has eigenvalues :math:`\lambda_i \in \mathbb{C}`,
  1677. the matrix :math:`\mathrm{matrix\_exp}(A)` has eigenvalues :math:`e^{\lambda_i} \in \mathbb{C}`.
  1678. Supports input of bfloat16, float, double, cfloat and cdouble dtypes.
  1679. Also supports batches of matrices, and if :attr:`A` is a batch of matrices then
  1680. the output has the same batch dimensions.
  1681. Args:
  1682. A (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions.
  1683. Example::
  1684. >>> A = torch.empty(2, 2, 2)
  1685. >>> A[0, :, :] = torch.eye(2, 2)
  1686. >>> A[1, :, :] = 2 * torch.eye(2, 2)
  1687. >>> A
  1688. tensor([[[1., 0.],
  1689. [0., 1.]],
  1690. [[2., 0.],
  1691. [0., 2.]]])
  1692. >>> torch.linalg.matrix_exp(A)
  1693. tensor([[[2.7183, 0.0000],
  1694. [0.0000, 2.7183]],
  1695. [[7.3891, 0.0000],
  1696. [0.0000, 7.3891]]])
  1697. >>> import math
  1698. >>> A = torch.tensor([[0, math.pi/3], [-math.pi/3, 0]]) # A is skew-symmetric
  1699. >>> torch.linalg.matrix_exp(A) # matrix_exp(A) = [[cos(pi/3), sin(pi/3)], [-sin(pi/3), cos(pi/3)]]
  1700. tensor([[ 0.5000, 0.8660],
  1701. [-0.8660, 0.5000]])
  1702. """,
  1703. )
  1704. solve = _add_docstr(
  1705. _linalg.linalg_solve,
  1706. r"""
  1707. linalg.solve(A, B, *, left=True, out=None) -> Tensor
  1708. Computes the solution of a square system of linear equations with a unique solution.
  1709. Letting :math:`\mathbb{K}` be :math:`\mathbb{R}` or :math:`\mathbb{C}`,
  1710. this function computes the solution :math:`X \in \mathbb{K}^{n \times k}` of the **linear system** associated to
  1711. :math:`A \in \mathbb{K}^{n \times n}, B \in \mathbb{K}^{n \times k}`, which is defined as
  1712. .. math:: AX = B
  1713. If :attr:`left`\ `= False`, this function returns the matrix :math:`X \in \mathbb{K}^{n \times k}` that solves the system
  1714. .. math::
  1715. XA = B\mathrlap{\qquad A \in \mathbb{K}^{k \times k}, B \in \mathbb{K}^{n \times k}.}
  1716. This system of linear equations has one solution if and only if :math:`A` is `invertible`_.
  1717. This function assumes that :math:`A` is invertible.
  1718. Supports inputs of float, double, cfloat and cdouble dtypes.
  1719. Also supports batches of matrices, and if the inputs are batches of matrices then
  1720. the output has the same batch dimensions.
  1721. Letting `*` be zero or more batch dimensions,
  1722. - If :attr:`A` has shape `(*, n, n)` and :attr:`B` has shape `(*, n)` (a batch of vectors) or shape
  1723. `(*, n, k)` (a batch of matrices or "multiple right-hand sides"), this function returns `X` of shape
  1724. `(*, n)` or `(*, n, k)` respectively.
  1725. - Otherwise, if :attr:`A` has shape `(*, n, n)` and :attr:`B` has shape `(n,)` or `(n, k)`, :attr:`B`
  1726. is broadcasted to have shape `(*, n)` or `(*, n, k)` respectively.
  1727. This function then returns the solution of the resulting batch of systems of linear equations.
  1728. .. note::
  1729. This function computes `X = \ `:attr:`A`\ `.inverse() @ \ `:attr:`B` in a faster and
  1730. more numerically stable way than performing the computations separately.
  1731. .. note::
  1732. It is possible to compute the solution of the system :math:`XA = B` by passing the inputs
  1733. :attr:`A` and :attr:`B` transposed and transposing the output returned by this function.
  1734. .. note::
  1735. :attr:`A` is allowed to be a non-batched `torch.sparse_csr_tensor`, but only with `left=True`.
  1736. """
  1737. + rf"""
  1738. .. note:: {common_notes["sync_note_has_ex"].format("torch.linalg.solve_ex")}
  1739. """
  1740. + r"""
  1741. .. seealso::
  1742. :func:`torch.linalg.solve_triangular` computes the solution of a triangular system of linear
  1743. equations with a unique solution.
  1744. Args:
  1745. A (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions.
  1746. B (Tensor): right-hand side tensor of shape `(*, n)` or `(*, n, k)` or `(n,)` or `(n, k)`
  1747. according to the rules described above
  1748. Keyword args:
  1749. left (bool, optional): whether to solve the system :math:`AX=B` or :math:`XA = B`. Default: `True`.
  1750. out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.
  1751. Raises:
  1752. RuntimeError: if the :attr:`A` matrix is not invertible or any matrix in a batched :attr:`A`
  1753. is not invertible.
  1754. Examples::
  1755. >>> A = torch.randn(3, 3)
  1756. >>> b = torch.randn(3)
  1757. >>> x = torch.linalg.solve(A, b)
  1758. >>> torch.allclose(A @ x, b)
  1759. True
  1760. >>> A = torch.randn(2, 3, 3)
  1761. >>> B = torch.randn(2, 3, 4)
  1762. >>> X = torch.linalg.solve(A, B)
  1763. >>> X.shape
  1764. torch.Size([2, 3, 4])
  1765. >>> torch.allclose(A @ X, B)
  1766. True
  1767. >>> A = torch.randn(2, 3, 3)
  1768. >>> b = torch.randn(3, 1)
  1769. >>> x = torch.linalg.solve(A, b) # b is broadcasted to size (2, 3, 1)
  1770. >>> x.shape
  1771. torch.Size([2, 3, 1])
  1772. >>> torch.allclose(A @ x, b)
  1773. True
  1774. >>> b = torch.randn(3)
  1775. >>> x = torch.linalg.solve(A, b) # b is broadcasted to size (2, 3)
  1776. >>> x.shape
  1777. torch.Size([2, 3])
  1778. >>> Ax = A @ x.unsqueeze(-1)
  1779. >>> torch.allclose(Ax, b.unsqueeze(-1).expand_as(Ax))
  1780. True
  1781. .. _invertible:
  1782. https://en.wikipedia.org/wiki/Invertible_matrix#The_invertible_matrix_theorem
  1783. """,
  1784. )
  1785. solve_triangular = _add_docstr(
  1786. _linalg.linalg_solve_triangular,
  1787. r"""
  1788. linalg.solve_triangular(A, B, *, upper, left=True, unitriangular=False, out=None) -> Tensor
  1789. Computes the solution of a triangular system of linear equations with a unique solution.
  1790. Letting :math:`\mathbb{K}` be :math:`\mathbb{R}` or :math:`\mathbb{C}`,
  1791. this function computes the solution :math:`X \in \mathbb{K}^{n \times k}` of the **linear system**
  1792. associated to the triangular matrix :math:`A \in \mathbb{K}^{n \times n}` without zeros on the diagonal
  1793. (that is, it is `invertible`_) and the rectangular matrix , :math:`B \in \mathbb{K}^{n \times k}`,
  1794. which is defined as
  1795. .. math:: AX = B
  1796. The argument :attr:`upper` signals whether :math:`A` is upper or lower triangular.
  1797. If :attr:`left`\ `= False`, this function returns the matrix :math:`X \in \mathbb{K}^{n \times k}` that
  1798. solves the system
  1799. .. math::
  1800. XA = B\mathrlap{\qquad A \in \mathbb{K}^{k \times k}, B \in \mathbb{K}^{n \times k}.}
  1801. If :attr:`upper`\ `= True` (resp. `False`) just the upper (resp. lower) triangular half of :attr:`A`
  1802. will be accessed. The elements below the main diagonal will be considered to be zero and will not be accessed.
  1803. If :attr:`unitriangular`\ `= True`, the diagonal of :attr:`A` is assumed to be ones and will not be accessed.
  1804. The result may contain `NaN` s if the diagonal of :attr:`A` contains zeros or elements that
  1805. are very close to zero and :attr:`unitriangular`\ `= False` (default) or if the input matrix
  1806. has very small eigenvalues.
  1807. Supports inputs of float, double, cfloat and cdouble dtypes.
  1808. Also supports batches of matrices, and if the inputs are batches of matrices then
  1809. the output has the same batch dimensions.
  1810. .. seealso::
  1811. :func:`torch.linalg.solve` computes the solution of a general square system of linear
  1812. equations with a unique solution.
  1813. Args:
  1814. A (Tensor): tensor of shape `(*, n, n)` (or `(*, k, k)` if :attr:`left`\ `= False`)
  1815. where `*` is zero or more batch dimensions.
  1816. B (Tensor): right-hand side tensor of shape `(*, n, k)`.
  1817. Keyword args:
  1818. upper (bool): whether :attr:`A` is an upper or lower triangular matrix.
  1819. left (bool, optional): whether to solve the system :math:`AX=B` or :math:`XA = B`. Default: `True`.
  1820. unitriangular (bool, optional): if `True`, the diagonal elements of :attr:`A` are assumed to be
  1821. all equal to `1`. Default: `False`.
  1822. out (Tensor, optional): output tensor. `B` may be passed as `out` and the result is computed in-place on `B`.
  1823. Ignored if `None`. Default: `None`.
  1824. Examples::
  1825. >>> A = torch.randn(3, 3).triu_()
  1826. >>> B = torch.randn(3, 4)
  1827. >>> X = torch.linalg.solve_triangular(A, B, upper=True)
  1828. >>> torch.allclose(A @ X, B)
  1829. True
  1830. >>> A = torch.randn(2, 3, 3).tril_()
  1831. >>> B = torch.randn(2, 3, 4)
  1832. >>> X = torch.linalg.solve_triangular(A, B, upper=False)
  1833. >>> torch.allclose(A @ X, B)
  1834. True
  1835. >>> A = torch.randn(2, 4, 4).tril_()
  1836. >>> B = torch.randn(2, 3, 4)
  1837. >>> X = torch.linalg.solve_triangular(A, B, upper=False, left=False)
  1838. >>> torch.allclose(X @ A, B)
  1839. True
  1840. .. _invertible:
  1841. https://en.wikipedia.org/wiki/Invertible_matrix#The_invertible_matrix_theorem
  1842. """,
  1843. )
  1844. lu_factor = _add_docstr(
  1845. _linalg.linalg_lu_factor,
  1846. r"""
  1847. linalg.lu_factor(A, *, bool pivot=True, out=None) -> (Tensor, Tensor)
  1848. Computes a compact representation of the LU factorization with partial pivoting of a matrix.
  1849. This function computes a compact representation of the decomposition given by :func:`torch.linalg.lu`.
  1850. If the matrix is square, this representation may be used in :func:`torch.linalg.lu_solve`
  1851. to solve system of linear equations that share the matrix :attr:`A`.
  1852. The returned decomposition is represented as a named tuple `(LU, pivots)`.
  1853. The ``LU`` matrix has the same shape as the input matrix ``A``. Its upper and lower triangular
  1854. parts encode the non-constant elements of ``L`` and ``U`` of the LU decomposition of ``A``.
  1855. The returned permutation matrix is represented by a 1-indexed vector. `pivots[i] == j` represents
  1856. that in the `i`-th step of the algorithm, the `i`-th row was permuted with the `j-1`-th row.
  1857. On CUDA, one may use :attr:`pivot`\ `= False`. In this case, this function returns the LU
  1858. decomposition without pivoting if it exists.
  1859. Supports inputs of float, double, cfloat and cdouble dtypes.
  1860. Also supports batches of matrices, and if the inputs are batches of matrices then
  1861. the output has the same batch dimensions.
  1862. """
  1863. + rf"""
  1864. .. note:: {common_notes["sync_note_has_ex"].format("torch.linalg.lu_factor_ex")}
  1865. """
  1866. + r"""
  1867. .. warning:: The LU decomposition is almost never unique, as often there are different permutation
  1868. matrices that can yield different LU decompositions.
  1869. As such, different platforms, like SciPy, or inputs on different devices,
  1870. may produce different valid decompositions.
  1871. Gradient computations are only supported if the input matrix is full-rank.
  1872. If this condition is not met, no error will be thrown, but the gradient may not be finite.
  1873. This is because the LU decomposition with pivoting is not differentiable at these points.
  1874. .. seealso::
  1875. :func:`torch.linalg.lu_solve` solves a system of linear equations given the output of this
  1876. function provided the input matrix was square and invertible.
  1877. :func:`torch.lu_unpack` unpacks the tensors returned by :func:`~lu_factor` into the three
  1878. matrices `P, L, U` that form the decomposition.
  1879. :func:`torch.linalg.lu` computes the LU decomposition with partial pivoting of a possibly
  1880. non-square matrix. It is a composition of :func:`~lu_factor` and :func:`torch.lu_unpack`.
  1881. :func:`torch.linalg.solve` solves a system of linear equations. It is a composition
  1882. of :func:`~lu_factor` and :func:`~lu_solve`.
  1883. Args:
  1884. A (Tensor): tensor of shape `(*, m, n)` where `*` is zero or more batch dimensions.
  1885. Keyword args:
  1886. pivot (bool, optional): Whether to compute the LU decomposition with partial pivoting, or the regular LU
  1887. decomposition. :attr:`pivot`\ `= False` not supported on CPU. Default: `True`.
  1888. out (tuple, optional): tuple of two tensors to write the output to. Ignored if `None`. Default: `None`.
  1889. Returns:
  1890. A named tuple `(LU, pivots)`.
  1891. Raises:
  1892. RuntimeError: if the :attr:`A` matrix is not invertible or any matrix in a batched :attr:`A`
  1893. is not invertible.
  1894. Examples::
  1895. >>> A = torch.randn(2, 3, 3)
  1896. >>> B1 = torch.randn(2, 3, 4)
  1897. >>> B2 = torch.randn(2, 3, 7)
  1898. >>> LU, pivots = torch.linalg.lu_factor(A)
  1899. >>> X1 = torch.linalg.lu_solve(LU, pivots, B1)
  1900. >>> X2 = torch.linalg.lu_solve(LU, pivots, B2)
  1901. >>> torch.allclose(A @ X1, B1)
  1902. True
  1903. >>> torch.allclose(A @ X2, B2)
  1904. True
  1905. .. _invertible:
  1906. https://en.wikipedia.org/wiki/Invertible_matrix#The_invertible_matrix_theorem
  1907. """,
  1908. )
  1909. lu_factor_ex = _add_docstr(
  1910. _linalg.linalg_lu_factor_ex,
  1911. r"""
  1912. linalg.lu_factor_ex(A, *, pivot=True, check_errors=False, out=None) -> (Tensor, Tensor, Tensor)
  1913. This is a version of :func:`~lu_factor` that does not perform error checks unless :attr:`check_errors`\ `= True`.
  1914. It also returns the :attr:`info` tensor returned by `LAPACK's getrf`_.
  1915. """
  1916. + rf"""
  1917. .. note:: {common_notes["sync_note_ex"]}
  1918. .. warning:: {common_notes["experimental_warning"]}
  1919. """
  1920. + r"""
  1921. Args:
  1922. A (Tensor): tensor of shape `(*, m, n)` where `*` is zero or more batch dimensions.
  1923. Keyword args:
  1924. pivot (bool, optional): Whether to compute the LU decomposition with partial pivoting, or the regular LU
  1925. decomposition. :attr:`pivot`\ `= False` not supported on CPU. Default: `True`.
  1926. check_errors (bool, optional): controls whether to check the content of ``infos`` and raise
  1927. an error if it is non-zero. Default: `False`.
  1928. out (tuple, optional): tuple of three tensors to write the output to. Ignored if `None`. Default: `None`.
  1929. Returns:
  1930. A named tuple `(LU, pivots, info)`.
  1931. .. _LAPACK's getrf:
  1932. https://www.netlib.org/lapack/explore-html-3.6.1/dd/d9a/group__double_g_ecomputational_ga0019443faea08275ca60a734d0593e60.html
  1933. """,
  1934. )
  1935. lu_solve = _add_docstr(
  1936. _linalg.linalg_lu_solve,
  1937. r"""
  1938. linalg.lu_solve(LU, pivots, B, *, left=True, adjoint=False, out=None) -> Tensor
  1939. Computes the solution of a square system of linear equations with a unique solution given an LU decomposition.
  1940. Letting :math:`\mathbb{K}` be :math:`\mathbb{R}` or :math:`\mathbb{C}`,
  1941. this function computes the solution :math:`X \in \mathbb{K}^{n \times k}` of the **linear system** associated to
  1942. :math:`A \in \mathbb{K}^{n \times n}, B \in \mathbb{K}^{n \times k}`, which is defined as
  1943. .. math:: AX = B
  1944. where :math:`A` is given factorized as returned by :func:`~lu_factor`.
  1945. If :attr:`left`\ `= False`, this function returns the matrix :math:`X \in \mathbb{K}^{n \times k}` that solves the system
  1946. .. math::
  1947. XA = B\mathrlap{\qquad A \in \mathbb{K}^{k \times k}, B \in \mathbb{K}^{n \times k}.}
  1948. If :attr:`adjoint`\ `= True` (and :attr:`left`\ `= True`), given an LU factorization of :math:`A`
  1949. this function function returns the :math:`X \in \mathbb{K}^{n \times k}` that solves the system
  1950. .. math::
  1951. A^{\text{H}}X = B\mathrlap{\qquad A \in \mathbb{K}^{k \times k}, B \in \mathbb{K}^{n \times k}.}
  1952. where :math:`A^{\text{H}}` is the conjugate transpose when :math:`A` is complex, and the
  1953. transpose when :math:`A` is real-valued. The :attr:`left`\ `= False` case is analogous.
  1954. Supports inputs of float, double, cfloat and cdouble dtypes.
  1955. Also supports batches of matrices, and if the inputs are batches of matrices then
  1956. the output has the same batch dimensions.
  1957. Args:
  1958. LU (Tensor): tensor of shape `(*, n, n)` (or `(*, k, k)` if :attr:`left`\ `= True`)
  1959. where `*` is zero or more batch dimensions as returned by :func:`~lu_factor`.
  1960. pivots (Tensor): tensor of shape `(*, n)` (or `(*, k)` if :attr:`left`\ `= True`)
  1961. where `*` is zero or more batch dimensions as returned by :func:`~lu_factor`.
  1962. B (Tensor): right-hand side tensor of shape `(*, n, k)`.
  1963. Keyword args:
  1964. left (bool, optional): whether to solve the system :math:`AX=B` or :math:`XA = B`. Default: `True`.
  1965. adjoint (bool, optional): whether to solve the system :math:`AX=B` or :math:`A^{\text{H}}X = B`. Default: `False`.
  1966. out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.
  1967. Examples::
  1968. >>> A = torch.randn(3, 3)
  1969. >>> LU, pivots = torch.linalg.lu_factor(A)
  1970. >>> B = torch.randn(3, 2)
  1971. >>> X = torch.linalg.lu_solve(LU, pivots, B)
  1972. >>> torch.allclose(A @ X, B)
  1973. True
  1974. >>> B = torch.randn(3, 3, 2) # Broadcasting rules apply: A is broadcasted
  1975. >>> X = torch.linalg.lu_solve(LU, pivots, B)
  1976. >>> torch.allclose(A @ X, B)
  1977. True
  1978. >>> B = torch.randn(3, 5, 3)
  1979. >>> X = torch.linalg.lu_solve(LU, pivots, B, left=False)
  1980. >>> torch.allclose(X @ A, B)
  1981. True
  1982. >>> B = torch.randn(3, 3, 4) # Now solve for A^T
  1983. >>> X = torch.linalg.lu_solve(LU, pivots, B, adjoint=True)
  1984. >>> torch.allclose(A.mT @ X, B)
  1985. True
  1986. .. _invertible:
  1987. https://en.wikipedia.org/wiki/Invertible_matrix#The_invertible_matrix_theorem
  1988. """,
  1989. )
  1990. lu = _add_docstr(
  1991. _linalg.linalg_lu,
  1992. r"""
  1993. lu(A, *, pivot=True, out=None) -> (Tensor, Tensor, Tensor)
  1994. Computes the LU decomposition with partial pivoting of a matrix.
  1995. Letting :math:`\mathbb{K}` be :math:`\mathbb{R}` or :math:`\mathbb{C}`,
  1996. the **LU decomposition with partial pivoting** of a matrix
  1997. :math:`A \in \mathbb{K}^{m \times n}` is defined as
  1998. .. math::
  1999. A = PLU\mathrlap{\qquad P \in \mathbb{K}^{m \times m}, L \in \mathbb{K}^{m \times k}, U \in \mathbb{K}^{k \times n}}
  2000. where `k = min(m,n)`, :math:`P` is a `permutation matrix`_, :math:`L` is lower triangular with ones on the diagonal
  2001. and :math:`U` is upper triangular.
  2002. If :attr:`pivot`\ `= False` and :attr:`A` is on GPU, then the **LU decomposition without pivoting** is computed
  2003. .. math::
  2004. A = LU\mathrlap{\qquad L \in \mathbb{K}^{m \times k}, U \in \mathbb{K}^{k \times n}}
  2005. When :attr:`pivot`\ `= False`, the returned matrix :attr:`P` will be empty.
  2006. The LU decomposition without pivoting `may not exist`_ if any of the principal minors of :attr:`A` is singular.
  2007. In this case, the output matrix may contain `inf` or `NaN`.
  2008. Supports input of float, double, cfloat and cdouble dtypes.
  2009. Also supports batches of matrices, and if :attr:`A` is a batch of matrices then
  2010. the output has the same batch dimensions.
  2011. .. seealso::
  2012. :func:`torch.linalg.solve` solves a system of linear equations using the LU decomposition
  2013. with partial pivoting.
  2014. .. warning:: The LU decomposition is almost never unique, as often there are different permutation
  2015. matrices that can yield different LU decompositions.
  2016. As such, different platforms, like SciPy, or inputs on different devices,
  2017. may produce different valid decompositions.
  2018. .. warning:: Gradient computations are only supported if the input matrix is full-rank.
  2019. If this condition is not met, no error will be thrown, but the gradient
  2020. may not be finite.
  2021. This is because the LU decomposition with pivoting is not differentiable at these points.
  2022. Args:
  2023. A (Tensor): tensor of shape `(*, m, n)` where `*` is zero or more batch dimensions.
  2024. pivot (bool, optional): Controls whether to compute the LU decomposition with partial pivoting or
  2025. no pivoting. Default: `True`.
  2026. Keyword args:
  2027. out (tuple, optional): output tuple of three tensors. Ignored if `None`. Default: `None`.
  2028. Returns:
  2029. A named tuple `(P, L, U)`.
  2030. Examples::
  2031. >>> A = torch.randn(3, 2)
  2032. >>> P, L, U = torch.linalg.lu(A)
  2033. >>> P
  2034. tensor([[0., 1., 0.],
  2035. [0., 0., 1.],
  2036. [1., 0., 0.]])
  2037. >>> L
  2038. tensor([[1.0000, 0.0000],
  2039. [0.5007, 1.0000],
  2040. [0.0633, 0.9755]])
  2041. >>> U
  2042. tensor([[0.3771, 0.0489],
  2043. [0.0000, 0.9644]])
  2044. >>> torch.dist(A, P @ L @ U)
  2045. tensor(5.9605e-08)
  2046. >>> A = torch.randn(2, 5, 7, device="cuda")
  2047. >>> P, L, U = torch.linalg.lu(A, pivot=False)
  2048. >>> P
  2049. tensor([], device='cuda:0')
  2050. >>> torch.dist(A, L @ U)
  2051. tensor(1.0376e-06, device='cuda:0')
  2052. .. _permutation matrix:
  2053. https://en.wikipedia.org/wiki/Permutation_matrix
  2054. .. _may not exist:
  2055. https://en.wikipedia.org/wiki/LU_decomposition#Definitions
  2056. """,
  2057. )
  2058. tensorinv = _add_docstr(
  2059. _linalg.linalg_tensorinv,
  2060. r"""
  2061. linalg.tensorinv(A, ind=2, *, out=None) -> Tensor
  2062. Computes the multiplicative inverse of :func:`torch.tensordot`.
  2063. If `m` is the product of the first :attr:`ind` dimensions of :attr:`A` and `n` is the product of
  2064. the rest of the dimensions, this function expects `m` and `n` to be equal.
  2065. If this is the case, it computes a tensor `X` such that
  2066. `tensordot(\ `:attr:`A`\ `, X, \ `:attr:`ind`\ `)` is the identity matrix in dimension `m`.
  2067. `X` will have the shape of :attr:`A` but with the first :attr:`ind` dimensions pushed back to the end
  2068. .. code:: text
  2069. X.shape == A.shape[ind:] + A.shape[:ind]
  2070. Supports input of float, double, cfloat and cdouble dtypes.
  2071. .. note:: When :attr:`A` is a `2`-dimensional tensor and :attr:`ind`\ `= 1`,
  2072. this function computes the (multiplicative) inverse of :attr:`A`
  2073. (see :func:`torch.linalg.inv`).
  2074. .. note::
  2075. Consider using :func:`torch.linalg.tensorsolve` if possible for multiplying a tensor on the left
  2076. by the tensor inverse, as::
  2077. linalg.tensorsolve(A, B) == torch.tensordot(linalg.tensorinv(A), B) # When B is a tensor with shape A.shape[:B.ndim]
  2078. It is always preferred to use :func:`~tensorsolve` when possible, as it is faster and more
  2079. numerically stable than computing the pseudoinverse explicitly.
  2080. .. seealso::
  2081. :func:`torch.linalg.tensorsolve` computes
  2082. `torch.tensordot(tensorinv(\ `:attr:`A`\ `), \ `:attr:`B`\ `)`.
  2083. Args:
  2084. A (Tensor): tensor to invert. Its shape must satisfy
  2085. `prod(\ `:attr:`A`\ `.shape[:\ `:attr:`ind`\ `]) ==
  2086. prod(\ `:attr:`A`\ `.shape[\ `:attr:`ind`\ `:])`.
  2087. ind (int): index at which to compute the inverse of :func:`torch.tensordot`. Default: `2`.
  2088. Keyword args:
  2089. out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.
  2090. Raises:
  2091. RuntimeError: if the reshaped :attr:`A` is not invertible or the product of the first
  2092. :attr:`ind` dimensions is not equal to the product of the rest.
  2093. Examples::
  2094. >>> A = torch.eye(4 * 6).reshape((4, 6, 8, 3))
  2095. >>> Ainv = torch.linalg.tensorinv(A, ind=2)
  2096. >>> Ainv.shape
  2097. torch.Size([8, 3, 4, 6])
  2098. >>> B = torch.randn(4, 6)
  2099. >>> torch.allclose(torch.tensordot(Ainv, B), torch.linalg.tensorsolve(A, B))
  2100. True
  2101. >>> A = torch.randn(4, 4)
  2102. >>> Atensorinv = torch.linalg.tensorinv(A, ind=1)
  2103. >>> Ainv = torch.linalg.inv(A)
  2104. >>> torch.allclose(Atensorinv, Ainv)
  2105. True
  2106. """,
  2107. )
  2108. tensorsolve = _add_docstr(
  2109. _linalg.linalg_tensorsolve,
  2110. r"""
  2111. linalg.tensorsolve(A, B, dims=None, *, out=None) -> Tensor
  2112. Computes the solution `X` to the system `torch.tensordot(A, X) = B`.
  2113. If `m` is the product of the first :attr:`B`\ `.ndim` dimensions of :attr:`A` and
  2114. `n` is the product of the rest of the dimensions, this function expects `m` and `n` to be equal.
  2115. The returned tensor `x` satisfies
  2116. `tensordot(\ `:attr:`A`\ `, x, dims=x.ndim) == \ `:attr:`B`.
  2117. `x` has shape :attr:`A`\ `[B.ndim:]`.
  2118. If :attr:`dims` is specified, :attr:`A` will be reshaped as
  2119. .. code:: text
  2120. A = movedim(A, dims, range(len(dims) - A.ndim + 1, 0))
  2121. Supports inputs of float, double, cfloat and cdouble dtypes.
  2122. .. seealso::
  2123. :func:`torch.linalg.tensorinv` computes the multiplicative inverse of
  2124. :func:`torch.tensordot`.
  2125. Args:
  2126. A (Tensor): tensor to solve for. Its shape must satisfy
  2127. `prod(\ `:attr:`A`\ `.shape[:\ `:attr:`B`\ `.ndim]) ==
  2128. prod(\ `:attr:`A`\ `.shape[\ `:attr:`B`\ `.ndim:])`.
  2129. B (Tensor): tensor of shape :attr:`A`\ `.shape[:\ `:attr:`B`\ `.ndim]`.
  2130. dims (Tuple[int], optional): dimensions of :attr:`A` to be moved.
  2131. If `None`, no dimensions are moved. Default: `None`.
  2132. Keyword args:
  2133. out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.
  2134. Raises:
  2135. RuntimeError: if the reshaped :attr:`A`\ `.view(m, m)` with `m` as above is not
  2136. invertible or the product of the first :attr:`ind` dimensions is not equal
  2137. to the product of the rest of the dimensions.
  2138. Examples::
  2139. >>> A = torch.eye(2 * 3 * 4).reshape((2 * 3, 4, 2, 3, 4))
  2140. >>> B = torch.randn(2 * 3, 4)
  2141. >>> X = torch.linalg.tensorsolve(A, B)
  2142. >>> X.shape
  2143. torch.Size([2, 3, 4])
  2144. >>> torch.allclose(torch.tensordot(A, X, dims=X.ndim), B)
  2145. True
  2146. >>> A = torch.randn(6, 4, 4, 3, 2)
  2147. >>> B = torch.randn(4, 3, 2)
  2148. >>> X = torch.linalg.tensorsolve(A, B, dims=(0, 2))
  2149. >>> X.shape
  2150. torch.Size([6, 4])
  2151. >>> A = A.permute(1, 3, 4, 0, 2)
  2152. >>> A.shape[B.ndim:]
  2153. torch.Size([6, 4])
  2154. >>> torch.allclose(torch.tensordot(A, X, dims=X.ndim), B, atol=1e-6)
  2155. True
  2156. """,
  2157. )
  2158. qr = _add_docstr(
  2159. _linalg.linalg_qr,
  2160. r"""
  2161. qr(A, mode='reduced', *, out=None) -> (Tensor, Tensor)
  2162. Computes the QR decomposition of a matrix.
  2163. Letting :math:`\mathbb{K}` be :math:`\mathbb{R}` or :math:`\mathbb{C}`,
  2164. the **full QR decomposition** of a matrix
  2165. :math:`A \in \mathbb{K}^{m \times n}` is defined as
  2166. .. math::
  2167. A = QR\mathrlap{\qquad Q \in \mathbb{K}^{m \times m}, R \in \mathbb{K}^{m \times n}}
  2168. where :math:`Q` is orthogonal in the real case and unitary in the complex case,
  2169. and :math:`R` is upper triangular with real diagonal (even in the complex case).
  2170. When `m > n` (tall matrix), as `R` is upper triangular, its last `m - n` rows are zero.
  2171. In this case, we can drop the last `m - n` columns of `Q` to form the
  2172. **reduced QR decomposition**:
  2173. .. math::
  2174. A = QR\mathrlap{\qquad Q \in \mathbb{K}^{m \times n}, R \in \mathbb{K}^{n \times n}}
  2175. The reduced QR decomposition agrees with the full QR decomposition when `n >= m` (wide matrix).
  2176. Supports input of float, double, cfloat and cdouble dtypes.
  2177. Also supports batches of matrices, and if :attr:`A` is a batch of matrices then
  2178. the output has the same batch dimensions.
  2179. The parameter :attr:`mode` chooses between the full and reduced QR decomposition.
  2180. If :attr:`A` has shape `(*, m, n)`, denoting `k = min(m, n)`
  2181. - :attr:`mode`\ `= 'reduced'` (default): Returns `(Q, R)` of shapes `(*, m, k)`, `(*, k, n)` respectively.
  2182. It is always differentiable.
  2183. - :attr:`mode`\ `= 'complete'`: Returns `(Q, R)` of shapes `(*, m, m)`, `(*, m, n)` respectively.
  2184. It is differentiable for `m <= n`.
  2185. - :attr:`mode`\ `= 'r'`: Computes only the reduced `R`. Returns `(Q, R)` with `Q` empty and `R` of shape `(*, k, n)`.
  2186. It is never differentiable.
  2187. Differences with `numpy.linalg.qr`:
  2188. - :attr:`mode`\ `= 'raw'` is not implemented.
  2189. - Unlike `numpy.linalg.qr`, this function always returns a tuple of two tensors.
  2190. When :attr:`mode`\ `= 'r'`, the `Q` tensor is an empty tensor.
  2191. .. warning:: The elements in the diagonal of `R` are not necessarily positive.
  2192. As such, the returned QR decomposition is only unique up to the sign of the diagonal of `R`.
  2193. Therefore, different platforms, like NumPy, or inputs on different devices,
  2194. may produce different valid decompositions.
  2195. .. warning:: The QR decomposition is only well-defined if the first `k = min(m, n)` columns
  2196. of every matrix in :attr:`A` are linearly independent.
  2197. If this condition is not met, no error will be thrown, but the QR produced
  2198. may be incorrect and its autodiff may fail or produce incorrect results.
  2199. Args:
  2200. A (Tensor): tensor of shape `(*, m, n)` where `*` is zero or more batch dimensions.
  2201. mode (str, optional): one of `'reduced'`, `'complete'`, `'r'`.
  2202. Controls the shape of the returned tensors. Default: `'reduced'`.
  2203. Keyword args:
  2204. out (tuple, optional): output tuple of two tensors. Ignored if `None`. Default: `None`.
  2205. Returns:
  2206. A named tuple `(Q, R)`.
  2207. Examples::
  2208. >>> A = torch.tensor([[12., -51, 4], [6, 167, -68], [-4, 24, -41]])
  2209. >>> Q, R = torch.linalg.qr(A)
  2210. >>> Q
  2211. tensor([[-0.8571, 0.3943, 0.3314],
  2212. [-0.4286, -0.9029, -0.0343],
  2213. [ 0.2857, -0.1714, 0.9429]])
  2214. >>> R
  2215. tensor([[ -14.0000, -21.0000, 14.0000],
  2216. [ 0.0000, -175.0000, 70.0000],
  2217. [ 0.0000, 0.0000, -35.0000]])
  2218. >>> (Q @ R).round()
  2219. tensor([[ 12., -51., 4.],
  2220. [ 6., 167., -68.],
  2221. [ -4., 24., -41.]])
  2222. >>> (Q.T @ Q).round()
  2223. tensor([[ 1., 0., 0.],
  2224. [ 0., 1., -0.],
  2225. [ 0., -0., 1.]])
  2226. >>> Q2, R2 = torch.linalg.qr(A, mode='r')
  2227. >>> Q2
  2228. tensor([])
  2229. >>> torch.equal(R, R2)
  2230. True
  2231. >>> A = torch.randn(3, 4, 5)
  2232. >>> Q, R = torch.linalg.qr(A, mode='complete')
  2233. >>> torch.dist(Q @ R, A)
  2234. tensor(1.6099e-06)
  2235. >>> torch.dist(Q.mT @ Q, torch.eye(4))
  2236. tensor(6.2158e-07)
  2237. """,
  2238. )
  2239. vander = _add_docstr(
  2240. _linalg.linalg_vander,
  2241. r"""
  2242. vander(x, N=None) -> Tensor
  2243. Generates a Vandermonde matrix.
  2244. Returns the Vandermonde matrix :math:`V`
  2245. .. math::
  2246. V = \begin{pmatrix}
  2247. 1 & x_1 & x_1^2 & \dots & x_1^{N-1}\\
  2248. 1 & x_2 & x_2^2 & \dots & x_2^{N-1}\\
  2249. 1 & x_3 & x_3^2 & \dots & x_3^{N-1}\\
  2250. \vdots & \vdots & \vdots & \ddots &\vdots \\
  2251. 1 & x_n & x_n^2 & \dots & x_n^{N-1}
  2252. \end{pmatrix}.
  2253. for `N > 1`.
  2254. If :attr:`N`\ `= None`, then `N = x.size(-1)` so that the output is a square matrix.
  2255. Supports inputs of float, double, cfloat, cdouble, and integral dtypes.
  2256. Also supports batches of vectors, and if :attr:`x` is a batch of vectors then
  2257. the output has the same batch dimensions.
  2258. Differences with `numpy.vander`:
  2259. - Unlike `numpy.vander`, this function returns the powers of :attr:`x` in ascending order.
  2260. To get them in the reverse order call ``linalg.vander(x, N).flip(-1)``.
  2261. Args:
  2262. x (Tensor): tensor of shape `(*, n)` where `*` is zero or more batch dimensions
  2263. consisting of vectors.
  2264. Keyword args:
  2265. N (int, optional): Number of columns in the output. Default: `x.size(-1)`
  2266. Example::
  2267. >>> x = torch.tensor([1, 2, 3, 5])
  2268. >>> linalg.vander(x)
  2269. tensor([[ 1, 1, 1, 1],
  2270. [ 1, 2, 4, 8],
  2271. [ 1, 3, 9, 27],
  2272. [ 1, 5, 25, 125]])
  2273. >>> linalg.vander(x, N=3)
  2274. tensor([[ 1, 1, 1],
  2275. [ 1, 2, 4],
  2276. [ 1, 3, 9],
  2277. [ 1, 5, 25]])
  2278. """,
  2279. )
  2280. vecdot = _add_docstr(
  2281. _linalg.linalg_vecdot,
  2282. r"""
  2283. linalg.vecdot(x, y, *, dim=-1, out=None) -> Tensor
  2284. Computes the dot product of two batches of vectors along a dimension.
  2285. In symbols, this function computes
  2286. .. math::
  2287. \sum_{i=1}^n \overline{x_i}y_i.
  2288. over the dimension :attr:`dim` where :math:`\overline{x_i}` denotes the conjugate for complex
  2289. vectors, and it is the identity for real vectors.
  2290. Supports input of half, bfloat16, float, double, cfloat, cdouble and integral dtypes.
  2291. It also supports broadcasting.
  2292. Args:
  2293. x (Tensor): first batch of vectors of shape `(*, n)`.
  2294. y (Tensor): second batch of vectors of shape `(*, n)`.
  2295. Keyword args:
  2296. dim (int): Dimension along which to compute the dot product. Default: `-1`.
  2297. out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.
  2298. Examples::
  2299. >>> v1 = torch.randn(3, 2)
  2300. >>> v2 = torch.randn(3, 2)
  2301. >>> linalg.vecdot(v1, v2)
  2302. tensor([ 0.3223, 0.2815, -0.1944])
  2303. >>> torch.vdot(v1[0], v2[0])
  2304. tensor(0.3223)
  2305. """,
  2306. )
  2307. _powsum = _add_docstr(
  2308. _linalg.linalg__powsum,
  2309. r"""
  2310. linalg._powsum(x, ord, dim=None, keepdim=False, *, dtype=None, out=None) -> Tensor
  2311. Computes the sum of the absolute values raised to the power ``ord``.
  2312. This function computes ``sum(abs(x)**ord)`` without applying the final root,
  2313. which is useful for distributed computing where the root should only be applied
  2314. once after reducing across all ranks.
  2315. Supports input of float, double, cfloat and cdouble dtypes.
  2316. Args:
  2317. x (Tensor): tensor, flattened by default, or optionally over dimension(s)
  2318. specified by :attr:`dim`.
  2319. ord (int, float): the exponent value. Can be any real number.
  2320. Keyword args:
  2321. dim (int, Tuple[int], optional): dimension(s) to reduce over.
  2322. Default: ``None`` (all dimensions).
  2323. keepdim (bool, optional): whether the output has :attr:`dim` retained. Default: ``False``.
  2324. dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
  2325. If specified, the input tensor is cast to :attr:`dtype` before the operation
  2326. is performed. Default: ``None``.
  2327. out (Tensor, optional): output tensor. Ignored if ``None``. Default: ``None``.
  2328. Returns:
  2329. A real-valued tensor, even when :attr:`x` is complex.
  2330. Example::
  2331. >>> x = torch.tensor([1., 2., 3.])
  2332. >>> torch.linalg._powsum(x, 2)
  2333. tensor(14.)
  2334. >>> torch.linalg.vector_norm(x, 2)
  2335. tensor(3.7417)
  2336. >>> torch.linalg._powsum(x, 2) ** 0.5 # equivalent to vector_norm
  2337. tensor(3.7417)
  2338. """,
  2339. )