_tensor.py 53 KB

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