_tensor.py 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  1. from collections import OrderedDict
  2. import enum
  3. import functools
  4. from numbers import Number
  5. from typing import Any, Dict, Optional, Tuple, Union
  6. import warnings
  7. import copyreg
  8. from copy import deepcopy
  9. import torch
  10. import torch._C as _C
  11. from torch._namedtensor_internals import (
  12. update_names, check_serializing_named_tensor, resolve_ellipsis,
  13. unzip_namedshape, single_ellipsis_index, is_ellipsis)
  14. from torch.overrides import (
  15. has_torch_function, has_torch_function_unary, has_torch_function_variadic,
  16. handle_torch_function, get_default_nowrap_functions)
  17. import torch.utils.hooks as hooks
  18. def _handle_torch_function_and_wrap_type_error_to_not_implemented(f):
  19. # functools.wraps doesn't work well with methods in python 2
  20. method_assignments = ('__name__', '__doc__')
  21. assigned = functools.WRAPPER_ASSIGNMENTS
  22. @functools.wraps(f, assigned=assigned)
  23. def wrapped(*args, **kwargs):
  24. try:
  25. # See https://github.com/pytorch/pytorch/issues/75462
  26. if has_torch_function(args):
  27. return handle_torch_function(wrapped, args, *args, **kwargs)
  28. return f(*args, **kwargs)
  29. except TypeError:
  30. return NotImplemented
  31. return wrapped
  32. # Should not be used, this is kept only for BC of loading old serialized Tensor subclasses
  33. def _rebuild_from_type(func, type, args, dict):
  34. if type is Tensor:
  35. return func(*args)
  36. ret = func(*args).as_subclass(type)
  37. ret.__dict__ = dict
  38. return ret
  39. def _rebuild_from_type_v2(func, new_type, args, state):
  40. if new_type is Tensor:
  41. return func(*args)
  42. ret = func(*args)
  43. if type(ret) is not new_type:
  44. ret = ret.as_subclass(new_type)
  45. # Tensor does define __setstate__ even though it doesn't define
  46. # __getstate__. So only use __setstate__ if it is NOT the one defined
  47. # on Tensor
  48. if getattr(ret.__class__, "__setstate__", Tensor.__setstate__) is not Tensor.__setstate__:
  49. ret.__setstate__(state)
  50. else:
  51. if isinstance(state, tuple):
  52. if not len(state) == 2:
  53. raise RuntimeError(f"Invalid serialized state: {state}")
  54. dict_state = state[0]
  55. slots_state = state[1]
  56. else:
  57. dict_state = state
  58. slots_state = None
  59. for k, v in dict_state.items():
  60. setattr(ret, k, v)
  61. if slots_state:
  62. for k, v in slots_state.items():
  63. setattr(ret, k, v)
  64. return ret
  65. # NB: If you subclass Tensor, and want to share the subclassed class
  66. # across processes, you must also update torch/multiprocessing/reductions.py
  67. # to define a ForkingPickler serialization mode for the class.
  68. #
  69. # NB: If you add a new method to Tensor, you must update
  70. # torch/__init__.py.in to add a type annotation for your method;
  71. # otherwise, it will not show up in autocomplete.
  72. class Tensor(torch._C._TensorBase):
  73. def __deepcopy__(self, memo):
  74. if has_torch_function_unary(self):
  75. return handle_torch_function(Tensor.__deepcopy__, (self,), self, memo)
  76. if not self.is_leaf:
  77. raise RuntimeError("Only Tensors created explicitly by the user "
  78. "(graph leaves) support the deepcopy protocol at the moment")
  79. if id(self) in memo:
  80. return memo[id(self)]
  81. with torch.no_grad():
  82. # TODO: skipping storage copy is wrong for meta, as meta
  83. # does accurate alias tracking; however, the code below
  84. # doesn't work because of
  85. # https://github.com/pytorch/pytorch/issues/47442
  86. # Update the test in test_serialization if you remove 'meta' from here
  87. if self.is_sparse or self.device.type in ['lazy', 'xla', 'mps', 'ort', 'meta', 'hpu'] or \
  88. (type(self) is not Tensor and self.data_ptr() == 0):
  89. new_tensor = self.clone()
  90. if type(new_tensor) is not type(self):
  91. raise RuntimeError("The default implementation of __deepcopy__() for wrapper subclasses "
  92. "only works for subclass types that implement clone() and for which "
  93. "cloning returns another instance of the same subclass. You should either "
  94. "properly implement clone() for your subclass or override __deepcopy__() "
  95. "if it is intended behavior for clone() to return an instance of a "
  96. "different type.")
  97. else:
  98. new_storage = self.storage().__deepcopy__(memo)
  99. if self.is_quantized:
  100. # quantizer_params can be different type based on torch attribute
  101. quantizer_params: Union[Tuple[torch.qscheme, float, int], Tuple[torch.qscheme, Tensor, Tensor, int]]
  102. if self.qscheme() == torch.per_tensor_affine:
  103. quantizer_params = self.qscheme(), self.q_scale(), self.q_zero_point()
  104. elif self.qscheme() in (torch.per_channel_affine, torch.per_channel_affine_float_qparams):
  105. quantizer_params = self.qscheme(), \
  106. self.q_per_channel_scales(), \
  107. self.q_per_channel_zero_points(), \
  108. self.q_per_channel_axis()
  109. else:
  110. raise RuntimeError(f"Unsupported qscheme {self.qscheme()} in deepcopy")
  111. # TODO: Once we decide to break serialization FC, no longer
  112. # need to wrap with _TypedStorage
  113. new_tensor = torch._utils._rebuild_qtensor(
  114. torch.storage._TypedStorage(
  115. wrap_storage=new_storage._untyped(),
  116. dtype=self.dtype),
  117. self.storage_offset(),
  118. self.size(),
  119. self.stride(),
  120. quantizer_params,
  121. self.requires_grad,
  122. self._backward_hooks)
  123. if type(new_tensor) is not type(self):
  124. raise RuntimeError("The default implementation of __deepcopy__() for quantized tensors "
  125. "expects the tensor returned by torch._utils._rebuild_qtensor() to "
  126. "match the type of the instance being copied. If you encounter this, "
  127. "please open an issue on PyTorch's GitHub.")
  128. else:
  129. new_tensor = self.new_empty([])
  130. if type(new_tensor) is not type(self):
  131. raise RuntimeError("The default implementation of __deepcopy__() for non-wrapper subclasses "
  132. "only works for subclass types that implement new_empty() and for which "
  133. "that function returns another instance of the same subclass. You should "
  134. "either properly implement new_empty() for your subclass or override "
  135. "__deepcopy__() if it is intended behavior for new_empty() to return "
  136. "an instance of a different type.")
  137. new_tensor.set_(new_storage, self.storage_offset(), self.size(), self.stride())
  138. if self.is_conj():
  139. new_tensor = new_tensor.conj_physical()
  140. if self.is_neg():
  141. new_tensor = new_tensor.neg()
  142. if self.requires_grad:
  143. new_tensor.requires_grad_()
  144. if self.grad is not None:
  145. new_tensor.grad = self.grad.__deepcopy__(memo)
  146. if not type(self) is Tensor:
  147. if type(new_tensor) is not type(self):
  148. raise RuntimeError("Type of deepcopy result does not match the type of the source tensor. "
  149. "If you encounter this, please open an issue on PyTorch's GitHub.")
  150. # Plain Tensors don't have slots
  151. slots_to_save = copyreg._slotnames(self.__class__) # type: ignore[attr-defined]
  152. for slot in slots_to_save:
  153. if hasattr(self, slot):
  154. setattr(new_tensor, slot, deepcopy(getattr(self, slot), memo))
  155. new_tensor.__dict__ = deepcopy(self.__dict__, memo)
  156. memo[id(self)] = new_tensor
  157. return new_tensor
  158. def __reduce_ex__(self, proto):
  159. if type(self) is Tensor:
  160. return self._reduce_ex_internal(proto)
  161. if has_torch_function_unary(self):
  162. return handle_torch_function(Tensor.__reduce_ex__, (self,), self, proto)
  163. func, args = self._reduce_ex_internal(proto)
  164. # Get the state of the python subclass
  165. # This loosely mimicks the function on the object class but since Tensor do not inherit
  166. # from it, we cannot call that function directly
  167. # https://github.com/python/cpython/blob/c83919bd635f4433f1c6ae8504996a9fe3c215e5/Objects/typeobject.c#L4891
  168. getstate_fn = getattr(self, "__getstate__", None)
  169. if getstate_fn:
  170. state = getstate_fn()
  171. else:
  172. slots_to_save = copyreg._slotnames(self.__class__) # type: ignore[attr-defined]
  173. if slots_to_save:
  174. state = (self.__dict__, {name: getattr(self, name) for name in slots_to_save if hasattr(self, name)})
  175. else:
  176. state = self.__dict__
  177. return (_rebuild_from_type_v2, (func, type(self), args, state))
  178. def storage(self):
  179. r"""
  180. storage() -> torch.Storage
  181. Returns the underlying storage.
  182. """
  183. if has_torch_function_unary(self):
  184. return handle_torch_function(Tensor.storage, (self,), self)
  185. return torch._TypedStorage(wrap_storage=self._storage(), dtype=self.dtype)
  186. def _reduce_ex_internal(self, proto):
  187. check_serializing_named_tensor(self)
  188. # See Note [Don't serialize hooks]
  189. torch.utils.hooks.warn_if_has_hooks(self)
  190. backward_hooks: Dict[Any, Any] = OrderedDict()
  191. # Note: Numpy array is chosen to be the rebuild component for XLA, ORT Tensors.
  192. # We considered a few options:
  193. # 1. CPU tensor can't be used here.
  194. # Otherwise in torch.load CPU storage is reconstructed with randomly
  195. # initialized data, moved onto backend device, and then storage is updated
  196. # to the serialized content. This works perfectly for CPU/CUDA but not these backends;
  197. # their tensors are disconnected with storage so they don't get the update.
  198. # 2. Python list is not a good fit due to performance reason.
  199. # `tolist()` converts every single element in the tensor into python objects
  200. # and serialize them one by one.
  201. if self.device.type in ['xla', 'ort', 'mps', 'hpu']:
  202. return (torch._utils._rebuild_device_tensor_from_numpy, (self.cpu().numpy(),
  203. self.dtype,
  204. str(self.device),
  205. self.requires_grad))
  206. if self.device.type == 'meta':
  207. # NB: This implementation BREAKS storage sharing. Current
  208. # hypothesis is that no one cares for meta tensors.
  209. arg_meta = (
  210. self.dtype,
  211. tuple(self.size()),
  212. self.stride(),
  213. self.requires_grad,
  214. )
  215. return (torch._utils._rebuild_meta_tensor_no_storage, arg_meta)
  216. if self.is_quantized:
  217. # quantizer_params can be different type based on torch attribute
  218. quantizer_params: Union[Tuple[torch.qscheme, float, int], Tuple[Any, Tensor, Tensor, int]]
  219. if self.qscheme() == torch.per_tensor_affine:
  220. quantizer_params = (torch.per_tensor_affine,
  221. self.q_scale(),
  222. self.q_zero_point())
  223. elif self.qscheme() in (torch.per_channel_affine, torch.per_channel_affine_float_qparams):
  224. # convert scales and zero points to tuple to avoid recursive calls
  225. # when/if we get multi-axis quantized tensors in the future, the shape
  226. # is recoverable from the main tensor shape
  227. quantizer_params = (torch.per_channel_affine,
  228. self.q_per_channel_scales(),
  229. self.q_per_channel_zero_points(),
  230. self.q_per_channel_axis())
  231. else:
  232. raise RuntimeError(f"Serialization is not supported for tensors of type {self.qscheme()}")
  233. # TODO: Once we decide to break serialization FC, no longer
  234. # need to wrap with _TypedStorage
  235. args_qtensor = (
  236. torch.storage._TypedStorage(
  237. wrap_storage=self.storage()._untyped(),
  238. dtype=self.dtype),
  239. self.storage_offset(),
  240. tuple(self.size()),
  241. self.stride(),
  242. quantizer_params,
  243. self.requires_grad,
  244. backward_hooks)
  245. return (torch._utils._rebuild_qtensor, args_qtensor)
  246. elif self.is_sparse:
  247. if self.layout == torch.sparse_coo:
  248. args_sparse = (self.layout,
  249. (self._indices(),
  250. self._values(),
  251. self.size()))
  252. else:
  253. raise NotImplementedError(
  254. 'sparse tensor __reduce_ex__ for layout `%s`' % (self.layout))
  255. return (torch._utils._rebuild_sparse_tensor, args_sparse)
  256. elif self.is_sparse_csr:
  257. if self.layout == torch.sparse_csr:
  258. args_sparse_csr = (self.layout,
  259. (self.crow_indices(),
  260. self.col_indices(),
  261. self.values(),
  262. self.size()))
  263. else:
  264. raise NotImplementedError(
  265. 'sparse csr tensor __reduce_ex__ for layout `%s`' % (self.layout))
  266. return (torch._utils._rebuild_sparse_csr_tensor, args_sparse_csr)
  267. elif self.data_ptr() == 0 and type(self) is not torch.Tensor:
  268. arg_wrapper_subclass = (
  269. type(self),
  270. self.dtype,
  271. tuple(self.size()),
  272. self.stride(),
  273. self.storage_offset(),
  274. self.layout,
  275. self.device,
  276. self.requires_grad
  277. )
  278. return (torch._utils._rebuild_wrapper_subclass, arg_wrapper_subclass)
  279. else:
  280. # TODO: Once we decide to break serialization FC, no longer
  281. # need to wrap with _TypedStorage
  282. args = (
  283. torch.storage._TypedStorage(
  284. wrap_storage=self.storage()._untyped(),
  285. dtype=self.dtype),
  286. self.storage_offset(),
  287. tuple(self.size()),
  288. self.stride(),
  289. self.requires_grad,
  290. backward_hooks) # previously was self._backward_hooks
  291. return (torch._utils._rebuild_tensor_v2, args)
  292. def __setstate__(self, state):
  293. if has_torch_function_unary(self):
  294. return handle_torch_function(Tensor.__setstate__, (self,), self, state)
  295. # Warning: this method is NOT called when you torch.load() a tensor;
  296. # that is managed by _rebuild_tensor_v2
  297. if not self.is_leaf:
  298. raise RuntimeError('__setstate__ can be only called on leaf Tensors')
  299. if len(state) == 4:
  300. # legacy serialization of Tensor
  301. self.set_(*state)
  302. return
  303. elif len(state) == 5:
  304. # legacy serialization of Variable
  305. self.data = state[0]
  306. state = (state[3], state[4], state[2])
  307. # The setting of _backward_hooks is expected to be a no-op.
  308. # See Note [Don't serialize hooks]
  309. self.requires_grad, _, self._backward_hooks = state
  310. def __repr__(self, *, tensor_contents=None):
  311. if has_torch_function_unary(self):
  312. return handle_torch_function(Tensor.__repr__, (self,), self,
  313. tensor_contents=tensor_contents)
  314. # All strings are unicode in Python 3.
  315. return torch._tensor_str._str(self, tensor_contents=tensor_contents)
  316. def backward(self, gradient=None, retain_graph=None, create_graph=False, inputs=None):
  317. r"""Computes the gradient of current tensor w.r.t. graph leaves.
  318. The graph is differentiated using the chain rule. If the tensor is
  319. non-scalar (i.e. its data has more than one element) and requires
  320. gradient, the function additionally requires specifying ``gradient``.
  321. It should be a tensor of matching type and location, that contains
  322. the gradient of the differentiated function w.r.t. ``self``.
  323. This function accumulates gradients in the leaves - you might need to zero
  324. ``.grad`` attributes or set them to ``None`` before calling it.
  325. See :ref:`Default gradient layouts<default-grad-layouts>`
  326. for details on the memory layout of accumulated gradients.
  327. .. note::
  328. If you run any forward ops, create ``gradient``, and/or call ``backward``
  329. in a user-specified CUDA stream context, see
  330. :ref:`Stream semantics of backward passes<bwd-cuda-stream-semantics>`.
  331. .. note::
  332. When ``inputs`` are provided and a given input is not a leaf,
  333. the current implementation will call its grad_fn (though it is not strictly needed to get this gradients).
  334. It is an implementation detail on which the user should not rely.
  335. See https://github.com/pytorch/pytorch/pull/60521#issuecomment-867061780 for more details.
  336. Args:
  337. gradient (Tensor or None): Gradient w.r.t. the
  338. tensor. If it is a tensor, it will be automatically converted
  339. to a Tensor that does not require grad unless ``create_graph`` is True.
  340. None values can be specified for scalar Tensors or ones that
  341. don't require grad. If a None value would be acceptable then
  342. this argument is optional.
  343. retain_graph (bool, optional): If ``False``, the graph used to compute
  344. the grads will be freed. Note that in nearly all cases setting
  345. this option to True is not needed and often can be worked around
  346. in a much more efficient way. Defaults to the value of
  347. ``create_graph``.
  348. create_graph (bool, optional): If ``True``, graph of the derivative will
  349. be constructed, allowing to compute higher order derivative
  350. products. Defaults to ``False``.
  351. inputs (sequence of Tensor): Inputs w.r.t. which the gradient will be
  352. accumulated into ``.grad``. All other Tensors will be ignored. If not
  353. provided, the gradient is accumulated into all the leaf Tensors that were
  354. used to compute the attr::tensors.
  355. """
  356. if has_torch_function_unary(self):
  357. return handle_torch_function(
  358. Tensor.backward,
  359. (self,),
  360. self,
  361. gradient=gradient,
  362. retain_graph=retain_graph,
  363. create_graph=create_graph,
  364. inputs=inputs)
  365. torch.autograd.backward(self, gradient, retain_graph, create_graph, inputs=inputs)
  366. def register_hook(self, hook):
  367. r"""Registers a backward hook.
  368. The hook will be called every time a gradient with respect to the
  369. Tensor is computed. The hook should have the following signature::
  370. hook(grad) -> Tensor or None
  371. The hook should not modify its argument, but it can optionally return
  372. a new gradient which will be used in place of :attr:`grad`.
  373. This function returns a handle with a method ``handle.remove()``
  374. that removes the hook from the module.
  375. Example::
  376. >>> v = torch.tensor([0., 0., 0.], requires_grad=True)
  377. >>> h = v.register_hook(lambda grad: grad * 2) # double the gradient
  378. >>> v.backward(torch.tensor([1., 2., 3.]))
  379. >>> v.grad
  380. 2
  381. 4
  382. 6
  383. [torch.FloatTensor of size (3,)]
  384. >>> h.remove() # removes the hook
  385. """
  386. if has_torch_function_unary(self):
  387. return handle_torch_function(Tensor.register_hook, (self,), self, hook)
  388. if not self.requires_grad:
  389. raise RuntimeError("cannot register a hook on a tensor that "
  390. "doesn't require gradient")
  391. if self._backward_hooks is None:
  392. self._backward_hooks = OrderedDict()
  393. if self.grad_fn is not None:
  394. self.grad_fn._register_hook_dict(self)
  395. handle = hooks.RemovableHandle(self._backward_hooks)
  396. self._backward_hooks[handle.id] = hook
  397. return handle
  398. def reinforce(self, reward):
  399. def trim(str):
  400. return '\n'.join([line.strip() for line in str.split('\n')])
  401. raise RuntimeError(trim(r"""reinforce() was removed.
  402. Use torch.distributions instead.
  403. See https://pytorch.org/docs/master/distributions.html
  404. Instead of:
  405. probs = policy_network(state)
  406. action = probs.multinomial()
  407. next_state, reward = env.step(action)
  408. action.reinforce(reward)
  409. action.backward()
  410. Use:
  411. probs = policy_network(state)
  412. # NOTE: categorical is equivalent to what used to be called multinomial
  413. m = torch.distributions.Categorical(probs)
  414. action = m.sample()
  415. next_state, reward = env.step(action)
  416. loss = -m.log_prob(action) * reward
  417. loss.backward()
  418. """))
  419. detach = _C._add_docstr(_C._TensorBase.detach, r"""
  420. Returns a new Tensor, detached from the current graph.
  421. The result will never require gradient.
  422. This method also affects forward mode AD gradients and the result will never
  423. have forward mode AD gradients.
  424. .. note::
  425. Returned Tensor shares the same storage with the original one.
  426. In-place modifications on either of them will be seen, and may trigger
  427. errors in correctness checks.
  428. IMPORTANT NOTE: Previously, in-place size / stride / storage changes
  429. (such as `resize_` / `resize_as_` / `set_` / `transpose_`) to the returned tensor
  430. also update the original tensor. Now, these in-place changes will not update the
  431. original tensor anymore, and will instead trigger an error.
  432. For sparse tensors:
  433. In-place indices / values changes (such as `zero_` / `copy_` / `add_`) to the
  434. returned tensor will not update the original tensor anymore, and will instead
  435. trigger an error.
  436. """)
  437. detach_ = _C._add_docstr(_C._TensorBase.detach_, r"""
  438. Detaches the Tensor from the graph that created it, making it a leaf.
  439. Views cannot be detached in-place.
  440. This method also affects forward mode AD gradients and the result will never
  441. have forward mode AD gradients.
  442. """)
  443. def is_shared(self):
  444. r"""Checks if tensor is in shared memory.
  445. This is always ``True`` for CUDA tensors.
  446. """
  447. if has_torch_function_unary(self):
  448. return handle_torch_function(Tensor.is_shared, (self,), self)
  449. return self.storage().is_shared()
  450. def share_memory_(self):
  451. r"""Moves the underlying storage to shared memory.
  452. This is a no-op if the underlying storage is already in shared memory
  453. and for CUDA tensors. Tensors in shared memory cannot be resized.
  454. """
  455. if has_torch_function_unary(self):
  456. return handle_torch_function(Tensor.share_memory_, (self,), self)
  457. self.storage().share_memory_()
  458. return self
  459. def __reversed__(self):
  460. r"""Reverses the tensor along dimension 0."""
  461. if has_torch_function_unary(self):
  462. return handle_torch_function(Tensor.__reversed__, (self,), self)
  463. if self.dim() == 0:
  464. return self
  465. else:
  466. return self.flip(0)
  467. def norm(self, p="fro", dim=None, keepdim=False, dtype=None):
  468. r"""See :func:`torch.norm`"""
  469. if has_torch_function_unary(self):
  470. return handle_torch_function(Tensor.norm, (self,), self, p=p, dim=dim, keepdim=keepdim, dtype=dtype)
  471. return torch.norm(self, p, dim, keepdim, dtype=dtype)
  472. def solve(self, other):
  473. from ._linalg_utils import solve
  474. return solve(self, other)
  475. def lu(self, pivot=True, get_infos=False):
  476. r"""See :func:`torch.lu`"""
  477. # If get_infos is True, then we don't need to check for errors and vice versa
  478. if has_torch_function_unary(self):
  479. return handle_torch_function(Tensor.lu, (self,), self, pivot=pivot, get_infos=get_infos)
  480. LU, pivots, infos = torch._lu_with_info(self, pivot=pivot, check_errors=(not get_infos))
  481. if get_infos:
  482. return LU, pivots, infos
  483. else:
  484. return LU, pivots
  485. def stft(self, n_fft: int, hop_length: Optional[int] = None,
  486. win_length: Optional[int] = None, window: 'Optional[Tensor]' = None,
  487. center: bool = True, pad_mode: str = 'reflect', normalized: bool = False,
  488. onesided: Optional[bool] = None, return_complex: Optional[bool] = None):
  489. r"""See :func:`torch.stft`
  490. .. warning::
  491. This function changed signature at version 0.4.1. Calling with
  492. the previous signature may cause error or return incorrect result.
  493. """
  494. if has_torch_function_unary(self):
  495. return handle_torch_function(
  496. Tensor.stft, (self,), self, n_fft, hop_length=hop_length,
  497. win_length=win_length, window=window, center=center, pad_mode=pad_mode, normalized=normalized,
  498. onesided=onesided, return_complex=return_complex
  499. )
  500. return torch.stft(self, n_fft, hop_length, win_length, window, center,
  501. pad_mode, normalized, onesided, return_complex=return_complex)
  502. def istft(self, n_fft: int, hop_length: Optional[int] = None,
  503. win_length: Optional[int] = None, window: 'Optional[Tensor]' = None,
  504. center: bool = True, normalized: bool = False,
  505. onesided: Optional[bool] = None, length: Optional[int] = None,
  506. return_complex: bool = False):
  507. r"""See :func:`torch.istft`"""
  508. if has_torch_function_unary(self):
  509. return handle_torch_function(
  510. Tensor.istft, (self,), self, n_fft, hop_length=hop_length, win_length=win_length,
  511. window=window, center=center, normalized=normalized, onesided=onesided, length=length,
  512. return_complex=return_complex
  513. )
  514. return torch.istft(self, n_fft, hop_length, win_length, window, center,
  515. normalized, onesided, length, return_complex=return_complex)
  516. def resize(self, *sizes):
  517. if has_torch_function_unary(self):
  518. return handle_torch_function(Tensor.resize, (self,), self, *sizes)
  519. warnings.warn("non-inplace resize is deprecated")
  520. from torch.autograd._functions import Resize
  521. return Resize.apply(self, sizes)
  522. def resize_as(self, tensor):
  523. if has_torch_function_variadic(self, tensor):
  524. return handle_torch_function(Tensor.resize_as, (self, tensor), self, tensor)
  525. warnings.warn("non-inplace resize_as is deprecated")
  526. from torch.autograd._functions import Resize
  527. return Resize.apply(self, tensor.size())
  528. def split(self, split_size, dim=0):
  529. r"""See :func:`torch.split`
  530. """
  531. if has_torch_function_unary(self):
  532. return handle_torch_function(Tensor.split, (self,), self, split_size, dim=dim)
  533. if isinstance(split_size, int):
  534. return super(Tensor, self).split(split_size, dim)
  535. elif isinstance(split_size, Tensor):
  536. try:
  537. split_size = int(split_size)
  538. return super(Tensor, self).split(split_size, dim)
  539. except ValueError:
  540. return super(Tensor, self).split_with_sizes(split_size, dim)
  541. else:
  542. return super(Tensor, self).split_with_sizes(split_size, dim)
  543. def unique(self, sorted=True, return_inverse=False, return_counts=False, dim=None):
  544. r"""Returns the unique elements of the input tensor.
  545. See :func:`torch.unique`
  546. """
  547. if has_torch_function_unary(self):
  548. return handle_torch_function(
  549. Tensor.unique, (self,), self, sorted=sorted, return_inverse=return_inverse,
  550. return_counts=return_counts, dim=dim
  551. )
  552. return torch.unique(self, sorted=sorted, return_inverse=return_inverse, return_counts=return_counts, dim=dim)
  553. def unique_consecutive(self, return_inverse=False, return_counts=False, dim=None):
  554. r"""Eliminates all but the first element from every consecutive group of equivalent elements.
  555. See :func:`torch.unique_consecutive`
  556. """
  557. if has_torch_function_unary(self):
  558. return handle_torch_function(
  559. Tensor.unique_consecutive, (self,), self, return_inverse=return_inverse,
  560. return_counts=return_counts, dim=dim
  561. )
  562. return torch.unique_consecutive(self, return_inverse=return_inverse, return_counts=return_counts, dim=dim)
  563. @_handle_torch_function_and_wrap_type_error_to_not_implemented
  564. def __rsub__(self, other):
  565. return _C._VariableFunctions.rsub(self, other)
  566. @_handle_torch_function_and_wrap_type_error_to_not_implemented
  567. def __rdiv__(self, other):
  568. return self.reciprocal() * other
  569. __rtruediv__ = __rdiv__
  570. __itruediv__ = _C._TensorBase.__idiv__
  571. __pow__ = _handle_torch_function_and_wrap_type_error_to_not_implemented(_C._TensorBase.pow)
  572. __ipow__ = _handle_torch_function_and_wrap_type_error_to_not_implemented(_C._TensorBase.pow_)
  573. @_handle_torch_function_and_wrap_type_error_to_not_implemented
  574. def __rmod__(self, other):
  575. return torch.remainder(other, self)
  576. def __format__(self, format_spec):
  577. if has_torch_function_unary(self):
  578. return handle_torch_function(Tensor.__format__, (self,), self, format_spec)
  579. if self.dim() == 0 and not self.is_meta:
  580. return self.item().__format__(format_spec)
  581. return object.__format__(self, format_spec)
  582. @_handle_torch_function_and_wrap_type_error_to_not_implemented
  583. def __rpow__(self, other):
  584. dtype = torch.result_type(other, self)
  585. return torch.tensor(other, dtype=dtype, device=self.device) ** self
  586. @_handle_torch_function_and_wrap_type_error_to_not_implemented
  587. def __floordiv__(self, other):
  588. warnings.warn("__floordiv__ is deprecated, and its behavior will change in a future version of pytorch. "
  589. "It currently rounds toward 0 (like the 'trunc' function NOT 'floor'). "
  590. "This results in incorrect rounding for negative values. "
  591. "To keep the current behavior, use torch.div(a, b, rounding_mode='trunc'), "
  592. "or for actual floor division, use torch.div(a, b, rounding_mode='floor').", stacklevel=3)
  593. return torch.div(self, other, rounding_mode='trunc')
  594. @_handle_torch_function_and_wrap_type_error_to_not_implemented
  595. def __rfloordiv__(self, other):
  596. warnings.warn("__rfloordiv__ is deprecated, and its behavior will change in a future version of pytorch. "
  597. "It currently rounds toward 0 (like the 'trunc' function NOT 'floor'). "
  598. "This results in incorrect rounding for negative values. "
  599. "To keep the current behavior, use torch.div(a, b, rounding_mode='trunc'), "
  600. "or for actual floor division, use torch.div(a, b, rounding_mode='floor').", stacklevel=3)
  601. return torch.div(other, self, rounding_mode='trunc')
  602. @_handle_torch_function_and_wrap_type_error_to_not_implemented
  603. def __rlshift__(self, other):
  604. return torch.bitwise_left_shift(other, self)
  605. @_handle_torch_function_and_wrap_type_error_to_not_implemented
  606. def __rrshift__(self, other):
  607. return torch.bitwise_right_shift(other, self)
  608. @_handle_torch_function_and_wrap_type_error_to_not_implemented
  609. def __rmatmul__(self, other):
  610. return torch.matmul(other, self)
  611. __pos__ = _C._TensorBase.positive
  612. __neg__ = _C._TensorBase.neg
  613. __abs__ = _C._TensorBase.abs
  614. def __len__(self):
  615. if has_torch_function_unary(self):
  616. return handle_torch_function(Tensor.__len__, (self,), self)
  617. if self.dim() == 0:
  618. raise TypeError("len() of a 0-d tensor")
  619. if torch._C._get_tracing_state():
  620. warnings.warn('Using len to get tensor shape might cause the trace to be incorrect. '
  621. 'Recommended usage would be tensor.shape[0]. '
  622. 'Passing a tensor of different shape might lead to errors or silently give '
  623. 'incorrect results.', category=torch.jit.TracerWarning, stacklevel=2)
  624. return self.shape[0]
  625. def __iter__(self):
  626. # NB: we use 'imap' and not 'map' here, so that in Python 2 we get a
  627. # generator and don't eagerly perform all the indexes. This could
  628. # save us work, and also helps keep trace ordering deterministic
  629. # (e.g., if you zip(*hiddens), the eager map will force all the
  630. # indexes of hiddens[0] before hiddens[1], while the generator
  631. # map will interleave them.)
  632. # NB: We have intentionally skipped __torch_function__ dispatch here.
  633. # See gh-54457
  634. if self.dim() == 0:
  635. raise TypeError('iteration over a 0-d tensor')
  636. if torch._C._get_tracing_state():
  637. warnings.warn('Iterating over a tensor might cause the trace to be incorrect. '
  638. 'Passing a tensor of different shape won\'t change the number of '
  639. 'iterations executed (and might lead to errors or silently give '
  640. 'incorrect results).', category=torch.jit.TracerWarning, stacklevel=2)
  641. return iter(self.unbind(0))
  642. def __hash__(self):
  643. if has_torch_function_unary(self):
  644. return handle_torch_function(Tensor.__hash__, (self,), self)
  645. return id(self)
  646. def __dir__(self):
  647. if has_torch_function_unary(self):
  648. return handle_torch_function(Tensor.__dir__, (self,), self)
  649. tensor_methods = dir(self.__class__)
  650. tensor_methods.remove('volatile') # deprecated
  651. attrs = list(self.__dict__.keys())
  652. keys = tensor_methods + attrs
  653. # property only available dense, cuda tensors
  654. if (not self.is_cuda) or self.is_sparse:
  655. keys.remove("__cuda_array_interface__")
  656. return sorted(keys)
  657. # Numpy array interface, to support `numpy.asarray(tensor) -> ndarray`
  658. __array_priority__ = 1000 # prefer Tensor ops over numpy ones
  659. def __array__(self, dtype=None):
  660. if has_torch_function_unary(self):
  661. return handle_torch_function(Tensor.__array__, (self,), self, dtype=dtype)
  662. if dtype is None:
  663. return self.numpy()
  664. else:
  665. return self.numpy().astype(dtype, copy=False)
  666. # Wrap Numpy array again in a suitable tensor when done, to support e.g.
  667. # `numpy.sin(tensor) -> tensor` or `numpy.greater(tensor, 0) -> ByteTensor`
  668. def __array_wrap__(self, array):
  669. if has_torch_function_unary(self):
  670. return handle_torch_function(Tensor.__array_wrap__, (self,), self, array=array)
  671. if array.dtype == bool:
  672. # Workaround, torch has no built-in bool tensor
  673. array = array.astype('uint8')
  674. return torch.from_numpy(array)
  675. def __contains__(self, element):
  676. r"""Check if `element` is present in tensor
  677. Args:
  678. element (Tensor or scalar): element to be checked
  679. for presence in current tensor"
  680. """
  681. if has_torch_function_unary(self):
  682. return handle_torch_function(Tensor.__contains__, (self,), self, element)
  683. if isinstance(element, (torch.Tensor, Number)):
  684. # type hint doesn't understand the __contains__ result array
  685. return (element == self).any().item() # type: ignore[union-attr]
  686. raise RuntimeError(
  687. "Tensor.__contains__ only supports Tensor or scalar, but you passed in a %s." %
  688. type(element)
  689. )
  690. @property
  691. def __cuda_array_interface__(self):
  692. """Array view description for cuda tensors.
  693. See:
  694. https://numba.pydata.org/numba-doc/latest/cuda/cuda_array_interface.html
  695. """
  696. if has_torch_function_unary(self):
  697. # TODO mypy doesn't support @property, see: https://github.com/python/mypy/issues/6185
  698. return handle_torch_function(Tensor.__cuda_array_interface__.__get__, (self,), self) # type: ignore[attr-defined]
  699. # raise AttributeError for unsupported tensors, so that
  700. # hasattr(cpu_tensor, "__cuda_array_interface__") is False.
  701. if not self.is_cuda:
  702. raise AttributeError(
  703. "Can't get __cuda_array_interface__ on non-CUDA tensor type: %s "
  704. "If CUDA data is required use tensor.cuda() to copy tensor to device memory." %
  705. self.type()
  706. )
  707. if self.is_sparse:
  708. raise AttributeError(
  709. "Can't get __cuda_array_interface__ on sparse type: %s "
  710. "Use Tensor.to_dense() to convert to a dense tensor first." %
  711. self.type()
  712. )
  713. # RuntimeError, matching tensor.__array__() behavior.
  714. if self.requires_grad:
  715. raise RuntimeError(
  716. "Can't get __cuda_array_interface__ on Variable that requires grad. "
  717. "If gradients aren't required, use var.detach() to get Variable that doesn't require grad."
  718. )
  719. # CUDA devices are little-endian and tensors are stored in native byte
  720. # order. 1-byte entries are endian-agnostic.
  721. typestr = {
  722. torch.complex64: "<c8",
  723. torch.complex128: "<c16",
  724. torch.float16: "<f2",
  725. torch.float32: "<f4",
  726. torch.float64: "<f8",
  727. torch.uint8: "|u1",
  728. torch.int8: "|i1",
  729. torch.int16: "<i2",
  730. torch.int32: "<i4",
  731. torch.int64: "<i8",
  732. }[self.dtype]
  733. itemsize = self.storage().element_size()
  734. shape = tuple(self.shape)
  735. if self.is_contiguous():
  736. # __cuda_array_interface__ v2 requires the strides to be omitted
  737. # (either not set or set to None) for C-contiguous arrays.
  738. strides = None
  739. else:
  740. strides = tuple(s * itemsize for s in self.stride())
  741. data_ptr = self.data_ptr() if self.numel() > 0 else 0
  742. data = (data_ptr, False) # read-only is false
  743. return dict(typestr=typestr, shape=shape, strides=strides, data=data, version=2)
  744. def storage_type(self):
  745. r"""storage_type() -> type
  746. Returns the type of the underlying storage.
  747. """
  748. if has_torch_function_unary(self):
  749. return handle_torch_function(Tensor.storage_type, (self,), self)
  750. return self.storage()._get_legacy_storage_class()
  751. def refine_names(self, *names):
  752. r"""Refines the dimension names of :attr:`self` according to :attr:`names`.
  753. Refining is a special case of renaming that "lifts" unnamed dimensions.
  754. A ``None`` dim can be refined to have any name; a named dim can only be
  755. refined to have the same name.
  756. Because named tensors can coexist with unnamed tensors, refining names
  757. gives a nice way to write named-tensor-aware code that works with both
  758. named and unnamed tensors.
  759. :attr:`names` may contain up to one Ellipsis (``...``).
  760. The Ellipsis is expanded greedily; it is expanded in-place to fill
  761. :attr:`names` to the same length as ``self.dim()`` using names from the
  762. corresponding indices of ``self.names``.
  763. Python 2 does not support Ellipsis but one may use a string literal
  764. instead (``'...'``).
  765. Args:
  766. names (iterable of str): The desired names of the output tensor. May
  767. contain up to one Ellipsis.
  768. Examples::
  769. >>> imgs = torch.randn(32, 3, 128, 128)
  770. >>> named_imgs = imgs.refine_names('N', 'C', 'H', 'W')
  771. >>> named_imgs.names
  772. ('N', 'C', 'H', 'W')
  773. >>> tensor = torch.randn(2, 3, 5, 7, 11)
  774. >>> tensor = tensor.refine_names('A', ..., 'B', 'C')
  775. >>> tensor.names
  776. ('A', None, None, 'B', 'C')
  777. .. warning::
  778. The named tensor API is experimental and subject to change.
  779. """
  780. if has_torch_function_unary(self):
  781. return handle_torch_function(Tensor.refine_names, (self,), self, *names)
  782. names = resolve_ellipsis(names, self.names, 'refine_names')
  783. return super(Tensor, self).refine_names(names)
  784. def align_to(self, *names):
  785. r"""Permutes the dimensions of the :attr:`self` tensor to match the order
  786. specified in :attr:`names`, adding size-one dims for any new names.
  787. All of the dims of :attr:`self` must be named in order to use this method.
  788. The resulting tensor is a view on the original tensor.
  789. All dimension names of :attr:`self` must be present in :attr:`names`.
  790. :attr:`names` may contain additional names that are not in ``self.names``;
  791. the output tensor has a size-one dimension for each of those new names.
  792. :attr:`names` may contain up to one Ellipsis (``...``).
  793. The Ellipsis is expanded to be equal to all dimension names of :attr:`self`
  794. that are not mentioned in :attr:`names`, in the order that they appear
  795. in :attr:`self`.
  796. Python 2 does not support Ellipsis but one may use a string literal
  797. instead (``'...'``).
  798. Args:
  799. names (iterable of str): The desired dimension ordering of the
  800. output tensor. May contain up to one Ellipsis that is expanded
  801. to all unmentioned dim names of :attr:`self`.
  802. Examples::
  803. >>> tensor = torch.randn(2, 2, 2, 2, 2, 2)
  804. >>> named_tensor = tensor.refine_names('A', 'B', 'C', 'D', 'E', 'F')
  805. # Move the F and E dims to the front while keeping the rest in order
  806. >>> named_tensor.align_to('F', 'E', ...)
  807. .. warning::
  808. The named tensor API is experimental and subject to change.
  809. """
  810. if has_torch_function_unary(self):
  811. return handle_torch_function(Tensor.align_to, (self,), self, *names)
  812. ellipsis_idx = single_ellipsis_index(names, 'align_to')
  813. if ellipsis_idx is None:
  814. return super(Tensor, self).align_to(names)
  815. return super(Tensor, self).align_to(
  816. [name for name in names if not is_ellipsis(name)],
  817. ellipsis_idx)
  818. def unflatten(self, dim, sizes):
  819. r"""Expands the dimension :attr:`dim` of the :attr:`self` tensor over multiple dimensions
  820. of sizes given by :attr:`sizes`.
  821. * :attr:`sizes` is the new shape of the unflattened dimension and it can be a `Tuple[int]` as well
  822. as `torch.Size` if :attr:`self` is a `Tensor`, or `namedshape` (Tuple[(name: str, size: int)])
  823. if :attr:`self` is a `NamedTensor`. The total number of elements in sizes must match the number
  824. of elements in the original dim being unflattened.
  825. Args:
  826. dim (Union[int, str]): Dimension to unflatten
  827. sizes (Union[Tuple[int] or torch.Size, Tuple[Tuple[str, int]]]): New shape of the unflattened dimension
  828. Examples:
  829. >>> torch.randn(3, 4, 1).unflatten(1, (2, 2)).shape
  830. torch.Size([3, 2, 2, 1])
  831. >>> torch.randn(3, 4, 1).unflatten(1, (-1, 2)).shape # the size -1 is inferred from the size of dimension 1
  832. torch.Size([3, 2, 2, 1])
  833. >>> torch.randn(2, 4, names=('A', 'B')).unflatten('B', (('B1', 2), ('B2', 2)))
  834. tensor([[[-1.1772, 0.0180],
  835. [ 0.2412, 0.1431]],
  836. [[-1.1819, -0.8899],
  837. [ 1.5813, 0.2274]]], names=('A', 'B1', 'B2'))
  838. >>> torch.randn(2, names=('A',)).unflatten('A', (('B1', -1), ('B2', 1)))
  839. tensor([[-0.8591],
  840. [ 0.3100]], names=('B1', 'B2'))
  841. .. warning::
  842. The named tensor API is experimental and subject to change.
  843. """
  844. if has_torch_function_unary(self):
  845. return handle_torch_function(Tensor.unflatten, (self,), self, dim, sizes)
  846. if not sizes:
  847. raise RuntimeError("unflatten: sizes must be non-empty")
  848. names = None
  849. if isinstance(sizes, OrderedDict) or (isinstance(sizes, (tuple, list)) and isinstance(sizes[0], (tuple, list))):
  850. names, sizes = unzip_namedshape(sizes)
  851. return super(Tensor, self).unflatten(dim, sizes, names)
  852. def rename_(self, *names, **rename_map):
  853. """In-place version of :meth:`~Tensor.rename`."""
  854. if has_torch_function_unary(self):
  855. return handle_torch_function(Tensor.rename_, (self,), self, *names, **rename_map)
  856. # Note [rename_ / rename API]
  857. # The Python API for these is different from the C++ API. In Python:
  858. # 1) tensor.rename(*names) takes a vararglist of names
  859. # 2) tensor.rename(**rename_map) takes a map of names to rename.
  860. # C++ is static, making it difficult to implement similar behavior.
  861. return update_names(self, names, rename_map, inplace=True)
  862. def rename(self, *names, **rename_map):
  863. """Renames dimension names of :attr:`self`.
  864. There are two main usages:
  865. ``self.rename(**rename_map)`` returns a view on tensor that has dims
  866. renamed as specified in the mapping :attr:`rename_map`.
  867. ``self.rename(*names)`` returns a view on tensor, renaming all
  868. dimensions positionally using :attr:`names`.
  869. Use ``self.rename(None)`` to drop names on a tensor.
  870. One cannot specify both positional args :attr:`names` and keyword args
  871. :attr:`rename_map`.
  872. Examples::
  873. >>> imgs = torch.rand(2, 3, 5, 7, names=('N', 'C', 'H', 'W'))
  874. >>> renamed_imgs = imgs.rename(N='batch', C='channels')
  875. >>> renamed_imgs.names
  876. ('batch', 'channels', 'H', 'W')
  877. >>> renamed_imgs = imgs.rename(None)
  878. >>> renamed_imgs.names
  879. (None,)
  880. >>> renamed_imgs = imgs.rename('batch', 'channel', 'height', 'width')
  881. >>> renamed_imgs.names
  882. ('batch', 'channel', 'height', 'width')
  883. .. warning::
  884. The named tensor API is experimental and subject to change.
  885. """
  886. if has_torch_function_unary(self):
  887. return handle_torch_function(Tensor.rename, (self,), self, *names, **rename_map)
  888. # See Note [rename_ / rename API]
  889. return update_names(self, names, rename_map, inplace=False)
  890. def to_sparse_coo(self):
  891. """ Convert a tensor to :ref:`coordinate format <sparse-coo-docs>`.
  892. Examples::
  893. >>> dense = torch.randn(5, 5)
  894. >>> sparse = dense.to_sparse_coo()
  895. >>> sparse._nnz()
  896. 25
  897. """
  898. return self.to_sparse()
  899. def _update_names(self, names, inplace):
  900. if has_torch_function_unary(self):
  901. return handle_torch_function(Tensor._update_names, (self,), self, names, inplace)
  902. # See Note [rename_ / rename API]
  903. if inplace:
  904. return super(Tensor, self).rename_(names)
  905. else:
  906. return super(Tensor, self).rename(names)
  907. @property
  908. def grad(self):
  909. """
  910. This attribute is ``None`` by default and becomes a Tensor the first time a call to
  911. :func:`backward` computes gradients for ``self``.
  912. The attribute will then contain the gradients computed and future calls to
  913. :func:`backward` will accumulate (add) gradients into it.
  914. """
  915. if has_torch_function_unary(self):
  916. # TODO mypy doesn't support @property, see: https://github.com/python/mypy/issues/6185
  917. return handle_torch_function(Tensor.grad.__get__, (self,), self) # type: ignore[attr-defined]
  918. return self._grad
  919. @grad.setter
  920. def grad(self, new_grad):
  921. if has_torch_function_unary(self):
  922. # TODO mypy doesn't support @property, see: https://github.com/python/mypy/issues/6185
  923. return handle_torch_function(Tensor.grad.__set__, (self,), self, new_grad) # type: ignore[attr-defined]
  924. self._grad = new_grad
  925. @grad.deleter
  926. def grad(self):
  927. if has_torch_function_unary(self):
  928. # TODO mypy doesn't support @property, see: https://github.com/python/mypy/issues/6185
  929. return handle_torch_function(Tensor.grad.__delete__, (self,), self) # type: ignore[attr-defined]
  930. del self._grad
  931. @classmethod
  932. def __torch_function__(cls, func, types, args=(), kwargs=None):
  933. """
  934. This __torch_function__ implementation wraps subclasses such that
  935. methods called on subclasses return a subclass instance instead of
  936. a ``torch.Tensor`` instance.
  937. One corollary to this is that you need coverage for torch.Tensor
  938. methods if implementing __torch_function__ for subclasses.
  939. We recommend always calling ``super().__torch_function__`` as the base
  940. case when doing the above.
  941. While not mandatory, we recommend making `__torch_function__` a classmethod.
  942. """
  943. if kwargs is None:
  944. kwargs = {}
  945. if not all(issubclass(cls, t) for t in types):
  946. return NotImplemented
  947. with _C.DisableTorchFunction():
  948. ret = func(*args, **kwargs)
  949. if func in get_default_nowrap_functions():
  950. return ret
  951. else:
  952. return _convert(ret, cls)
  953. __torch_dispatch__ = _C._disabled_torch_dispatch_impl
  954. def __dlpack__(self, stream=None):
  955. """
  956. Creates a DLpack `capsule https://data-apis.org/array-api/latest/design_topics/data_interchange.html#data-interchange`_
  957. of the current tensor to be exported to other libraries.
  958. This function will be called from the `from_dlpack` method
  959. of the library that will consume the capsule. `from_dlpack` passes the current
  960. stream to this method as part of the specification.
  961. Args:
  962. stream (integer or None): An optional Python integer representing a
  963. pointer to a CUDA stream. The current stream is synchronized with
  964. this stream before the capsule is created, and since the capsule
  965. shares its storage with the tensor this make it safe to access from
  966. both streams. If None or -1 is passed then no synchronization is performed.
  967. """
  968. if has_torch_function_unary(self):
  969. return handle_torch_function(Tensor.__dlpack__, (self,), self, stream)
  970. # DLPack capsules can't capture all of PyTorch's semantics,
  971. # so we prohibit exporting tensors that would lose their properties like
  972. # requires_grad and having the conjugate bit set.
  973. if self.requires_grad:
  974. raise RuntimeError('Can\'t export tensors that require gradient, use tensor.detach()')
  975. if self.is_conj():
  976. raise RuntimeError('Can\'t export tensors with the conjugate bit set')
  977. if self.layout != torch.strided:
  978. raise RuntimeError('Can\'t export tensors with layout other than torch.strided')
  979. if stream is not None and type(stream) is not int:
  980. # Stream pointers in CUDA/ROCm are uniquely numbered and can
  981. # be retrieved from their integer value.
  982. raise TypeError('stream must be ``int`` or ``none``')
  983. elif stream is not None and stream != -1:
  984. if self.device.type == 'cuda':
  985. stream = torch.cuda.ExternalStream(stream)
  986. # Only synchronize on different streams
  987. if stream != torch.cuda.current_stream:
  988. event = torch.cuda.Event()
  989. event.record(torch.cuda.current_stream())
  990. stream.wait_event(event)
  991. return torch.to_dlpack(self)
  992. def __dlpack_device__(self) -> Tuple[enum.IntEnum, int]:
  993. # Avoid circular import
  994. from torch.utils.dlpack import DLDeviceType
  995. if has_torch_function_unary(self):
  996. return handle_torch_function(Tensor.__dlpack_device__, (self,), self)
  997. idx = self.device.index if self.device.index is not None else 0
  998. if self.device.type == 'cuda' and torch.version.hip is not None:
  999. device_type = DLDeviceType.kDLROCM
  1000. elif self.device.type == 'cpu' and self.is_pinned():
  1001. device_type = DLDeviceType.kDLCPUPinned
  1002. elif self.device.type == 'cuda':
  1003. device_type = DLDeviceType.kDLGPU
  1004. elif self.device.type == 'cpu':
  1005. device_type = DLDeviceType.kDLCPU
  1006. else:
  1007. raise ValueError('Unknown device type {} for Dlpack'.format(self.device.type))
  1008. return (device_type, idx)
  1009. __module__ = 'torch'
  1010. def _convert(ret, cls):
  1011. if cls is Tensor:
  1012. return ret
  1013. if isinstance(ret, Tensor) and not isinstance(ret, cls):
  1014. ret = ret.as_subclass(cls)
  1015. if isinstance(ret, (tuple, list)):
  1016. # Also handles things like namedtuples
  1017. ret = type(ret)(_convert(r, cls) for r in ret)
  1018. return ret