_tensor.py 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537
  1. # mypy: allow-untyped-defs
  2. import copyreg
  3. import enum
  4. import functools
  5. import warnings
  6. from collections import OrderedDict
  7. from copy import deepcopy
  8. from numbers import Number
  9. from typing import Any, Dict, Optional, Tuple, Union
  10. import torch
  11. import torch._C as _C
  12. import torch.utils.hooks as hooks
  13. from torch._namedtensor_internals import (
  14. check_serializing_named_tensor,
  15. is_ellipsis,
  16. resolve_ellipsis,
  17. single_ellipsis_index,
  18. unzip_namedshape,
  19. update_names,
  20. )
  21. from torch.overrides import (
  22. get_default_nowrap_functions,
  23. handle_torch_function,
  24. has_torch_function,
  25. has_torch_function_unary,
  26. has_torch_function_variadic,
  27. )
  28. from torch.utils.dlpack import DLDeviceType
  29. def _handle_torch_function_and_wrap_type_error_to_not_implemented(f):
  30. assigned = functools.WRAPPER_ASSIGNMENTS
  31. @functools.wraps(f, assigned=assigned)
  32. def wrapped(*args, **kwargs):
  33. try:
  34. # See https://github.com/pytorch/pytorch/issues/75462
  35. if has_torch_function(args):
  36. return handle_torch_function(wrapped, args, *args, **kwargs)
  37. return f(*args, **kwargs)
  38. except TypeError:
  39. return NotImplemented
  40. return wrapped
  41. # Should not be used, this is kept only for BC of loading old serialized Tensor subclasses
  42. def _rebuild_from_type(func, type, args, dict):
  43. if type is Tensor:
  44. return func(*args)
  45. ret = func(*args).as_subclass(type)
  46. ret.__dict__ = dict
  47. return ret
  48. def _rebuild_from_type_v2(func, new_type, args, state):
  49. ret = func(*args)
  50. if type(ret) is not new_type:
  51. ret = ret.as_subclass(new_type)
  52. # Tensor does define __setstate__ even though it doesn't define
  53. # __getstate__. So only use __setstate__ if it is NOT the one defined
  54. # on Tensor
  55. if (
  56. getattr(ret.__class__, "__setstate__", Tensor.__setstate__)
  57. is not Tensor.__setstate__
  58. ):
  59. ret.__setstate__(state)
  60. else:
  61. ret = torch._utils._set_obj_state(ret, state)
  62. return ret
  63. # NB: If you subclass Tensor, and want to share the subclassed class
  64. # across processes, you must also update torch/multiprocessing/reductions.py
  65. # to define a ForkingPickler serialization mode for the class.
  66. #
  67. # NB: If you add a new method to Tensor, you must update
  68. # torch/_C/__init__.pyi.in to add a type annotation for your method;
  69. # otherwise, it will not show up in autocomplete.
  70. class Tensor(torch._C.TensorBase):
  71. def __deepcopy__(self, memo):
  72. if has_torch_function_unary(self):
  73. return handle_torch_function(Tensor.__deepcopy__, (self,), self, memo)
  74. if not self.is_leaf:
  75. raise RuntimeError(
  76. "Only Tensors created explicitly by the user "
  77. "(graph leaves) support the deepcopy protocol at the moment. "
  78. "If you were attempting to deepcopy a module, this may be because "
  79. "of a torch.nn.utils.weight_norm usage, "
  80. "see https://github.com/pytorch/pytorch/pull/103001"
  81. )
  82. if id(self) in memo:
  83. return memo[id(self)]
  84. with torch.no_grad():
  85. # TODO: skipping storage copy is wrong for meta, as meta
  86. # does accurate alias tracking; however, the code below
  87. # doesn't work because of
  88. # https://github.com/pytorch/pytorch/issues/47442
  89. # Update the test in test_serialization if you remove 'meta' from here
  90. if (
  91. self.is_sparse
  92. or self.device.type
  93. in ["lazy", "xla", "mtia", "mps", "maia", "meta", "ipu"]
  94. or (
  95. not torch._C._has_storage(self)
  96. and self.device.type == torch._C._get_privateuse1_backend_name()
  97. )
  98. or (type(self) is not Tensor and self.data_ptr() == 0)
  99. ):
  100. new_tensor = self.clone()
  101. if type(new_tensor) is not type(self):
  102. raise RuntimeError(
  103. "The default implementation of __deepcopy__() for wrapper subclasses "
  104. "only works for subclass types that implement clone() and for which "
  105. "cloning returns another instance of the same subclass. You should either "
  106. "properly implement clone() for your subclass or override __deepcopy__() "
  107. "if it is intended behavior for clone() to return an instance of a "
  108. "different type."
  109. )
  110. else:
  111. new_storage = self._typed_storage()._deepcopy(memo)
  112. if self.is_quantized:
  113. # quantizer_params can be different type based on torch attribute
  114. quantizer_params: Union[
  115. Tuple[torch.qscheme, float, int],
  116. Tuple[torch.qscheme, Tensor, Tensor, int],
  117. ]
  118. if self.qscheme() == torch.per_tensor_affine:
  119. quantizer_params = (
  120. self.qscheme(),
  121. self.q_scale(),
  122. self.q_zero_point(),
  123. )
  124. elif self.qscheme() in (
  125. torch.per_channel_affine,
  126. torch.per_channel_affine_float_qparams,
  127. ):
  128. quantizer_params = (
  129. self.qscheme(),
  130. self.q_per_channel_scales(),
  131. self.q_per_channel_zero_points(),
  132. self.q_per_channel_axis(),
  133. )
  134. else:
  135. raise RuntimeError(
  136. f"Unsupported qscheme {self.qscheme()} in deepcopy"
  137. )
  138. # TODO: Once we decide to break serialization FC, no longer
  139. # need to wrap with TypedStorage
  140. new_tensor = torch._utils._rebuild_qtensor(
  141. torch.storage.TypedStorage(
  142. wrap_storage=new_storage._untyped_storage,
  143. dtype=self.dtype,
  144. _internal=True,
  145. ),
  146. self.storage_offset(),
  147. self.size(),
  148. self.stride(),
  149. quantizer_params,
  150. self.requires_grad,
  151. self._backward_hooks,
  152. )
  153. if type(new_tensor) is not type(self):
  154. raise RuntimeError(
  155. "The default implementation of __deepcopy__() for quantized tensors "
  156. "expects the tensor returned by torch._utils._rebuild_qtensor() to "
  157. "match the type of the instance being copied. If you encounter this, "
  158. "please open an issue on PyTorch's GitHub."
  159. )
  160. else:
  161. new_tensor = self.new_empty([])
  162. if type(new_tensor) is not type(self):
  163. raise RuntimeError(
  164. "The default implementation of __deepcopy__() for non-wrapper subclasses "
  165. "only works for subclass types that implement new_empty() and for which "
  166. "that function returns another instance of the same subclass. You should "
  167. "either properly implement new_empty() for your subclass or override "
  168. "__deepcopy__() if it is intended behavior for new_empty() to return "
  169. "an instance of a different type."
  170. )
  171. new_tensor.set_(
  172. new_storage, self.storage_offset(), self.size(), self.stride()
  173. )
  174. if self.is_conj():
  175. new_tensor = new_tensor.conj_physical()
  176. if self.is_neg():
  177. new_tensor = new_tensor.neg()
  178. if self.requires_grad:
  179. new_tensor.requires_grad_()
  180. if self.grad is not None:
  181. new_tensor.grad = self.grad.__deepcopy__(memo)
  182. if type(self) is not Tensor:
  183. if type(new_tensor) is not type(self):
  184. raise RuntimeError(
  185. "Type of deepcopy result does not match the type of the source tensor. "
  186. "If you encounter this, please open an issue on PyTorch's GitHub."
  187. )
  188. # Plain Tensors don't have slots
  189. slots_to_save = copyreg._slotnames(self.__class__) # type: ignore[attr-defined]
  190. for slot in slots_to_save:
  191. if hasattr(self, slot):
  192. setattr(new_tensor, slot, deepcopy(getattr(self, slot), memo))
  193. new_tensor.__dict__ = deepcopy(self.__dict__, memo)
  194. memo[id(self)] = new_tensor
  195. return new_tensor
  196. def __reduce_ex__(self, proto):
  197. state = torch._utils._get_obj_state(self)
  198. if type(self) is Tensor and not state:
  199. # Fast path for regular tensor without Python state.
  200. return self._reduce_ex_internal(proto)
  201. if has_torch_function_unary(self):
  202. return handle_torch_function(Tensor.__reduce_ex__, (self,), self, proto)
  203. func, args = self._reduce_ex_internal(proto)
  204. return (_rebuild_from_type_v2, (func, type(self), args, state))
  205. def storage(self):
  206. r"""
  207. storage() -> torch.TypedStorage
  208. Returns the underlying :class:`TypedStorage`.
  209. .. warning::
  210. :class:`TypedStorage` is deprecated. It will be removed in the future, and
  211. :class:`UntypedStorage` will be the only storage class. To access the
  212. :class:`UntypedStorage` directly, use :attr:`Tensor.untyped_storage()`.
  213. """
  214. if has_torch_function_unary(self):
  215. return handle_torch_function(Tensor.storage, (self,), self)
  216. torch.storage._warn_typed_storage_removal(stacklevel=2)
  217. return self._typed_storage()
  218. # For internal use only, to avoid raising deprecation warning
  219. def _typed_storage(self):
  220. untyped_storage = self.untyped_storage()
  221. return torch.TypedStorage(
  222. wrap_storage=untyped_storage, dtype=self.dtype, _internal=True
  223. )
  224. def _reduce_ex_internal(self, proto):
  225. check_serializing_named_tensor(self)
  226. # See Note [Don't serialize hooks]
  227. torch.utils.hooks.warn_if_has_hooks(self)
  228. backward_hooks: Dict[Any, Any] = OrderedDict()
  229. # Note: Numpy array is chosen to be the rebuild component for XLA, MTIA, MAIA Tensors.
  230. # We considered a few options:
  231. # 1. CPU tensor can't be used here.
  232. # Otherwise in torch.load CPU storage is reconstructed with randomly
  233. # initialized data, moved onto backend device, and then storage is updated
  234. # to the serialized content. This works perfectly for CPU/CUDA but not these backends;
  235. # their tensors are disconnected with storage so they don't get the update.
  236. # 2. Python list is not a good fit due to performance reason.
  237. # `tolist()` converts every single element in the tensor into python objects
  238. # and serialize them one by one.
  239. if self.device.type in ["xla", "mtia", "maia"] or (
  240. not torch._C._has_storage(self)
  241. and self.device.type == torch._C._get_privateuse1_backend_name()
  242. ):
  243. # Convert BFloat16 tesors to Float32 before conversion to numpy, as numpy doesn't
  244. # support BFloat16. The rebuild tensor from numpy takes in the original self.dtype,
  245. # this would reconstruct the BFloat16 tensor from numpy.
  246. numpy_tensor = (
  247. self.cpu().numpy()
  248. if self.dtype != torch.bfloat16
  249. else self.cpu().to(torch.float32).numpy()
  250. )
  251. return (
  252. torch._utils._rebuild_device_tensor_from_numpy,
  253. (numpy_tensor, self.dtype, str(self.device), self.requires_grad),
  254. )
  255. if self.device.type == "meta":
  256. # NB: This implementation BREAKS storage sharing. Current
  257. # hypothesis is that no one cares for meta tensors.
  258. arg_meta = (
  259. self.dtype,
  260. tuple(self.size()),
  261. self.stride(),
  262. self.requires_grad,
  263. )
  264. return (torch._utils._rebuild_meta_tensor_no_storage, arg_meta)
  265. if self.is_quantized:
  266. # quantizer_params can be different type based on torch attribute
  267. quantizer_params: Union[
  268. Tuple[torch.qscheme, float, int], Tuple[Any, Tensor, Tensor, int]
  269. ]
  270. if self.qscheme() == torch.per_tensor_affine:
  271. quantizer_params = (
  272. torch.per_tensor_affine,
  273. self.q_scale(),
  274. self.q_zero_point(),
  275. )
  276. elif self.qscheme() in (
  277. torch.per_channel_affine,
  278. torch.per_channel_affine_float_qparams,
  279. ):
  280. # convert scales and zero points to tuple to avoid recursive calls
  281. # when/if we get multi-axis quantized tensors in the future, the shape
  282. # is recoverable from the main tensor shape
  283. quantizer_params = (
  284. torch.per_channel_affine,
  285. self.q_per_channel_scales(),
  286. self.q_per_channel_zero_points(),
  287. self.q_per_channel_axis(),
  288. )
  289. else:
  290. raise RuntimeError(
  291. f"Serialization is not supported for tensors of type {self.qscheme()}"
  292. )
  293. # TODO: Once we decide to break serialization FC, no longer
  294. # need to wrap with TypedStorage
  295. args_qtensor = (
  296. torch.storage.TypedStorage(
  297. wrap_storage=self._typed_storage()._untyped_storage,
  298. dtype=self.dtype,
  299. _internal=True,
  300. ),
  301. self.storage_offset(),
  302. tuple(self.size()),
  303. self.stride(),
  304. quantizer_params,
  305. self.requires_grad,
  306. backward_hooks,
  307. )
  308. return (torch._utils._rebuild_qtensor, args_qtensor)
  309. elif self.is_sparse:
  310. if self.layout == torch.sparse_coo:
  311. args_sparse = (
  312. self.layout,
  313. (self._indices(), self._values(), self.size(), self.is_coalesced()),
  314. )
  315. else:
  316. raise NotImplementedError(
  317. f"sparse tensor __reduce_ex__ for layout `{self.layout}`"
  318. )
  319. return (torch._utils._rebuild_sparse_tensor, args_sparse)
  320. elif self.layout in {
  321. torch.sparse_csr,
  322. torch.sparse_csc,
  323. torch.sparse_bsr,
  324. torch.sparse_bsc,
  325. }:
  326. if self.layout in {torch.sparse_csr, torch.sparse_bsr}:
  327. compressed_indices, plain_indices = (
  328. self.crow_indices(),
  329. self.col_indices(),
  330. )
  331. else:
  332. compressed_indices, plain_indices = (
  333. self.ccol_indices(),
  334. self.row_indices(),
  335. )
  336. args_sparse_compressed = (
  337. self.layout,
  338. (
  339. compressed_indices,
  340. plain_indices,
  341. self.values(),
  342. self.size(),
  343. ),
  344. )
  345. return (torch._utils._rebuild_sparse_tensor, args_sparse_compressed)
  346. elif self.is_nested:
  347. args_nested = (
  348. # NB: values() currently returns the storage as a buffer in an unsafe way.
  349. # Ideally, we'd use a private API for this instead. TODO: Switch to this if
  350. # we ever get around to adding it.
  351. self.values(),
  352. self._nested_tensor_size(),
  353. self._nested_tensor_strides(),
  354. self._nested_tensor_storage_offsets(),
  355. )
  356. return (torch._utils._rebuild_nested_tensor, args_nested)
  357. elif (
  358. type(self) is not torch.Tensor
  359. and type(self).__torch_dispatch__ is not torch.Tensor.__torch_dispatch__
  360. and (
  361. isinstance(
  362. self,
  363. (
  364. torch._subclasses.fake_tensor.FakeTensor,
  365. torch._subclasses.functional_tensor.FunctionalTensor,
  366. ),
  367. )
  368. or self.data_ptr() == 0
  369. )
  370. ):
  371. arg_wrapper_subclass = (
  372. type(self),
  373. self.dtype,
  374. tuple(self.size()),
  375. self.stride(),
  376. self.storage_offset(),
  377. self.layout,
  378. self.device,
  379. self.requires_grad,
  380. )
  381. return (torch._utils._rebuild_wrapper_subclass, arg_wrapper_subclass)
  382. else:
  383. v3_dtypes = torch.storage._new_dtypes()
  384. if self.dtype in v3_dtypes:
  385. rebuild_func = torch._utils._rebuild_tensor_v3
  386. storage = self.untyped_storage()
  387. else:
  388. # TODO: Once we decide to break serialization FC, no longer
  389. # need to wrap with TypedStorage
  390. rebuild_func = torch._utils._rebuild_tensor_v2 # type: ignore[assignment]
  391. storage = torch.storage.TypedStorage(
  392. wrap_storage=self._typed_storage()._untyped_storage,
  393. dtype=self.dtype,
  394. _internal=True,
  395. ) # type: ignore[assignment]
  396. args = (
  397. storage,
  398. self.storage_offset(),
  399. tuple(self.size()),
  400. self.stride(),
  401. self.requires_grad,
  402. backward_hooks,
  403. ) # previously was self._backward_hooks
  404. if isinstance(storage, torch.storage.UntypedStorage):
  405. args = args + (self.dtype,) # type: ignore[assignment]
  406. metadata = torch._utils.get_tensor_metadata(self)
  407. if metadata:
  408. args = args + (metadata,) # type: ignore[assignment]
  409. return (rebuild_func, args)
  410. def __setstate__(self, state):
  411. if has_torch_function_unary(self):
  412. return handle_torch_function(Tensor.__setstate__, (self,), self, state)
  413. # Warning: this method is NOT called when you torch.load() a tensor;
  414. # that is managed by _rebuild_tensor_v2
  415. if not self.is_leaf:
  416. raise RuntimeError("__setstate__ can be only called on leaf Tensors")
  417. if len(state) == 4:
  418. # legacy serialization of Tensor
  419. self.set_(*state)
  420. return
  421. elif len(state) == 5:
  422. # legacy serialization of Variable
  423. self.data = state[0]
  424. state = (state[3], state[4], state[2])
  425. # The setting of _backward_hooks is expected to be a no-op.
  426. # See Note [Don't serialize hooks]
  427. self.requires_grad, _, self._backward_hooks = state
  428. def __repr__(self, *, tensor_contents=None):
  429. if has_torch_function_unary(self):
  430. return handle_torch_function(
  431. Tensor.__repr__, (self,), self, tensor_contents=tensor_contents
  432. )
  433. # All strings are unicode in Python 3.
  434. return torch._tensor_str._str(self, tensor_contents=tensor_contents)
  435. def backward(
  436. self, gradient=None, retain_graph=None, create_graph=False, inputs=None
  437. ):
  438. r"""Computes the gradient of current tensor wrt graph leaves.
  439. The graph is differentiated using the chain rule. If the tensor is
  440. non-scalar (i.e. its data has more than one element) and requires
  441. gradient, the function additionally requires specifying a ``gradient``.
  442. It should be a tensor of matching type and shape, that represents
  443. the gradient of the differentiated function w.r.t. ``self``.
  444. This function accumulates gradients in the leaves - you might need to zero
  445. ``.grad`` attributes or set them to ``None`` before calling it.
  446. See :ref:`Default gradient layouts<default-grad-layouts>`
  447. for details on the memory layout of accumulated gradients.
  448. .. note::
  449. If you run any forward ops, create ``gradient``, and/or call ``backward``
  450. in a user-specified CUDA stream context, see
  451. :ref:`Stream semantics of backward passes<bwd-cuda-stream-semantics>`.
  452. .. note::
  453. When ``inputs`` are provided and a given input is not a leaf,
  454. the current implementation will call its grad_fn (though it is not strictly needed to get this gradients).
  455. It is an implementation detail on which the user should not rely.
  456. See https://github.com/pytorch/pytorch/pull/60521#issuecomment-867061780 for more details.
  457. Args:
  458. gradient (Tensor, optional): The gradient of the function
  459. being differentiated w.r.t. ``self``.
  460. This argument can be omitted if ``self`` is a scalar.
  461. retain_graph (bool, optional): If ``False``, the graph used to compute
  462. the grads will be freed. Note that in nearly all cases setting
  463. this option to True is not needed and often can be worked around
  464. in a much more efficient way. Defaults to the value of
  465. ``create_graph``.
  466. create_graph (bool, optional): If ``True``, graph of the derivative will
  467. be constructed, allowing to compute higher order derivative
  468. products. Defaults to ``False``.
  469. inputs (sequence of Tensor, optional): Inputs w.r.t. which the gradient will be
  470. accumulated into ``.grad``. All other tensors will be ignored. If not
  471. provided, the gradient is accumulated into all the leaf Tensors that were
  472. used to compute the :attr:`tensors`.
  473. """
  474. if has_torch_function_unary(self):
  475. return handle_torch_function(
  476. Tensor.backward,
  477. (self,),
  478. self,
  479. gradient=gradient,
  480. retain_graph=retain_graph,
  481. create_graph=create_graph,
  482. inputs=inputs,
  483. )
  484. torch.autograd.backward(
  485. self, gradient, retain_graph, create_graph, inputs=inputs
  486. )
  487. def register_hook(self, hook):
  488. r"""Registers a backward hook.
  489. The hook will be called every time a gradient with respect to the
  490. Tensor is computed. The hook should have the following signature::
  491. hook(grad) -> Tensor or None
  492. The hook should not modify its argument, but it can optionally return
  493. a new gradient which will be used in place of :attr:`grad`.
  494. This function returns a handle with a method ``handle.remove()``
  495. that removes the hook from the module.
  496. .. note::
  497. See :ref:`backward-hooks-execution` for more information on how when this hook
  498. is executed, and how its execution is ordered relative to other hooks.
  499. Example::
  500. >>> v = torch.tensor([0., 0., 0.], requires_grad=True)
  501. >>> h = v.register_hook(lambda grad: grad * 2) # double the gradient
  502. >>> v.backward(torch.tensor([1., 2., 3.]))
  503. >>> v.grad
  504. 2
  505. 4
  506. 6
  507. [torch.FloatTensor of size (3,)]
  508. >>> h.remove() # removes the hook
  509. """
  510. if has_torch_function_unary(self):
  511. return handle_torch_function(Tensor.register_hook, (self,), self, hook)
  512. if not self.requires_grad:
  513. raise RuntimeError(
  514. "cannot register a hook on a tensor that doesn't require gradient"
  515. )
  516. if self._backward_hooks is None:
  517. self._backward_hooks = OrderedDict()
  518. if self.grad_fn is not None:
  519. self.grad_fn._register_hook_dict(self)
  520. handle = hooks.RemovableHandle(self._backward_hooks)
  521. self._backward_hooks[handle.id] = hook
  522. return handle
  523. def register_post_accumulate_grad_hook(self, hook):
  524. r"""Registers a backward hook that runs after grad accumulation.
  525. The hook will be called after all gradients for a tensor have been accumulated,
  526. meaning that the .grad field has been updated on that tensor. The post
  527. accumulate grad hook is ONLY applicable for leaf tensors (tensors without a
  528. .grad_fn field). Registering this hook on a non-leaf tensor will error!
  529. The hook should have the following signature::
  530. hook(param: Tensor) -> None
  531. Note that, unlike other autograd hooks, this hook operates on the tensor
  532. that requires grad and not the grad itself. The hook can in-place modify
  533. and access its Tensor argument, including its .grad field.
  534. This function returns a handle with a method ``handle.remove()``
  535. that removes the hook from the module.
  536. .. note::
  537. See :ref:`backward-hooks-execution` for more information on how when this hook
  538. is executed, and how its execution is ordered relative to other hooks. Since
  539. this hook runs during the backward pass, it will run in no_grad mode (unless
  540. create_graph is True). You can use torch.enable_grad() to re-enable autograd
  541. within the hook if you need it.
  542. Example::
  543. >>> v = torch.tensor([0., 0., 0.], requires_grad=True)
  544. >>> lr = 0.01
  545. >>> # simulate a simple SGD update
  546. >>> h = v.register_post_accumulate_grad_hook(lambda p: p.add_(p.grad, alpha=-lr))
  547. >>> v.backward(torch.tensor([1., 2., 3.]))
  548. >>> v
  549. tensor([-0.0100, -0.0200, -0.0300], requires_grad=True)
  550. >>> h.remove() # removes the hook
  551. """
  552. if has_torch_function_unary(self):
  553. return handle_torch_function(
  554. Tensor.register_post_accumulate_grad_hook, (self,), self, hook
  555. )
  556. if not self.requires_grad:
  557. raise RuntimeError(
  558. "cannot register a hook on a tensor that doesn't require gradient"
  559. )
  560. if self.grad_fn is not None:
  561. raise RuntimeError(
  562. "post accumulate grad hooks cannot be registered on non-leaf tensors"
  563. )
  564. if self._post_accumulate_grad_hooks is None:
  565. self._post_accumulate_grad_hooks: Dict[Any, Any] = OrderedDict()
  566. handle = hooks.RemovableHandle(self._post_accumulate_grad_hooks)
  567. self._post_accumulate_grad_hooks[handle.id] = hook
  568. return handle
  569. def reinforce(self, reward):
  570. def trim(str):
  571. return "\n".join([line.strip() for line in str.split("\n")])
  572. raise RuntimeError(
  573. trim(
  574. r"""reinforce() was removed.
  575. Use torch.distributions instead.
  576. See https://pytorch.org/docs/main/distributions.html
  577. Instead of:
  578. probs = policy_network(state)
  579. action = probs.multinomial()
  580. next_state, reward = env.step(action)
  581. action.reinforce(reward)
  582. action.backward()
  583. Use:
  584. probs = policy_network(state)
  585. # NOTE: categorical is equivalent to what used to be called multinomial
  586. m = torch.distributions.Categorical(probs)
  587. action = m.sample()
  588. next_state, reward = env.step(action)
  589. loss = -m.log_prob(action) * reward
  590. loss.backward()
  591. """
  592. )
  593. )
  594. detach = _C._add_docstr(
  595. _C.TensorBase.detach,
  596. r"""
  597. Returns a new Tensor, detached from the current graph.
  598. The result will never require gradient.
  599. This method also affects forward mode AD gradients and the result will never
  600. have forward mode AD gradients.
  601. .. note::
  602. Returned Tensor shares the same storage with the original one.
  603. In-place modifications on either of them will be seen, and may trigger
  604. errors in correctness checks.
  605. """,
  606. )
  607. detach_ = _C._add_docstr(
  608. _C.TensorBase.detach_,
  609. r"""
  610. Detaches the Tensor from the graph that created it, making it a leaf.
  611. Views cannot be detached in-place.
  612. This method also affects forward mode AD gradients and the result will never
  613. have forward mode AD gradients.
  614. """,
  615. )
  616. def is_shared(self):
  617. r"""Checks if tensor is in shared memory.
  618. This is always ``True`` for CUDA tensors.
  619. """
  620. if has_torch_function_unary(self):
  621. return handle_torch_function(Tensor.is_shared, (self,), self)
  622. return self._typed_storage()._is_shared()
  623. def share_memory_(self):
  624. r"""Moves the underlying storage to shared memory.
  625. This is a no-op if the underlying storage is already in shared memory
  626. and for CUDA tensors. Tensors in shared memory cannot be resized.
  627. See :meth:`torch.UntypedStorage.share_memory_` for more details.
  628. """
  629. if has_torch_function_unary(self):
  630. return handle_torch_function(Tensor.share_memory_, (self,), self)
  631. self._typed_storage()._share_memory_()
  632. return self
  633. def module_load(self, other, assign=False):
  634. r"""Defines how to transform ``other`` when loading it into ``self`` in :meth:`~nn.Module.load_state_dict`.
  635. Used when :func:`~torch.__future__.get_swap_module_params_on_conversion` is ``True``.
  636. It is expected that ``self`` is a parameter or buffer in an ``nn.Module`` and ``other`` is the
  637. value in the state dictionary with the corresponding key, this method defines
  638. how ``other`` is remapped before being swapped with ``self`` via
  639. :func:`~torch.utils.swap_tensors`` in ``module.load_state_dict()``.
  640. .. note::
  641. This method should always return a new object that is not ``self`` or ``other``.
  642. For example, the default implementation returns ``self.copy_(other).detach()``
  643. if ``assign`` is ``False`` or ``other.detach()`` if ``assign`` is ``True``.
  644. Args:
  645. other (Tensor): value in state dict with key corresponding to ``self``
  646. assign (bool): the assign argument passed to :meth:`nn.Module.load_state_dict`
  647. """
  648. if has_torch_function_variadic(self, other):
  649. return handle_torch_function(
  650. Tensor.module_load, (self, other), self, other, assign=assign
  651. )
  652. if assign:
  653. return other.detach()
  654. else:
  655. return self.copy_(other).detach()
  656. def __reversed__(self):
  657. r"""Reverses the tensor along dimension 0."""
  658. if has_torch_function_unary(self):
  659. return handle_torch_function(Tensor.__reversed__, (self,), self)
  660. if self.dim() == 0:
  661. return self
  662. else:
  663. return self.flip(0)
  664. def norm(
  665. self,
  666. p: Optional[Union[float, str]] = "fro",
  667. dim=None,
  668. keepdim=False,
  669. dtype=None,
  670. ):
  671. r"""See :func:`torch.norm`"""
  672. if has_torch_function_unary(self):
  673. return handle_torch_function(
  674. Tensor.norm, (self,), self, p=p, dim=dim, keepdim=keepdim, dtype=dtype
  675. )
  676. return torch.norm(self, p, dim, keepdim, dtype=dtype)
  677. def solve(self, other):
  678. from ._linalg_utils import solve
  679. return solve(self, other)
  680. def lstsq(self, other):
  681. from ._linalg_utils import lstsq
  682. return lstsq(self, other)
  683. def eig(self, eigenvectors=False):
  684. from ._linalg_utils import eig
  685. return eig(self, eigenvectors=eigenvectors)
  686. def symeig(self, eigenvectors=False):
  687. from ._linalg_utils import _symeig
  688. return _symeig(self, eigenvectors=eigenvectors)
  689. def lu(self, pivot=True, get_infos=False):
  690. r"""See :func:`torch.lu`"""
  691. # If get_infos is True, then we don't need to check for errors and vice versa
  692. if has_torch_function_unary(self):
  693. return handle_torch_function(
  694. Tensor.lu, (self,), self, pivot=pivot, get_infos=get_infos
  695. )
  696. LU, pivots, infos = torch._lu_with_info(
  697. self, pivot=pivot, check_errors=(not get_infos)
  698. )
  699. if get_infos:
  700. return LU, pivots, infos
  701. else:
  702. return LU, pivots
  703. def stft(
  704. self,
  705. n_fft: int,
  706. hop_length: Optional[int] = None,
  707. win_length: Optional[int] = None,
  708. window: "Optional[Tensor]" = None,
  709. center: bool = True,
  710. pad_mode: str = "reflect",
  711. normalized: bool = False,
  712. onesided: Optional[bool] = None,
  713. return_complex: Optional[bool] = None,
  714. ):
  715. r"""See :func:`torch.stft`
  716. .. warning::
  717. This function changed signature at version 0.4.1. Calling with
  718. the previous signature may cause error or return incorrect result.
  719. """
  720. if has_torch_function_unary(self):
  721. return handle_torch_function(
  722. Tensor.stft,
  723. (self,),
  724. self,
  725. n_fft,
  726. hop_length=hop_length,
  727. win_length=win_length,
  728. window=window,
  729. center=center,
  730. pad_mode=pad_mode,
  731. normalized=normalized,
  732. onesided=onesided,
  733. return_complex=return_complex,
  734. )
  735. return torch.stft(
  736. self,
  737. n_fft,
  738. hop_length,
  739. win_length,
  740. window,
  741. center,
  742. pad_mode,
  743. normalized,
  744. onesided,
  745. return_complex=return_complex,
  746. )
  747. def istft(
  748. self,
  749. n_fft: int,
  750. hop_length: Optional[int] = None,
  751. win_length: Optional[int] = None,
  752. window: "Optional[Tensor]" = None,
  753. center: bool = True,
  754. normalized: bool = False,
  755. onesided: Optional[bool] = None,
  756. length: Optional[int] = None,
  757. return_complex: bool = False,
  758. ):
  759. r"""See :func:`torch.istft`"""
  760. if has_torch_function_unary(self):
  761. return handle_torch_function(
  762. Tensor.istft,
  763. (self,),
  764. self,
  765. n_fft,
  766. hop_length=hop_length,
  767. win_length=win_length,
  768. window=window,
  769. center=center,
  770. normalized=normalized,
  771. onesided=onesided,
  772. length=length,
  773. return_complex=return_complex,
  774. )
  775. return torch.istft(
  776. self,
  777. n_fft,
  778. hop_length,
  779. win_length,
  780. window,
  781. center,
  782. normalized,
  783. onesided,
  784. length,
  785. return_complex=return_complex,
  786. )
  787. def resize(self, *sizes):
  788. if has_torch_function_unary(self):
  789. return handle_torch_function(Tensor.resize, (self,), self, *sizes)
  790. warnings.warn("non-inplace resize is deprecated")
  791. from torch.autograd._functions import Resize
  792. return Resize.apply(self, sizes)
  793. def resize_as(self, tensor):
  794. if has_torch_function_variadic(self, tensor):
  795. return handle_torch_function(Tensor.resize_as, (self, tensor), self, tensor)
  796. warnings.warn("non-inplace resize_as is deprecated")
  797. from torch.autograd._functions import Resize
  798. return Resize.apply(self, tensor.size())
  799. def split(self, split_size, dim=0):
  800. r"""See :func:`torch.split`"""
  801. if has_torch_function_unary(self):
  802. return handle_torch_function(
  803. Tensor.split, (self,), self, split_size, dim=dim
  804. )
  805. if isinstance(split_size, Tensor):
  806. try:
  807. split_size = int(split_size)
  808. except ValueError:
  809. pass
  810. if isinstance(split_size, (int, torch.SymInt)):
  811. return torch._VF.split(self, split_size, dim) # type: ignore[attr-defined]
  812. else:
  813. return torch._VF.split_with_sizes(self, split_size, dim)
  814. def unique(self, sorted=True, return_inverse=False, return_counts=False, dim=None):
  815. r"""Returns the unique elements of the input tensor.
  816. See :func:`torch.unique`
  817. """
  818. if has_torch_function_unary(self):
  819. return handle_torch_function(
  820. Tensor.unique,
  821. (self,),
  822. self,
  823. sorted=sorted,
  824. return_inverse=return_inverse,
  825. return_counts=return_counts,
  826. dim=dim,
  827. )
  828. return torch.unique(
  829. self,
  830. sorted=sorted,
  831. return_inverse=return_inverse,
  832. return_counts=return_counts,
  833. dim=dim,
  834. )
  835. def unique_consecutive(self, return_inverse=False, return_counts=False, dim=None):
  836. r"""Eliminates all but the first element from every consecutive group of equivalent elements.
  837. See :func:`torch.unique_consecutive`
  838. """
  839. if has_torch_function_unary(self):
  840. return handle_torch_function(
  841. Tensor.unique_consecutive,
  842. (self,),
  843. self,
  844. return_inverse=return_inverse,
  845. return_counts=return_counts,
  846. dim=dim,
  847. )
  848. return torch.unique_consecutive(
  849. self, return_inverse=return_inverse, return_counts=return_counts, dim=dim
  850. )
  851. @_handle_torch_function_and_wrap_type_error_to_not_implemented
  852. def __rsub__(self, other):
  853. return _C._VariableFunctions.rsub(self, other)
  854. @_handle_torch_function_and_wrap_type_error_to_not_implemented
  855. def __rdiv__(self, other):
  856. return self.reciprocal() * other
  857. __rtruediv__ = __rdiv__
  858. __itruediv__ = _C.TensorBase.__idiv__
  859. __pow__ = _handle_torch_function_and_wrap_type_error_to_not_implemented(
  860. _C.TensorBase.pow
  861. )
  862. __ipow__ = _handle_torch_function_and_wrap_type_error_to_not_implemented(
  863. _C.TensorBase.pow_
  864. )
  865. @_handle_torch_function_and_wrap_type_error_to_not_implemented
  866. def __rmod__(self, other):
  867. return torch.remainder(other, self)
  868. def __format__(self, format_spec):
  869. if has_torch_function_unary(self):
  870. return handle_torch_function(Tensor.__format__, (self,), self, format_spec)
  871. if self.dim() == 0 and not self.is_meta and type(self) is Tensor:
  872. return self.item().__format__(format_spec)
  873. return object.__format__(self, format_spec)
  874. @_handle_torch_function_and_wrap_type_error_to_not_implemented
  875. def __rpow__(self, other):
  876. return torch.pow(other, self)
  877. @_handle_torch_function_and_wrap_type_error_to_not_implemented
  878. def __floordiv__(self, other):
  879. return torch.floor_divide(self, other)
  880. @_handle_torch_function_and_wrap_type_error_to_not_implemented
  881. def __rfloordiv__(self, other):
  882. return torch.floor_divide(other, self)
  883. @_handle_torch_function_and_wrap_type_error_to_not_implemented
  884. def __rlshift__(self, other):
  885. return torch.bitwise_left_shift(other, self)
  886. @_handle_torch_function_and_wrap_type_error_to_not_implemented
  887. def __rrshift__(self, other):
  888. return torch.bitwise_right_shift(other, self)
  889. @_handle_torch_function_and_wrap_type_error_to_not_implemented
  890. def __rmatmul__(self, other):
  891. return torch.matmul(other, self)
  892. __pos__ = _C.TensorBase.positive
  893. __neg__ = _C.TensorBase.neg
  894. __abs__ = _C.TensorBase.abs
  895. def __len__(self):
  896. if has_torch_function_unary(self):
  897. return handle_torch_function(Tensor.__len__, (self,), self)
  898. if self.dim() == 0:
  899. raise TypeError("len() of a 0-d tensor")
  900. if torch._C._get_tracing_state():
  901. warnings.warn(
  902. "Using len to get tensor shape might cause the trace to be incorrect. "
  903. "Recommended usage would be tensor.shape[0]. "
  904. "Passing a tensor of different shape might lead to errors or silently give "
  905. "incorrect results.",
  906. category=torch.jit.TracerWarning,
  907. stacklevel=2,
  908. )
  909. return self.shape[0]
  910. def __iter__(self):
  911. # NB: we use 'imap' and not 'map' here, so that in Python 2 we get a
  912. # generator and don't eagerly perform all the indexes. This could
  913. # save us work, and also helps keep trace ordering deterministic
  914. # (e.g., if you zip(*hiddens), the eager map will force all the
  915. # indexes of hiddens[0] before hiddens[1], while the generator
  916. # map will interleave them.)
  917. # NB: We have intentionally skipped __torch_function__ dispatch here.
  918. # See gh-54457
  919. if self.dim() == 0:
  920. raise TypeError("iteration over a 0-d tensor")
  921. if torch._C._get_tracing_state():
  922. warnings.warn(
  923. "Iterating over a tensor might cause the trace to be incorrect. "
  924. "Passing a tensor of different shape won't change the number of "
  925. "iterations executed (and might lead to errors or silently give "
  926. "incorrect results).",
  927. category=torch.jit.TracerWarning,
  928. stacklevel=2,
  929. )
  930. return iter(self.unbind(0))
  931. def __hash__(self):
  932. # Do NOT handle __torch_function__ here as user's default
  933. # implementation that handle most functions will most likely do it wrong.
  934. # It can be easily overridden by defining this method on the user
  935. # subclass if needed.
  936. return id(self)
  937. def __dir__(self):
  938. if has_torch_function_unary(self):
  939. return handle_torch_function(Tensor.__dir__, (self,), self)
  940. tensor_methods = dir(self.__class__)
  941. tensor_methods.remove("volatile") # deprecated
  942. attrs = list(self.__dict__.keys())
  943. keys = tensor_methods + attrs
  944. # property only available dense, cuda tensors
  945. if (not self.is_cuda) or self.is_sparse:
  946. keys.remove("__cuda_array_interface__")
  947. return sorted(keys)
  948. # Numpy array interface, to support `numpy.asarray(tensor) -> ndarray`
  949. __array_priority__ = 1000 # prefer Tensor ops over numpy ones
  950. def __array__(self, dtype=None):
  951. if has_torch_function_unary(self):
  952. return handle_torch_function(Tensor.__array__, (self,), self, dtype=dtype)
  953. if dtype is None:
  954. return self.numpy()
  955. else:
  956. return self.numpy().astype(dtype, copy=False)
  957. # Wrap Numpy array again in a suitable tensor when done, to support e.g.
  958. # `numpy.sin(tensor) -> tensor` or `numpy.greater(tensor, 0) -> ByteTensor`
  959. def __array_wrap__(self, array):
  960. if has_torch_function_unary(self):
  961. return handle_torch_function(
  962. Tensor.__array_wrap__, (self,), self, array=array
  963. )
  964. if array.dtype == bool:
  965. # Workaround, torch has no built-in bool tensor
  966. array = array.astype("uint8")
  967. return torch.from_numpy(array)
  968. def __contains__(self, element):
  969. r"""Check if `element` is present in tensor
  970. Args:
  971. element (Tensor or scalar): element to be checked
  972. for presence in current tensor"
  973. """
  974. if has_torch_function_unary(self):
  975. return handle_torch_function(Tensor.__contains__, (self,), self, element)
  976. if isinstance(
  977. element, (torch.Tensor, Number, torch.SymInt, torch.SymFloat, torch.SymBool)
  978. ):
  979. # type hint doesn't understand the __contains__ result array
  980. return (element == self).any().item() # type: ignore[union-attr]
  981. raise RuntimeError(
  982. f"Tensor.__contains__ only supports Tensor or scalar, but you passed in a {type(element)}."
  983. )
  984. @property
  985. def __cuda_array_interface__(self):
  986. """Array view description for cuda tensors.
  987. See:
  988. https://numba.pydata.org/numba-doc/latest/cuda/cuda_array_interface.html
  989. """
  990. if has_torch_function_unary(self):
  991. # TODO mypy doesn't support @property, see: https://github.com/python/mypy/issues/6185
  992. return handle_torch_function(Tensor.__cuda_array_interface__.__get__, (self,), self) # type: ignore[attr-defined]
  993. # raise AttributeError for unsupported tensors, so that
  994. # hasattr(cpu_tensor, "__cuda_array_interface__") is False.
  995. if not self.is_cuda:
  996. raise AttributeError(
  997. f"Can't get __cuda_array_interface__ on non-CUDA tensor type: {self.type()} "
  998. "If CUDA data is required use tensor.cuda() to copy tensor to device memory."
  999. )
  1000. if self.is_sparse:
  1001. raise AttributeError(
  1002. f"Can't get __cuda_array_interface__ on sparse type: {self.type()} "
  1003. "Use Tensor.to_dense() to convert to a dense tensor first."
  1004. )
  1005. # RuntimeError, matching tensor.__array__() behavior.
  1006. if self.requires_grad:
  1007. raise RuntimeError(
  1008. "Can't get __cuda_array_interface__ on Variable that requires grad. "
  1009. "If gradients aren't required, use var.detach() to get Variable that doesn't require grad."
  1010. )
  1011. # CUDA devices are little-endian and tensors are stored in native byte
  1012. # order. 1-byte entries are endian-agnostic.
  1013. typestr = {
  1014. torch.complex64: "<c8",
  1015. torch.complex128: "<c16",
  1016. torch.float16: "<f2",
  1017. torch.float32: "<f4",
  1018. torch.float64: "<f8",
  1019. torch.uint8: "|u1",
  1020. torch.int8: "|i1",
  1021. torch.int16: "<i2",
  1022. torch.int32: "<i4",
  1023. torch.int64: "<i8",
  1024. }[self.dtype]
  1025. itemsize = self.element_size()
  1026. shape = tuple(self.shape)
  1027. if self.is_contiguous():
  1028. # __cuda_array_interface__ v2 requires the strides to be omitted
  1029. # (either not set or set to None) for C-contiguous arrays.
  1030. strides = None
  1031. else:
  1032. strides = tuple(s * itemsize for s in self.stride())
  1033. data_ptr = self.data_ptr() if self.numel() > 0 else 0
  1034. data = (data_ptr, False) # read-only is false
  1035. return dict(typestr=typestr, shape=shape, strides=strides, data=data, version=2)
  1036. def storage_type(self):
  1037. r"""storage_type() -> type
  1038. Returns the type of the underlying storage.
  1039. """
  1040. if has_torch_function_unary(self):
  1041. return handle_torch_function(Tensor.storage_type, (self,), self)
  1042. torch.storage._warn_typed_storage_removal()
  1043. return self._typed_storage()._get_legacy_storage_class()
  1044. def refine_names(self, *names):
  1045. r"""Refines the dimension names of :attr:`self` according to :attr:`names`.
  1046. Refining is a special case of renaming that "lifts" unnamed dimensions.
  1047. A ``None`` dim can be refined to have any name; a named dim can only be
  1048. refined to have the same name.
  1049. Because named tensors can coexist with unnamed tensors, refining names
  1050. gives a nice way to write named-tensor-aware code that works with both
  1051. named and unnamed tensors.
  1052. :attr:`names` may contain up to one Ellipsis (``...``).
  1053. The Ellipsis is expanded greedily; it is expanded in-place to fill
  1054. :attr:`names` to the same length as ``self.dim()`` using names from the
  1055. corresponding indices of ``self.names``.
  1056. Python 2 does not support Ellipsis but one may use a string literal
  1057. instead (``'...'``).
  1058. Args:
  1059. names (iterable of str): The desired names of the output tensor. May
  1060. contain up to one Ellipsis.
  1061. Examples::
  1062. >>> imgs = torch.randn(32, 3, 128, 128)
  1063. >>> named_imgs = imgs.refine_names('N', 'C', 'H', 'W')
  1064. >>> named_imgs.names
  1065. ('N', 'C', 'H', 'W')
  1066. >>> tensor = torch.randn(2, 3, 5, 7, 11)
  1067. >>> tensor = tensor.refine_names('A', ..., 'B', 'C')
  1068. >>> tensor.names
  1069. ('A', None, None, 'B', 'C')
  1070. .. warning::
  1071. The named tensor API is experimental and subject to change.
  1072. """
  1073. if has_torch_function_unary(self):
  1074. return handle_torch_function(Tensor.refine_names, (self,), self, *names)
  1075. names = resolve_ellipsis(names, self.names, "refine_names")
  1076. return super().refine_names(names)
  1077. def align_to(self, *names):
  1078. r"""Permutes the dimensions of the :attr:`self` tensor to match the order
  1079. specified in :attr:`names`, adding size-one dims for any new names.
  1080. All of the dims of :attr:`self` must be named in order to use this method.
  1081. The resulting tensor is a view on the original tensor.
  1082. All dimension names of :attr:`self` must be present in :attr:`names`.
  1083. :attr:`names` may contain additional names that are not in ``self.names``;
  1084. the output tensor has a size-one dimension for each of those new names.
  1085. :attr:`names` may contain up to one Ellipsis (``...``).
  1086. The Ellipsis is expanded to be equal to all dimension names of :attr:`self`
  1087. that are not mentioned in :attr:`names`, in the order that they appear
  1088. in :attr:`self`.
  1089. Python 2 does not support Ellipsis but one may use a string literal
  1090. instead (``'...'``).
  1091. Args:
  1092. names (iterable of str): The desired dimension ordering of the
  1093. output tensor. May contain up to one Ellipsis that is expanded
  1094. to all unmentioned dim names of :attr:`self`.
  1095. Examples::
  1096. >>> tensor = torch.randn(2, 2, 2, 2, 2, 2)
  1097. >>> named_tensor = tensor.refine_names('A', 'B', 'C', 'D', 'E', 'F')
  1098. # Move the F and E dims to the front while keeping the rest in order
  1099. >>> named_tensor.align_to('F', 'E', ...)
  1100. .. warning::
  1101. The named tensor API is experimental and subject to change.
  1102. """
  1103. if has_torch_function_unary(self):
  1104. return handle_torch_function(Tensor.align_to, (self,), self, *names)
  1105. ellipsis_idx = single_ellipsis_index(names, "align_to")
  1106. if ellipsis_idx is None:
  1107. return super().align_to(names)
  1108. return super().align_to(
  1109. [name for name in names if not is_ellipsis(name)], ellipsis_idx
  1110. )
  1111. def unflatten(self, dim, sizes):
  1112. r"""
  1113. unflatten(dim, sizes) -> Tensor
  1114. See :func:`torch.unflatten`.
  1115. """
  1116. if has_torch_function_unary(self):
  1117. return handle_torch_function(Tensor.unflatten, (self,), self, dim, sizes)
  1118. if not sizes:
  1119. raise RuntimeError("unflatten: sizes must be non-empty")
  1120. names = None
  1121. if isinstance(sizes, OrderedDict) or (
  1122. isinstance(sizes, (tuple, list)) and isinstance(sizes[0], (tuple, list))
  1123. ):
  1124. names, sizes = unzip_namedshape(sizes)
  1125. return super().unflatten(dim, sizes, names)
  1126. else:
  1127. return super().unflatten(dim, sizes)
  1128. def rename_(self, *names, **rename_map):
  1129. """In-place version of :meth:`~Tensor.rename`."""
  1130. if has_torch_function_unary(self):
  1131. return handle_torch_function(
  1132. Tensor.rename_, (self,), self, *names, **rename_map
  1133. )
  1134. # Note [rename_ / rename API]
  1135. # The Python API for these is different from the C++ API. In Python:
  1136. # 1) tensor.rename(*names) takes a vararglist of names
  1137. # 2) tensor.rename(**rename_map) takes a map of names to rename.
  1138. # C++ is static, making it difficult to implement similar behavior.
  1139. return update_names(self, names, rename_map, inplace=True)
  1140. def rename(self, *names, **rename_map):
  1141. """Renames dimension names of :attr:`self`.
  1142. There are two main usages:
  1143. ``self.rename(**rename_map)`` returns a view on tensor that has dims
  1144. renamed as specified in the mapping :attr:`rename_map`.
  1145. ``self.rename(*names)`` returns a view on tensor, renaming all
  1146. dimensions positionally using :attr:`names`.
  1147. Use ``self.rename(None)`` to drop names on a tensor.
  1148. One cannot specify both positional args :attr:`names` and keyword args
  1149. :attr:`rename_map`.
  1150. Examples::
  1151. >>> imgs = torch.rand(2, 3, 5, 7, names=('N', 'C', 'H', 'W'))
  1152. >>> renamed_imgs = imgs.rename(N='batch', C='channels')
  1153. >>> renamed_imgs.names
  1154. ('batch', 'channels', 'H', 'W')
  1155. >>> renamed_imgs = imgs.rename(None)
  1156. >>> renamed_imgs.names
  1157. (None, None, None, None)
  1158. >>> renamed_imgs = imgs.rename('batch', 'channel', 'height', 'width')
  1159. >>> renamed_imgs.names
  1160. ('batch', 'channel', 'height', 'width')
  1161. .. warning::
  1162. The named tensor API is experimental and subject to change.
  1163. """
  1164. if has_torch_function_unary(self):
  1165. return handle_torch_function(
  1166. Tensor.rename, (self,), self, *names, **rename_map
  1167. )
  1168. # See Note [rename_ / rename API]
  1169. return update_names(self, names, rename_map, inplace=False)
  1170. def to_sparse_coo(self):
  1171. """Convert a tensor to :ref:`coordinate format <sparse-coo-docs>`.
  1172. Examples::
  1173. >>> dense = torch.randn(5, 5)
  1174. >>> sparse = dense.to_sparse_coo()
  1175. >>> sparse._nnz()
  1176. 25
  1177. """
  1178. return self.to_sparse()
  1179. def dim_order(self):
  1180. """
  1181. dim_order() -> tuple
  1182. Returns a tuple of int describing the dim order or physical layout of :attr:`self`.
  1183. Args:
  1184. None
  1185. Dim order represents how dimensions are laid out in memory,
  1186. starting from the outermost to the innermost dimension.
  1187. Example::
  1188. >>> torch.empty((2, 3, 5, 7)).dim_order()
  1189. (0, 1, 2, 3)
  1190. >>> torch.empty((2, 3, 5, 7), memory_format=torch.channels_last).dim_order()
  1191. (0, 2, 3, 1)
  1192. .. warning::
  1193. The dim_order tensor API is experimental and subject to change.
  1194. """
  1195. if has_torch_function_unary(self):
  1196. return handle_torch_function(Tensor.dim_order, (self,), self)
  1197. import torch._prims_common as utils
  1198. return tuple(utils.compute_elementwise_output_logical_to_physical_perm(self))
  1199. def _update_names(self, names, inplace):
  1200. if has_torch_function_unary(self):
  1201. return handle_torch_function(
  1202. Tensor._update_names, (self,), self, names, inplace
  1203. )
  1204. # See Note [rename_ / rename API]
  1205. if inplace:
  1206. return super().rename_(names)
  1207. else:
  1208. return super().rename(names)
  1209. @classmethod
  1210. def __torch_function__(cls, func, types, args=(), kwargs=None):
  1211. """
  1212. This __torch_function__ implementation wraps subclasses such that
  1213. methods called on subclasses return a subclass instance instead of
  1214. a ``torch.Tensor`` instance.
  1215. One corollary to this is that you need coverage for torch.Tensor
  1216. methods if implementing __torch_function__ for subclasses.
  1217. We recommend always calling ``super().__torch_function__`` as the base
  1218. case when doing the above.
  1219. While not mandatory, we recommend making `__torch_function__` a classmethod.
  1220. """
  1221. if kwargs is None:
  1222. kwargs = {}
  1223. if not all(issubclass(cls, t) for t in types):
  1224. return NotImplemented
  1225. with _C.DisableTorchFunctionSubclass():
  1226. ret = func(*args, **kwargs)
  1227. if func in get_default_nowrap_functions():
  1228. return ret
  1229. else:
  1230. return _convert(ret, cls)
  1231. __torch_dispatch__ = _C._disabled_torch_dispatch_impl
  1232. def __dlpack__(self, stream=None):
  1233. """
  1234. Creates a DLpack `capsule https://data-apis.org/array-api/latest/design_topics/data_interchange.html#data-interchange`_
  1235. of the current tensor to be exported to other libraries.
  1236. This function will be called from the `from_dlpack` method
  1237. of the library that will consume the capsule. `from_dlpack` passes the current
  1238. stream to this method as part of the specification.
  1239. Args:
  1240. stream (integer or None): An optional Python integer representing a
  1241. pointer to a CUDA stream. The current stream is synchronized with
  1242. this stream before the capsule is created, and since the capsule
  1243. shares its storage with the tensor this make it safe to access from
  1244. both streams. If None or -1 is passed then no synchronization is performed.
  1245. If 1 (on CUDA) or 0 (on ROCM) then the default stream is used for
  1246. synchronization.
  1247. """
  1248. if has_torch_function_unary(self):
  1249. return handle_torch_function(Tensor.__dlpack__, (self,), self, stream)
  1250. # DLPack capsules can't capture all of PyTorch's semantics,
  1251. # so we prohibit exporting tensors that would lose their properties like
  1252. # requires_grad and having the conjugate bit set.
  1253. if self.requires_grad:
  1254. raise RuntimeError(
  1255. "Can't export tensors that require gradient, use tensor.detach()"
  1256. )
  1257. if self.is_conj():
  1258. raise RuntimeError("Can't export tensors with the conjugate bit set")
  1259. if self.layout != torch.strided:
  1260. raise RuntimeError(
  1261. "Can't export tensors with layout other than torch.strided"
  1262. )
  1263. if stream is not None and type(stream) is not int:
  1264. # Stream pointers in CUDA/ROCm are uniquely numbered and can
  1265. # be retrieved from their integer value.
  1266. raise TypeError("stream must be ``int`` or ``none``")
  1267. elif stream is not None and stream != -1:
  1268. if self.device.type == "cuda":
  1269. # NB: This logic handles the special case values for default
  1270. # streams and must be kept in sync with from_dlpack in
  1271. # torch/utils/dlpack.py
  1272. if stream == 1 and torch.version.hip is None:
  1273. stream = torch.cuda.default_stream()
  1274. elif stream == 0 and torch.version.hip is not None:
  1275. stream = torch.cuda.default_stream()
  1276. else:
  1277. stream = torch.cuda.ExternalStream(stream)
  1278. # Only synchronize on different streams
  1279. sync_stream = torch.cuda.current_stream()
  1280. if stream != sync_stream:
  1281. event = torch.cuda.Event()
  1282. event.record(sync_stream)
  1283. stream.wait_event(event)
  1284. return torch.to_dlpack(self)
  1285. def __dlpack_device__(self) -> Tuple[enum.IntEnum, int]:
  1286. if has_torch_function_unary(self):
  1287. return handle_torch_function(Tensor.__dlpack_device__, (self,), self)
  1288. device = self.device
  1289. idx = device.index if device.index is not None else 0
  1290. torch_device_type = device.type
  1291. if torch_device_type == "cuda" and torch.version.hip is not None:
  1292. device_type = DLDeviceType.kDLROCM
  1293. elif torch_device_type == "cpu" and self.is_pinned():
  1294. device_type = DLDeviceType.kDLCPUPinned
  1295. elif torch_device_type == "cuda":
  1296. device_type = DLDeviceType.kDLGPU
  1297. elif torch_device_type == "cpu":
  1298. device_type = DLDeviceType.kDLCPU
  1299. elif self.device.type == "xpu":
  1300. device_type = DLDeviceType.kDLOneAPI
  1301. else:
  1302. raise ValueError(f"Unknown device type {torch_device_type} for Dlpack")
  1303. return (device_type, idx)
  1304. __module__ = "torch"
  1305. def _convert(ret, cls):
  1306. if cls is Tensor:
  1307. return ret
  1308. if isinstance(ret, Tensor) and not isinstance(ret, cls):
  1309. ret = ret.as_subclass(cls)
  1310. if isinstance(ret, (tuple, list)):
  1311. # Also handles things like namedtuples
  1312. ret = type(ret)(_convert(r, cls) for r in ret)
  1313. return ret