2021-08-12 17:56:55 +00:00
|
|
|
from collections import OrderedDict
|
2021-09-13 02:45:57 +00:00
|
|
|
import enum
|
2021-08-12 18:39:31 +00:00
|
|
|
import functools
|
2021-01-11 03:16:04 +00:00
|
|
|
from numbers import Number
|
|
|
|
|
from typing import Any, Dict, Optional, Tuple, Union
|
2021-08-12 18:39:31 +00:00
|
|
|
import warnings
|
|
|
|
|
import copyreg
|
2021-09-27 21:32:41 +00:00
|
|
|
from copy import deepcopy
|
2021-01-11 03:16:04 +00:00
|
|
|
|
|
|
|
|
import torch
|
|
|
|
|
import torch._C as _C
|
|
|
|
|
from torch._namedtensor_internals import (
|
2021-08-12 18:39:31 +00:00
|
|
|
update_names, check_serializing_named_tensor, resolve_ellipsis,
|
|
|
|
|
unzip_namedshape, single_ellipsis_index, is_ellipsis)
|
2021-01-11 03:16:04 +00:00
|
|
|
from torch.overrides import (
|
2021-08-12 18:39:31 +00:00
|
|
|
has_torch_function, has_torch_function_unary, has_torch_function_variadic,
|
|
|
|
|
handle_torch_function, get_default_nowrap_functions)
|
|
|
|
|
import torch.utils.hooks as hooks
|
2019-10-28 21:21:34 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def _wrap_type_error_to_not_implemented(f):
|
|
|
|
|
# functools.wraps doesn't work well with methods in python 2
|
2021-08-12 18:39:31 +00:00
|
|
|
method_assignments = ('__name__', '__doc__')
|
2020-04-22 16:20:13 +00:00
|
|
|
assigned = functools.WRAPPER_ASSIGNMENTS
|
2019-10-28 21:21:34 +00:00
|
|
|
|
|
|
|
|
@functools.wraps(f, assigned=assigned)
|
|
|
|
|
def wrapped(*args, **kwargs):
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function(args):
|
2020-08-06 03:39:27 +00:00
|
|
|
return handle_torch_function(wrapped, args, *args, **kwargs)
|
2019-10-28 21:21:34 +00:00
|
|
|
try:
|
|
|
|
|
return f(*args, **kwargs)
|
|
|
|
|
except TypeError:
|
|
|
|
|
return NotImplemented
|
|
|
|
|
return wrapped
|
2018-04-03 20:29:25 +00:00
|
|
|
|
2021-08-05 13:47:02 +00:00
|
|
|
# Should not be used, this is kept only for BC of loading old serialized Tensor subclasses
|
2021-02-01 15:29:10 +00:00
|
|
|
def _rebuild_from_type(func, type, args, dict):
|
|
|
|
|
if type is Tensor:
|
|
|
|
|
return func(*args)
|
|
|
|
|
|
|
|
|
|
ret = func(*args).as_subclass(type)
|
|
|
|
|
ret.__dict__ = dict
|
|
|
|
|
return ret
|
|
|
|
|
|
2021-08-05 13:47:02 +00:00
|
|
|
def _rebuild_from_type_v2(func, new_type, args, state):
|
|
|
|
|
if new_type is Tensor:
|
|
|
|
|
return func(*args)
|
|
|
|
|
|
|
|
|
|
ret = func(*args).as_subclass(new_type)
|
|
|
|
|
# Tensor does define __setstate__ even though it doesn't define
|
|
|
|
|
# __getstate__. So only use __setstate__ if it is NOT the one defined
|
|
|
|
|
# on Tensor
|
2021-08-12 18:39:31 +00:00
|
|
|
if getattr(ret.__class__, "__setstate__", Tensor.__setstate__) is not Tensor.__setstate__:
|
2021-08-05 13:47:02 +00:00
|
|
|
ret.__setstate__(state)
|
|
|
|
|
else:
|
|
|
|
|
if isinstance(state, tuple):
|
|
|
|
|
if not len(state) == 2:
|
|
|
|
|
raise RuntimeError(f"Invalid serialized state: {state}")
|
|
|
|
|
dict_state = state[0]
|
|
|
|
|
slots_state = state[1]
|
|
|
|
|
else:
|
|
|
|
|
dict_state = state
|
|
|
|
|
slots_state = None
|
|
|
|
|
|
|
|
|
|
for k, v in dict_state.items():
|
|
|
|
|
setattr(ret, k, v)
|
|
|
|
|
|
|
|
|
|
if slots_state:
|
|
|
|
|
for k, v in slots_state.items():
|
|
|
|
|
setattr(ret, k, v)
|
|
|
|
|
return ret
|
|
|
|
|
|
2018-04-03 20:29:25 +00:00
|
|
|
|
Correctly share CUDA Parameters. (#10220)
Summary:
```
Correctly share CUDA Parameters, requires_grad and hooks.
Previously, the following was true:
- If you put a Parameter for a CUDA tensor
in multiprocessing queue (or otherwise tried to transfer it),
this failed, saying that we cannot pickle CUDA storage.
This is issue #9996.
- If you put a leaf Tensor that requires_grad=True through the
multiprocessing queue, it would come out the other end as
requires_grad=False (It should have come out the other end
as requires_grad=True). Similarly, backwards hooks were
lost.
- If you put a non-leaf Tensor that requires_grad=True through
the multiprocessing queue, it would come out the other end
as requires_grad=False.
The root cause for the first issue was that implementation of
reductions for Parameter used the superclass implementation
(tensor) in __reduce_ex__, but this always picks up the
non-ForkingPickler reduction, which doesn't work with CUDA tensors.
So, we registered a new ForkingPickler specifically for Parameter,
and adjusted the code to correctly rewrap a Tensor in a Parameter
if it was originally a parameter.
While working on this, we realized that requires_grad and backwards
hooks would not be preserved in the ForkingPickler reduction
implementation. We fixed the reducer to save these parameters.
However, Adam Paszke pointed out that we shouldn't allow sending
requires_grad=True, non-leaf Tensors over a multiprocessing
queue, since we don't actually support autograd over process
boundar. We now throw an error in this case; this may cause
previously working code to fail, but this is easy enough to fix;
just detach() the tensor before sending it. The error message says
so.
Fixes #9996.
```
Pull Request resolved: https://github.com/pytorch/pytorch/pull/10220
Differential Revision: D9160746
Pulled By: ezyang
fbshipit-source-id: a39c0dbc012ba5afc7a9e646da5c7f325b3cf05c
2018-08-10 20:46:54 +00:00
|
|
|
# NB: If you subclass Tensor, and want to share the subclassed class
|
|
|
|
|
# across processes, you must also update torch/multiprocessing/reductions.py
|
|
|
|
|
# to define a ForkingPickler serialization mode for the class.
|
2019-01-29 19:19:51 +00:00
|
|
|
#
|
|
|
|
|
# NB: If you add a new method to Tensor, you must update
|
|
|
|
|
# torch/__init__.py.in to add a type annotation for your method;
|
|
|
|
|
# otherwise, it will not show up in autocomplete.
|
2018-04-03 20:29:25 +00:00
|
|
|
class Tensor(torch._C._TensorBase):
|
|
|
|
|
def __deepcopy__(self, memo):
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
|
|
|
|
return handle_torch_function(Tensor.__deepcopy__, (self,), self, memo)
|
2018-04-03 20:29:25 +00:00
|
|
|
if not self.is_leaf:
|
2021-08-12 18:39:31 +00:00
|
|
|
raise RuntimeError("Only Tensors created explicitly by the user "
|
|
|
|
|
"(graph leaves) support the deepcopy protocol at the moment")
|
2018-04-03 20:29:25 +00:00
|
|
|
if id(self) in memo:
|
|
|
|
|
return memo[id(self)]
|
|
|
|
|
with torch.no_grad():
|
Restore storage on meta tensors; increase meta coverage (#53973)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/53973
Two parts to this PR; I had to put them together because adding support for X causes more test code to be exercised, which in turn may require a fix for Y.
The first part is restoring the concept of storage to meta tensors. Previously, meta tensors had a nullptr storage (e.g., `meta_tensor.storage()` is an error.) As I was increasing the coverage of meta tensors, I started running into test cases (specifically memory overlap tests) that were failing because not having storage meant I couldn't check for memory overlap. After some discussion, we decided that it would make sense for meta tensors to model this as well (we already model strides, so getting accurate view information also seems useful). This PR does that by:
* Rewrite all of the factory functions in MetaTensor.cpp to use the generic versions (which are very carefully written to not actually poke at the data pointer, so everything works out). The key idea here is we give meta tensors a special allocator, MetaAllocator, which always returns a nullptr even if you ask for a nonzero number of bytes. resize_ is also made generic; the normal variant can be used directly rather than having to instruct it to avoid resizing storage
* Turn on memory overlap checking in TensorIterator even for meta tensors
* Although meta tensors now have storage, the concept of meta storage is NOT exposed to Python land (as it would imply I would have to codegen MetaFloatStorage, MetaDoubleStorage, etc. classes). So `x.storage()` still raises an error and I have a cludge in `__deepcopy__` to break storage sharing upon deep copy (this is wrong, but no tests exercise this at the moment).
The second part is adding more support for the most used functions in the test suite.
* Inplace operations have very simple meta functions. I added `fill_`, `zero_`, `random_`, `uniform_` and `normal_`. In the case of random, I take advantage of pbelevich's templates for defining random kernels, so that I can reuse the common scaffolding, and then just register a noop stub that actually does the RNG. (Look, another structured kernels tiny variant!)
* `copy_` is now implemented. Copying into a meta tensor is always OK, but copying out of a meta tensor raises an error (as we don't know what the "correct" data to copy out is in this case)
* `empty_strided` usage from structured kernels now is implemented (TBH, this could have been done as soon as `empty_strided` was added)
* Meta was missing in a few places in TensorOptions/DispatchKey utility functions, so I added them
* Autograd engine now correctly homes meta tensors with CPU tensors (they have -1 device index so CUDA queues wouldn't work anyway)
* `apply_`, `map_` and `map2_` are special cased to no-op on meta tensor self. These count as inplace operations too but they are implemented a little differently.
Getting more meta function support triggers a number of bugs in the test suite, which I then fix:
- Linear algebra functions sometimes don't report NotImplementedError because they get swallowed by catch all try blocks. This is tracked in https://github.com/pytorch/pytorch/issues/53739
- dlpack obviously doesn't work with meta tensors, I just disabled the test
Signed-off-by: Edward Z. Yang <ezyang@fb.com>
Differential Revision: D27036572
Test Plan: Imported from OSS
Reviewed By: agolynski, bdhirsh
Pulled By: ezyang
fbshipit-source-id: 7005ecf4feb92a643c37389fdfbd852dbf00ac78
2021-03-29 15:34:19 +00:00
|
|
|
# TODO: skipping storage copy is wrong for meta, as meta
|
|
|
|
|
# does accurate alias tracking; however, the code below
|
|
|
|
|
# doesn't work because of
|
|
|
|
|
# https://github.com/pytorch/pytorch/issues/47442
|
2021-09-27 18:53:01 +00:00
|
|
|
if self.is_sparse or self.device.type in ['xla', 'mlc', 'ort', 'meta', 'hpu']:
|
2018-04-03 20:29:25 +00:00
|
|
|
new_tensor = self.clone()
|
|
|
|
|
else:
|
|
|
|
|
new_storage = self.storage().__deepcopy__(memo)
|
2019-11-02 00:37:11 +00:00
|
|
|
if self.is_quantized:
|
2020-09-24 15:20:06 +00:00
|
|
|
# quantizer_params can be different type based on torch attribute
|
2021-08-12 18:39:31 +00:00
|
|
|
quantizer_params: Union[Tuple[torch.qscheme, float, int], Tuple[torch.qscheme, Tensor, Tensor, int]]
|
2019-11-02 00:37:11 +00:00
|
|
|
if self.qscheme() == torch.per_tensor_affine:
|
2021-08-12 18:39:31 +00:00
|
|
|
quantizer_params = self.qscheme(), self.q_scale(), self.q_zero_point()
|
|
|
|
|
elif self.qscheme() in (torch.per_channel_affine, torch.per_channel_affine_float_qparams):
|
|
|
|
|
quantizer_params = self.qscheme(), \
|
|
|
|
|
self.q_per_channel_scales(), \
|
|
|
|
|
self.q_per_channel_zero_points(), \
|
|
|
|
|
self.q_per_channel_axis()
|
2019-11-02 00:37:11 +00:00
|
|
|
else:
|
2021-08-12 18:39:31 +00:00
|
|
|
raise RuntimeError(f"Unsupported qscheme {self.qscheme()} in deepcopy")
|
Remove dtype from torch.Storage and use only torch.ByteStorage (#62030)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/62030
Remove dtype tracking from Python Storage interface, remove all the different `<type>Storage` classes except for `ByteStorage`, and update serialization accordingly, while maintaining as much FC/BC as possible
Fixes https://github.com/pytorch/pytorch/issues/47442
* **THE SERIALIZATION FORMAT IS FULLY FC/BC.** We worked very hard to make sure this is the case. We will probably want to break FC at some point to make the serialization structure of tensors make more sense, but not today.
* There is now only a single torch.ByteStorage class. Methods like `Tensor.set_` no longer check that the dtype of storage is appropriate.
* As we no longer know what dtype of a storage is, we've **removed** the size method from Storage, replacing it with nbytes. This is to help catch otherwise silent errors where you confuse number of elements with number of bytes.
* `Storage._new_shared` takes a `nbytes` kwarg and will reject previous positional only calls. `Storage._new_with_file` and `_set_from_file` require explicit element size arguments.
* It's no longer possible to convert storages to different types using the float/double/etc methods. Instead, do the conversion using a tensor.
* It's no longer possible to allocate a typed storage directly using FloatStorage/DoubleStorage/etc constructors. Instead, construct a tensor and extract its storage. The classes still exist but they are used purely for unpickling.
* The preexisting serialization format stores dtype with storage, and in fact this dtype is used to determine the dtype of the tensor overall.
To accommodate this case, we introduce a new TypedStorage concept that exists only during unpickling time which is used to temporarily store the dtype so we can construct a tensor. **If you overrode the handling of pickling/unpickling, you MUST add handling for TypedStorage** or your serialization code will degrade to standard file-based serialization.
Original pull request: https://github.com/pytorch/pytorch/pull/59671
Reviewed By: soulitzer, ngimel
Differential Revision: D29466819
Pulled By: ezyang
fbshipit-source-id: 4a14e5d3c2b08e06e558683d97f7378a3180b00e
2021-10-05 20:48:45 +00:00
|
|
|
# TODO: Once we decide to break serialization FC, no longer
|
|
|
|
|
# need to wrap with TypedStorage
|
2019-11-02 00:37:11 +00:00
|
|
|
new_tensor = torch._utils._rebuild_qtensor(
|
Remove dtype from torch.Storage and use only torch.ByteStorage (#62030)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/62030
Remove dtype tracking from Python Storage interface, remove all the different `<type>Storage` classes except for `ByteStorage`, and update serialization accordingly, while maintaining as much FC/BC as possible
Fixes https://github.com/pytorch/pytorch/issues/47442
* **THE SERIALIZATION FORMAT IS FULLY FC/BC.** We worked very hard to make sure this is the case. We will probably want to break FC at some point to make the serialization structure of tensors make more sense, but not today.
* There is now only a single torch.ByteStorage class. Methods like `Tensor.set_` no longer check that the dtype of storage is appropriate.
* As we no longer know what dtype of a storage is, we've **removed** the size method from Storage, replacing it with nbytes. This is to help catch otherwise silent errors where you confuse number of elements with number of bytes.
* `Storage._new_shared` takes a `nbytes` kwarg and will reject previous positional only calls. `Storage._new_with_file` and `_set_from_file` require explicit element size arguments.
* It's no longer possible to convert storages to different types using the float/double/etc methods. Instead, do the conversion using a tensor.
* It's no longer possible to allocate a typed storage directly using FloatStorage/DoubleStorage/etc constructors. Instead, construct a tensor and extract its storage. The classes still exist but they are used purely for unpickling.
* The preexisting serialization format stores dtype with storage, and in fact this dtype is used to determine the dtype of the tensor overall.
To accommodate this case, we introduce a new TypedStorage concept that exists only during unpickling time which is used to temporarily store the dtype so we can construct a tensor. **If you overrode the handling of pickling/unpickling, you MUST add handling for TypedStorage** or your serialization code will degrade to standard file-based serialization.
Original pull request: https://github.com/pytorch/pytorch/pull/59671
Reviewed By: soulitzer, ngimel
Differential Revision: D29466819
Pulled By: ezyang
fbshipit-source-id: 4a14e5d3c2b08e06e558683d97f7378a3180b00e
2021-10-05 20:48:45 +00:00
|
|
|
torch.storage.TypedStorage(
|
|
|
|
|
wrap_storage=new_storage._untyped(),
|
|
|
|
|
dtype=self.dtype),
|
2019-11-02 00:37:11 +00:00
|
|
|
self.storage_offset(),
|
|
|
|
|
self.size(),
|
|
|
|
|
self.stride(),
|
|
|
|
|
quantizer_params,
|
|
|
|
|
self.requires_grad,
|
2021-08-12 18:39:31 +00:00
|
|
|
self._backward_hooks)
|
2019-11-02 00:37:11 +00:00
|
|
|
else:
|
Conjugate View (#54987)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/54987
Based off of ezyang (https://github.com/pytorch/pytorch/pull/44799) and bdhirsh (https://github.com/pytorch/pytorch/pull/43702) 's prototype:
Here's a summary of the changes in this PR:
This PR adds a new dispatch key called Conjugate. This enables us to make conjugate operation a view and leverage the specialized library functions that fast path with the hermitian operation (conj + transpose).
1. Conjugate operation will now return a view with conj bit (1) for complex tensors and returns self for non-complex tensors as before. This also means `torch.view_as_real` will no longer be a view on conjugated complex tensors and is hence disabled. To fill the gap, we have added `torch.view_as_real_physical` which would return the real tensor agnostic of the conjugate bit on the input complex tensor. The information about conjugation on the old tensor can be obtained by calling `.is_conj()` on the new tensor.
2. NEW API:
a) `.conj()` -- now returning a view.
b) `.conj_physical()` -- does the physical conjugate operation. If the conj bit for input was set, you'd get `self.clone()`, else you'll get a new tensor with conjugated value in its memory.
c) `.conj_physical_()`, and `out=` variant
d) `.resolve_conj()` -- materializes the conjugation. returns self if the conj bit is unset, else returns a new tensor with conjugated values and conj bit set to 0.
e) `.resolve_conj_()` in-place version of (d)
f) `view_as_real_physical` -- as described in (1), it's functionally same as `view_as_real`, just that it doesn't error out on conjugated tensors.
g) `view_as_real` -- existing function, but now errors out on conjugated tensors.
3. Conjugate Fallback
a) Vast majority of PyTorch functions would currently use this fallback when they are called on a conjugated tensor.
b) This fallback is well equipped to handle the following cases:
- functional operation e.g., `torch.sin(input)`
- Mutable inputs and in-place operations e.g., `tensor.add_(2)`
- out-of-place operation e.g., `torch.sin(input, out=out)`
- Tensorlist input args
- NOTE: Meta tensors don't work with conjugate fallback.
4. Autograd
a) `resolve_conj()` is an identity function w.r.t. autograd
b) Everything else works as expected.
5. Testing:
a) All method_tests run with conjugate view tensors.
b) OpInfo tests that run with conjugate views
- test_variant_consistency_eager/jit
- gradcheck, gradgradcheck
- test_conj_views (that only run for `torch.cfloat` dtype)
NOTE: functions like `empty_like`, `zero_like`, `randn_like`, `clone` don't propagate the conjugate bit.
Follow up work:
1. conjugate view RFC
2. Add neg bit to re-enable view operation on conjugated tensors
3. Update linalg functions to call into specialized functions that fast path with the hermitian operation.
Test Plan: Imported from OSS
Reviewed By: VitalyFedyunin
Differential Revision: D28227315
Pulled By: anjali411
fbshipit-source-id: acab9402b9d6a970c6d512809b627a290c8def5f
2021-06-04 21:11:23 +00:00
|
|
|
new_tensor = self.new_empty([])
|
2021-08-12 18:39:31 +00:00
|
|
|
new_tensor.set_(new_storage, self.storage_offset(), self.size(), self.stride())
|
Conjugate View (#54987)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/54987
Based off of ezyang (https://github.com/pytorch/pytorch/pull/44799) and bdhirsh (https://github.com/pytorch/pytorch/pull/43702) 's prototype:
Here's a summary of the changes in this PR:
This PR adds a new dispatch key called Conjugate. This enables us to make conjugate operation a view and leverage the specialized library functions that fast path with the hermitian operation (conj + transpose).
1. Conjugate operation will now return a view with conj bit (1) for complex tensors and returns self for non-complex tensors as before. This also means `torch.view_as_real` will no longer be a view on conjugated complex tensors and is hence disabled. To fill the gap, we have added `torch.view_as_real_physical` which would return the real tensor agnostic of the conjugate bit on the input complex tensor. The information about conjugation on the old tensor can be obtained by calling `.is_conj()` on the new tensor.
2. NEW API:
a) `.conj()` -- now returning a view.
b) `.conj_physical()` -- does the physical conjugate operation. If the conj bit for input was set, you'd get `self.clone()`, else you'll get a new tensor with conjugated value in its memory.
c) `.conj_physical_()`, and `out=` variant
d) `.resolve_conj()` -- materializes the conjugation. returns self if the conj bit is unset, else returns a new tensor with conjugated values and conj bit set to 0.
e) `.resolve_conj_()` in-place version of (d)
f) `view_as_real_physical` -- as described in (1), it's functionally same as `view_as_real`, just that it doesn't error out on conjugated tensors.
g) `view_as_real` -- existing function, but now errors out on conjugated tensors.
3. Conjugate Fallback
a) Vast majority of PyTorch functions would currently use this fallback when they are called on a conjugated tensor.
b) This fallback is well equipped to handle the following cases:
- functional operation e.g., `torch.sin(input)`
- Mutable inputs and in-place operations e.g., `tensor.add_(2)`
- out-of-place operation e.g., `torch.sin(input, out=out)`
- Tensorlist input args
- NOTE: Meta tensors don't work with conjugate fallback.
4. Autograd
a) `resolve_conj()` is an identity function w.r.t. autograd
b) Everything else works as expected.
5. Testing:
a) All method_tests run with conjugate view tensors.
b) OpInfo tests that run with conjugate views
- test_variant_consistency_eager/jit
- gradcheck, gradgradcheck
- test_conj_views (that only run for `torch.cfloat` dtype)
NOTE: functions like `empty_like`, `zero_like`, `randn_like`, `clone` don't propagate the conjugate bit.
Follow up work:
1. conjugate view RFC
2. Add neg bit to re-enable view operation on conjugated tensors
3. Update linalg functions to call into specialized functions that fast path with the hermitian operation.
Test Plan: Imported from OSS
Reviewed By: VitalyFedyunin
Differential Revision: D28227315
Pulled By: anjali411
fbshipit-source-id: acab9402b9d6a970c6d512809b627a290c8def5f
2021-06-04 21:11:23 +00:00
|
|
|
if self.is_conj():
|
|
|
|
|
new_tensor = new_tensor.conj_physical()
|
2021-07-13 20:49:22 +00:00
|
|
|
if self.is_neg():
|
|
|
|
|
new_tensor = new_tensor.neg()
|
2019-11-02 00:37:11 +00:00
|
|
|
new_tensor.requires_grad = self.requires_grad
|
2021-01-27 00:17:40 +00:00
|
|
|
if self.grad is not None:
|
|
|
|
|
new_tensor.grad = self.grad.__deepcopy__(memo)
|
2021-09-27 21:32:41 +00:00
|
|
|
|
|
|
|
|
if not type(self) is Tensor:
|
|
|
|
|
new_tensor = new_tensor.as_subclass(type(self)) # type: ignore[arg-type]
|
|
|
|
|
|
|
|
|
|
# Plain Tensors don't have slots
|
|
|
|
|
slots_to_save = copyreg._slotnames(self.__class__) # type: ignore[attr-defined]
|
|
|
|
|
for slot in slots_to_save:
|
|
|
|
|
if hasattr(self, slot):
|
|
|
|
|
setattr(new_tensor, slot, deepcopy(getattr(self, slot), memo))
|
|
|
|
|
|
|
|
|
|
new_tensor.__dict__ = deepcopy(self.__dict__, memo)
|
|
|
|
|
|
2018-04-03 20:29:25 +00:00
|
|
|
memo[id(self)] = new_tensor
|
|
|
|
|
return new_tensor
|
|
|
|
|
|
|
|
|
|
def __reduce_ex__(self, proto):
|
2021-02-01 15:29:10 +00:00
|
|
|
if type(self) is Tensor:
|
|
|
|
|
return self._reduce_ex_internal(proto)
|
2021-08-05 13:47:02 +00:00
|
|
|
if has_torch_function_unary(self):
|
|
|
|
|
return handle_torch_function(Tensor.__reduce_ex__, (self,), self, proto)
|
2021-02-01 15:29:10 +00:00
|
|
|
func, args = self._reduce_ex_internal(proto)
|
2021-08-05 13:47:02 +00:00
|
|
|
# Get the state of the python subclass
|
|
|
|
|
# This loosely mimicks the function on the object class but since Tensor do not inherit
|
|
|
|
|
# from it, we cannot call that function directly
|
|
|
|
|
# https://github.com/python/cpython/blob/c83919bd635f4433f1c6ae8504996a9fe3c215e5/Objects/typeobject.c#L4891
|
|
|
|
|
getstate_fn = getattr(self, "__getstate__", None)
|
|
|
|
|
if getstate_fn:
|
|
|
|
|
state = getstate_fn()
|
|
|
|
|
else:
|
|
|
|
|
slots_to_save = copyreg._slotnames(self.__class__) # type: ignore[attr-defined]
|
|
|
|
|
if slots_to_save:
|
2021-08-12 18:39:31 +00:00
|
|
|
state = (self.__dict__, {name: getattr(self, name) for name in slots_to_save if hasattr(self, name)})
|
2021-08-05 13:47:02 +00:00
|
|
|
else:
|
|
|
|
|
state = self.__dict__
|
|
|
|
|
return (_rebuild_from_type_v2, (func, type(self), args, state))
|
2021-02-01 15:29:10 +00:00
|
|
|
|
Remove dtype from torch.Storage and use only torch.ByteStorage (#62030)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/62030
Remove dtype tracking from Python Storage interface, remove all the different `<type>Storage` classes except for `ByteStorage`, and update serialization accordingly, while maintaining as much FC/BC as possible
Fixes https://github.com/pytorch/pytorch/issues/47442
* **THE SERIALIZATION FORMAT IS FULLY FC/BC.** We worked very hard to make sure this is the case. We will probably want to break FC at some point to make the serialization structure of tensors make more sense, but not today.
* There is now only a single torch.ByteStorage class. Methods like `Tensor.set_` no longer check that the dtype of storage is appropriate.
* As we no longer know what dtype of a storage is, we've **removed** the size method from Storage, replacing it with nbytes. This is to help catch otherwise silent errors where you confuse number of elements with number of bytes.
* `Storage._new_shared` takes a `nbytes` kwarg and will reject previous positional only calls. `Storage._new_with_file` and `_set_from_file` require explicit element size arguments.
* It's no longer possible to convert storages to different types using the float/double/etc methods. Instead, do the conversion using a tensor.
* It's no longer possible to allocate a typed storage directly using FloatStorage/DoubleStorage/etc constructors. Instead, construct a tensor and extract its storage. The classes still exist but they are used purely for unpickling.
* The preexisting serialization format stores dtype with storage, and in fact this dtype is used to determine the dtype of the tensor overall.
To accommodate this case, we introduce a new TypedStorage concept that exists only during unpickling time which is used to temporarily store the dtype so we can construct a tensor. **If you overrode the handling of pickling/unpickling, you MUST add handling for TypedStorage** or your serialization code will degrade to standard file-based serialization.
Original pull request: https://github.com/pytorch/pytorch/pull/59671
Reviewed By: soulitzer, ngimel
Differential Revision: D29466819
Pulled By: ezyang
fbshipit-source-id: 4a14e5d3c2b08e06e558683d97f7378a3180b00e
2021-10-05 20:48:45 +00:00
|
|
|
def storage(self):
|
|
|
|
|
r"""
|
|
|
|
|
storage() -> torch.Storage
|
|
|
|
|
|
|
|
|
|
Returns the underlying storage.
|
|
|
|
|
"""
|
|
|
|
|
if has_torch_function_unary(self):
|
|
|
|
|
return handle_torch_function(Tensor.storage, (self,), self)
|
|
|
|
|
|
|
|
|
|
if self.dtype not in torch.storage._dtype_to_storage_type_map():
|
|
|
|
|
raise RuntimeError(f'unsupported Storage type: {self.dtype}')
|
|
|
|
|
|
|
|
|
|
storage = self._storage()
|
|
|
|
|
storage_name = torch.storage._dtype_to_storage_type_map()[self.dtype]
|
|
|
|
|
storage_class = eval(type(storage).__module__ + '.' + storage_name)
|
|
|
|
|
storage = storage_class(wrap_storage=storage)
|
|
|
|
|
return storage
|
|
|
|
|
|
2021-02-01 15:29:10 +00:00
|
|
|
def _reduce_ex_internal(self, proto):
|
2019-09-18 12:44:43 +00:00
|
|
|
check_serializing_named_tensor(self)
|
2018-10-17 03:08:45 +00:00
|
|
|
# See Note [Don't serialize hooks]
|
|
|
|
|
torch.utils.hooks.warn_if_has_hooks(self)
|
2020-09-24 15:20:06 +00:00
|
|
|
backward_hooks: Dict[Any, Any] = OrderedDict()
|
2021-08-20 18:11:47 +00:00
|
|
|
# Note: Numpy array is chosen to be the rebuild component for XLA, ORT, MLC Tensors.
|
2019-10-01 22:00:41 +00:00
|
|
|
# We considered a few options:
|
|
|
|
|
# 1. CPU tensor can't be used here.
|
|
|
|
|
# Otherwise in torch.load CPU storage is reconstructed with randomly
|
2021-08-20 18:11:47 +00:00
|
|
|
# initialized data, moved onto backend device, and then storage is updated
|
|
|
|
|
# to the serialized content. This works perfectly for CPU/CUDA but not these backends;
|
|
|
|
|
# their tensors are disconnected with storage so they don't get the update.
|
2019-10-01 22:00:41 +00:00
|
|
|
# 2. Python list is not a good fit due to performance reason.
|
|
|
|
|
# `tolist()` converts every single element in the tensor into python objects
|
|
|
|
|
# and serialize them one by one.
|
2021-08-20 18:11:47 +00:00
|
|
|
if self.device.type in ['xla', 'ort', 'mlc']:
|
|
|
|
|
return (torch._utils._rebuild_device_tensor_from_numpy, (self.cpu().numpy(),
|
|
|
|
|
self.dtype,
|
|
|
|
|
str(self.device),
|
|
|
|
|
self.requires_grad))
|
2021-08-12 18:39:31 +00:00
|
|
|
if self.device.type == 'meta':
|
2021-07-26 21:31:18 +00:00
|
|
|
# NB: This implementation BREAKS storage sharing. Current
|
|
|
|
|
# hypothesis is that no one cares for meta tensors.
|
|
|
|
|
arg_meta = (
|
|
|
|
|
self.dtype,
|
|
|
|
|
tuple(self.size()),
|
|
|
|
|
self.stride(),
|
|
|
|
|
self.requires_grad,
|
|
|
|
|
)
|
|
|
|
|
return (torch._utils._rebuild_meta_tensor_no_storage, arg_meta)
|
2019-05-31 03:43:36 +00:00
|
|
|
if self.is_quantized:
|
2020-09-24 15:20:06 +00:00
|
|
|
# quantizer_params can be different type based on torch attribute
|
2021-08-12 18:39:31 +00:00
|
|
|
quantizer_params: Union[Tuple[torch.qscheme, float, int], Tuple[Any, Tensor, Tensor, int]]
|
2019-09-23 20:24:24 +00:00
|
|
|
if self.qscheme() == torch.per_tensor_affine:
|
2021-08-12 18:39:31 +00:00
|
|
|
quantizer_params = (torch.per_tensor_affine,
|
|
|
|
|
self.q_scale(),
|
|
|
|
|
self.q_zero_point())
|
|
|
|
|
elif self.qscheme() in (torch.per_channel_affine, torch.per_channel_affine_float_qparams):
|
2019-09-23 20:24:24 +00:00
|
|
|
# convert scales and zero points to tuple to avoid recursive calls
|
|
|
|
|
# when/if we get multi-axis quantized tensors in the future, the shape
|
|
|
|
|
# is recoverable from the main tensor shape
|
2021-08-12 18:39:31 +00:00
|
|
|
quantizer_params = (torch.per_channel_affine,
|
|
|
|
|
self.q_per_channel_scales(),
|
|
|
|
|
self.q_per_channel_zero_points(),
|
|
|
|
|
self.q_per_channel_axis())
|
2019-09-23 20:24:24 +00:00
|
|
|
else:
|
2021-08-12 18:39:31 +00:00
|
|
|
raise RuntimeError(f"Serialization is not supported for tensors of type {self.qscheme()}")
|
Remove dtype from torch.Storage and use only torch.ByteStorage (#62030)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/62030
Remove dtype tracking from Python Storage interface, remove all the different `<type>Storage` classes except for `ByteStorage`, and update serialization accordingly, while maintaining as much FC/BC as possible
Fixes https://github.com/pytorch/pytorch/issues/47442
* **THE SERIALIZATION FORMAT IS FULLY FC/BC.** We worked very hard to make sure this is the case. We will probably want to break FC at some point to make the serialization structure of tensors make more sense, but not today.
* There is now only a single torch.ByteStorage class. Methods like `Tensor.set_` no longer check that the dtype of storage is appropriate.
* As we no longer know what dtype of a storage is, we've **removed** the size method from Storage, replacing it with nbytes. This is to help catch otherwise silent errors where you confuse number of elements with number of bytes.
* `Storage._new_shared` takes a `nbytes` kwarg and will reject previous positional only calls. `Storage._new_with_file` and `_set_from_file` require explicit element size arguments.
* It's no longer possible to convert storages to different types using the float/double/etc methods. Instead, do the conversion using a tensor.
* It's no longer possible to allocate a typed storage directly using FloatStorage/DoubleStorage/etc constructors. Instead, construct a tensor and extract its storage. The classes still exist but they are used purely for unpickling.
* The preexisting serialization format stores dtype with storage, and in fact this dtype is used to determine the dtype of the tensor overall.
To accommodate this case, we introduce a new TypedStorage concept that exists only during unpickling time which is used to temporarily store the dtype so we can construct a tensor. **If you overrode the handling of pickling/unpickling, you MUST add handling for TypedStorage** or your serialization code will degrade to standard file-based serialization.
Original pull request: https://github.com/pytorch/pytorch/pull/59671
Reviewed By: soulitzer, ngimel
Differential Revision: D29466819
Pulled By: ezyang
fbshipit-source-id: 4a14e5d3c2b08e06e558683d97f7378a3180b00e
2021-10-05 20:48:45 +00:00
|
|
|
# TODO: Once we decide to break serialization FC, no longer
|
|
|
|
|
# need to wrap with TypedStorage
|
|
|
|
|
args_qtensor = (
|
|
|
|
|
torch.storage.TypedStorage(
|
|
|
|
|
wrap_storage=self.storage()._untyped(),
|
|
|
|
|
dtype=self.dtype),
|
|
|
|
|
self.storage_offset(),
|
|
|
|
|
tuple(self.size()),
|
|
|
|
|
self.stride(),
|
|
|
|
|
quantizer_params,
|
|
|
|
|
self.requires_grad,
|
|
|
|
|
backward_hooks)
|
2020-09-24 15:20:06 +00:00
|
|
|
return (torch._utils._rebuild_qtensor, args_qtensor)
|
2019-10-04 15:07:44 +00:00
|
|
|
elif self.is_sparse:
|
|
|
|
|
if self.layout == torch.sparse_coo:
|
2021-08-12 18:39:31 +00:00
|
|
|
args_sparse = (self.layout,
|
|
|
|
|
(self._indices(),
|
|
|
|
|
self._values(),
|
|
|
|
|
self.size()))
|
2019-10-04 15:07:44 +00:00
|
|
|
else:
|
|
|
|
|
raise NotImplementedError(
|
2021-08-12 18:39:31 +00:00
|
|
|
'sparse tensor __reduce_ex__ for layout `%s`' % (self.layout))
|
2020-09-24 15:20:06 +00:00
|
|
|
return (torch._utils._rebuild_sparse_tensor, args_sparse)
|
2019-05-31 03:43:36 +00:00
|
|
|
else:
|
Remove dtype from torch.Storage and use only torch.ByteStorage (#62030)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/62030
Remove dtype tracking from Python Storage interface, remove all the different `<type>Storage` classes except for `ByteStorage`, and update serialization accordingly, while maintaining as much FC/BC as possible
Fixes https://github.com/pytorch/pytorch/issues/47442
* **THE SERIALIZATION FORMAT IS FULLY FC/BC.** We worked very hard to make sure this is the case. We will probably want to break FC at some point to make the serialization structure of tensors make more sense, but not today.
* There is now only a single torch.ByteStorage class. Methods like `Tensor.set_` no longer check that the dtype of storage is appropriate.
* As we no longer know what dtype of a storage is, we've **removed** the size method from Storage, replacing it with nbytes. This is to help catch otherwise silent errors where you confuse number of elements with number of bytes.
* `Storage._new_shared` takes a `nbytes` kwarg and will reject previous positional only calls. `Storage._new_with_file` and `_set_from_file` require explicit element size arguments.
* It's no longer possible to convert storages to different types using the float/double/etc methods. Instead, do the conversion using a tensor.
* It's no longer possible to allocate a typed storage directly using FloatStorage/DoubleStorage/etc constructors. Instead, construct a tensor and extract its storage. The classes still exist but they are used purely for unpickling.
* The preexisting serialization format stores dtype with storage, and in fact this dtype is used to determine the dtype of the tensor overall.
To accommodate this case, we introduce a new TypedStorage concept that exists only during unpickling time which is used to temporarily store the dtype so we can construct a tensor. **If you overrode the handling of pickling/unpickling, you MUST add handling for TypedStorage** or your serialization code will degrade to standard file-based serialization.
Original pull request: https://github.com/pytorch/pytorch/pull/59671
Reviewed By: soulitzer, ngimel
Differential Revision: D29466819
Pulled By: ezyang
fbshipit-source-id: 4a14e5d3c2b08e06e558683d97f7378a3180b00e
2021-10-05 20:48:45 +00:00
|
|
|
# TODO: Once we decide to break serialization FC, no longer
|
|
|
|
|
# need to wrap with TypedStorage
|
|
|
|
|
args = (
|
|
|
|
|
torch.storage.TypedStorage(
|
|
|
|
|
wrap_storage=self.storage()._untyped(),
|
|
|
|
|
dtype=self.dtype),
|
|
|
|
|
self.storage_offset(),
|
|
|
|
|
tuple(self.size()),
|
|
|
|
|
self.stride(),
|
|
|
|
|
self.requires_grad,
|
|
|
|
|
backward_hooks) # previously was self._backward_hooks
|
2019-05-31 03:43:36 +00:00
|
|
|
return (torch._utils._rebuild_tensor_v2, args)
|
2018-04-03 20:29:25 +00:00
|
|
|
|
|
|
|
|
def __setstate__(self, state):
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
|
|
|
|
return handle_torch_function(Tensor.__setstate__, (self,), self, state)
|
2018-10-17 03:08:45 +00:00
|
|
|
# Warning: this method is NOT called when you torch.load() a tensor;
|
|
|
|
|
# that is managed by _rebuild_tensor_v2
|
2018-04-04 17:36:56 +00:00
|
|
|
if not self.is_leaf:
|
2021-08-12 18:39:31 +00:00
|
|
|
raise RuntimeError('__setstate__ can be only called on leaf Tensors')
|
2018-04-04 17:36:56 +00:00
|
|
|
if len(state) == 4:
|
|
|
|
|
# legacy serialization of Tensor
|
|
|
|
|
self.set_(*state)
|
|
|
|
|
return
|
|
|
|
|
elif len(state) == 5:
|
2018-04-03 20:29:25 +00:00
|
|
|
# legacy serialization of Variable
|
|
|
|
|
self.data = state[0]
|
|
|
|
|
state = (state[3], state[4], state[2])
|
2018-10-17 03:08:45 +00:00
|
|
|
# The setting of _backward_hooks is expected to be a no-op.
|
|
|
|
|
# See Note [Don't serialize hooks]
|
2018-04-03 20:29:25 +00:00
|
|
|
self.requires_grad, _, self._backward_hooks = state
|
|
|
|
|
|
|
|
|
|
def __repr__(self):
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
|
|
|
|
return handle_torch_function(Tensor.__repr__, (self,), self)
|
2020-04-22 16:20:13 +00:00
|
|
|
# All strings are unicode in Python 3.
|
|
|
|
|
return torch._tensor_str._str(self)
|
2018-04-03 20:29:25 +00:00
|
|
|
|
2021-08-12 18:39:31 +00:00
|
|
|
def backward(self, gradient=None, retain_graph=None, create_graph=False, inputs=None):
|
2018-04-04 17:36:56 +00:00
|
|
|
r"""Computes the gradient of current tensor w.r.t. graph leaves.
|
2018-04-03 20:29:25 +00:00
|
|
|
|
2018-04-04 17:36:56 +00:00
|
|
|
The graph is differentiated using the chain rule. If the tensor is
|
2018-04-03 20:29:25 +00:00
|
|
|
non-scalar (i.e. its data has more than one element) and requires
|
|
|
|
|
gradient, the function additionally requires specifying ``gradient``.
|
|
|
|
|
It should be a tensor of matching type and location, that contains
|
|
|
|
|
the gradient of the differentiated function w.r.t. ``self``.
|
|
|
|
|
|
2020-06-23 00:11:03 +00:00
|
|
|
This function accumulates gradients in the leaves - you might need to zero
|
|
|
|
|
``.grad`` attributes or set them to ``None`` before calling it.
|
|
|
|
|
See :ref:`Default gradient layouts<default-grad-layouts>`
|
|
|
|
|
for details on the memory layout of accumulated gradients.
|
2018-04-03 20:29:25 +00:00
|
|
|
|
Allow consumer ops to sync on GraphRoot's gradient (#45787)
Summary:
Currently, a GraphRoot instance doesn't have an associated stream. Streaming backward synchronization logic assumes the instance ran on the default stream, and tells consumer ops to sync with the default stream. If the gradient the GraphRoot instance passes to consumer backward ops was populated on a non-default stream, we have a race condition.
The race condition can exist even if the user doesn't give a manually populated gradient:
```python
with torch.cuda.stream(side_stream):
# loss.backward() implicitly synthesizes a one-element 1.0 tensor on side_stream
# GraphRoot passes it to consumers, but consumers first sync on default stream, not side_stream.
loss.backward()
# Internally to backward(), streaming-backward logic takes over, stuff executes on the same stream it ran on in forward,
# and the side_stream context is irrelevant. GraphRoot's interaction with its first consumer(s) is the spot where
# the side_stream context causes a problem.
```
This PR fixes the race condition by associating a GraphRoot instance, at construction time, with the current stream(s) on the device(s) of the grads it will pass to consumers. (i think this relies on GraphRoot executing in the main thread, before backward thread(s) fork, because the grads were populated on the main thread.)
The test demonstrates the race condition. It fails reliably without the PR's GraphRoot diffs and passes with the GraphRoot diffs.
With the GraphRoot diffs, manually populating an incoming-gradient arg for `backward` (or `torch.autograd.grad`) and the actual call to `autograd.backward` will have the same stream-semantics relationship as any other pair of ops:
```python
# implicit population is safe
with torch.cuda.stream(side_stream):
loss.backward()
# explicit population in side stream then backward in side stream is safe
with torch.cuda.stream(side_stream):
kickoff_grad = torch.ones_like(loss)
loss.backward(gradient=kickoff_grad)
# explicit population in one stream then backward kickoff in another stream
# is NOT safe, even with this PR's diffs, but that unsafety is consistent with
# stream-semantics relationship of any pair of ops
kickoff_grad = torch.ones_like(loss)
with torch.cuda.stream(side_stream):
loss.backward(gradient=kickoff_grad)
# Safe, as you'd expect for any pair of ops
kickoff_grad = torch.ones_like(loss)
side_stream.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(side_stream):
loss.backward(gradient=kickoff_grad)
```
This PR also adds the last three examples above to cuda docs and references them from autograd docstrings.
Pull Request resolved: https://github.com/pytorch/pytorch/pull/45787
Reviewed By: nairbv
Differential Revision: D24138376
Pulled By: albanD
fbshipit-source-id: bc4cd9390f9f0358633db530b1b09f9c1080d2a3
2020-10-07 15:51:45 +00:00
|
|
|
.. note::
|
|
|
|
|
|
|
|
|
|
If you run any forward ops, create ``gradient``, and/or call ``backward``
|
|
|
|
|
in a user-specified CUDA stream context, see
|
|
|
|
|
:ref:`Stream semantics of backward passes<bwd-cuda-stream-semantics>`.
|
|
|
|
|
|
2021-06-26 01:56:05 +00:00
|
|
|
.. note::
|
|
|
|
|
|
|
|
|
|
When ``inputs`` are provided and a given input is not a leaf,
|
|
|
|
|
the current implementation will call its grad_fn (though it is not strictly needed to get this gradients).
|
|
|
|
|
It is an implementation detail on which the user should not rely.
|
|
|
|
|
See https://github.com/pytorch/pytorch/pull/60521#issuecomment-867061780 for more details.
|
|
|
|
|
|
2020-12-28 17:33:01 +00:00
|
|
|
Args:
|
2018-04-04 17:36:56 +00:00
|
|
|
gradient (Tensor or None): Gradient w.r.t. the
|
|
|
|
|
tensor. If it is a tensor, it will be automatically converted
|
|
|
|
|
to a Tensor that does not require grad unless ``create_graph`` is True.
|
|
|
|
|
None values can be specified for scalar Tensors or ones that
|
2018-04-03 20:29:25 +00:00
|
|
|
don't require grad. If a None value would be acceptable then
|
|
|
|
|
this argument is optional.
|
|
|
|
|
retain_graph (bool, optional): If ``False``, the graph used to compute
|
|
|
|
|
the grads will be freed. Note that in nearly all cases setting
|
|
|
|
|
this option to True is not needed and often can be worked around
|
|
|
|
|
in a much more efficient way. Defaults to the value of
|
|
|
|
|
``create_graph``.
|
|
|
|
|
create_graph (bool, optional): If ``True``, graph of the derivative will
|
|
|
|
|
be constructed, allowing to compute higher order derivative
|
|
|
|
|
products. Defaults to ``False``.
|
2020-11-02 22:28:55 +00:00
|
|
|
inputs (sequence of Tensor): Inputs w.r.t. which the gradient will be
|
|
|
|
|
accumulated into ``.grad``. All other Tensors will be ignored. If not
|
|
|
|
|
provided, the gradient is accumulated into all the leaf Tensors that were
|
2021-06-26 01:56:05 +00:00
|
|
|
used to compute the attr::tensors.
|
2018-04-03 20:29:25 +00:00
|
|
|
"""
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
2020-08-06 03:39:27 +00:00
|
|
|
return handle_torch_function(
|
|
|
|
|
Tensor.backward,
|
2021-01-11 03:16:04 +00:00
|
|
|
(self,),
|
2020-08-06 03:39:27 +00:00
|
|
|
self,
|
|
|
|
|
gradient=gradient,
|
|
|
|
|
retain_graph=retain_graph,
|
2020-11-02 22:28:55 +00:00
|
|
|
create_graph=create_graph,
|
2021-08-12 18:39:31 +00:00
|
|
|
inputs=inputs)
|
|
|
|
|
torch.autograd.backward(self, gradient, retain_graph, create_graph, inputs=inputs)
|
2018-04-03 20:29:25 +00:00
|
|
|
|
|
|
|
|
def register_hook(self, hook):
|
|
|
|
|
r"""Registers a backward hook.
|
|
|
|
|
|
|
|
|
|
The hook will be called every time a gradient with respect to the
|
2018-04-04 17:36:56 +00:00
|
|
|
Tensor is computed. The hook should have the following signature::
|
2018-04-03 20:29:25 +00:00
|
|
|
|
2018-04-04 17:36:56 +00:00
|
|
|
hook(grad) -> Tensor or None
|
2018-04-03 20:29:25 +00:00
|
|
|
|
2018-07-09 01:54:24 +00:00
|
|
|
|
2018-04-03 20:29:25 +00:00
|
|
|
The hook should not modify its argument, but it can optionally return
|
|
|
|
|
a new gradient which will be used in place of :attr:`grad`.
|
|
|
|
|
|
|
|
|
|
This function returns a handle with a method ``handle.remove()``
|
|
|
|
|
that removes the hook from the module.
|
|
|
|
|
|
2018-07-09 01:54:24 +00:00
|
|
|
Example::
|
|
|
|
|
|
2018-04-04 17:36:56 +00:00
|
|
|
>>> v = torch.tensor([0., 0., 0.], requires_grad=True)
|
2018-04-03 20:29:25 +00:00
|
|
|
>>> h = v.register_hook(lambda grad: grad * 2) # double the gradient
|
2018-04-04 17:36:56 +00:00
|
|
|
>>> v.backward(torch.tensor([1., 2., 3.]))
|
|
|
|
|
>>> v.grad
|
|
|
|
|
|
2018-04-03 20:29:25 +00:00
|
|
|
2
|
2018-04-04 17:36:56 +00:00
|
|
|
4
|
|
|
|
|
6
|
|
|
|
|
[torch.FloatTensor of size (3,)]
|
|
|
|
|
|
2018-04-03 20:29:25 +00:00
|
|
|
>>> h.remove() # removes the hook
|
|
|
|
|
"""
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
|
|
|
|
return handle_torch_function(Tensor.register_hook, (self,), self, hook)
|
2018-04-03 20:29:25 +00:00
|
|
|
if not self.requires_grad:
|
2021-08-12 18:39:31 +00:00
|
|
|
raise RuntimeError("cannot register a hook on a tensor that "
|
|
|
|
|
"doesn't require gradient")
|
2018-04-03 20:29:25 +00:00
|
|
|
if self._backward_hooks is None:
|
|
|
|
|
self._backward_hooks = OrderedDict()
|
|
|
|
|
if self.grad_fn is not None:
|
|
|
|
|
self.grad_fn._register_hook_dict(self)
|
|
|
|
|
handle = hooks.RemovableHandle(self._backward_hooks)
|
|
|
|
|
self._backward_hooks[handle.id] = hook
|
|
|
|
|
return handle
|
|
|
|
|
|
|
|
|
|
def reinforce(self, reward):
|
|
|
|
|
def trim(str):
|
2021-08-12 18:39:31 +00:00
|
|
|
return '\n'.join([line.strip() for line in str.split('\n')])
|
2018-04-03 20:29:25 +00:00
|
|
|
|
2021-08-12 18:39:31 +00:00
|
|
|
raise RuntimeError(trim(r"""reinforce() was removed.
|
2018-04-03 20:29:25 +00:00
|
|
|
Use torch.distributions instead.
|
2018-10-15 19:55:10 +00:00
|
|
|
See https://pytorch.org/docs/master/distributions.html
|
2018-04-03 20:29:25 +00:00
|
|
|
|
|
|
|
|
Instead of:
|
|
|
|
|
|
|
|
|
|
probs = policy_network(state)
|
|
|
|
|
action = probs.multinomial()
|
|
|
|
|
next_state, reward = env.step(action)
|
|
|
|
|
action.reinforce(reward)
|
|
|
|
|
action.backward()
|
|
|
|
|
|
|
|
|
|
Use:
|
|
|
|
|
|
|
|
|
|
probs = policy_network(state)
|
|
|
|
|
# NOTE: categorical is equivalent to what used to be called multinomial
|
|
|
|
|
m = torch.distributions.Categorical(probs)
|
|
|
|
|
action = m.sample()
|
|
|
|
|
next_state, reward = env.step(action)
|
|
|
|
|
loss = -m.log_prob(action) * reward
|
|
|
|
|
loss.backward()
|
2021-08-12 18:39:31 +00:00
|
|
|
"""))
|
2018-04-03 20:29:25 +00:00
|
|
|
|
2021-08-12 18:39:31 +00:00
|
|
|
detach = _C._add_docstr(_C._TensorBase.detach, r"""
|
2018-04-04 17:36:56 +00:00
|
|
|
Returns a new Tensor, detached from the current graph.
|
2018-04-03 20:29:25 +00:00
|
|
|
|
|
|
|
|
The result will never require gradient.
|
|
|
|
|
|
2021-05-07 22:50:27 +00:00
|
|
|
This method also affects forward mode AD gradients and the result will never
|
|
|
|
|
have forward mode AD gradients.
|
|
|
|
|
|
2018-04-03 20:29:25 +00:00
|
|
|
.. note::
|
|
|
|
|
|
2018-12-27 00:31:47 +00:00
|
|
|
Returned Tensor shares the same storage with the original one.
|
2018-04-03 20:29:25 +00:00
|
|
|
In-place modifications on either of them will be seen, and may trigger
|
|
|
|
|
errors in correctness checks.
|
2018-12-27 00:31:47 +00:00
|
|
|
IMPORTANT NOTE: Previously, in-place size / stride / storage changes
|
|
|
|
|
(such as `resize_` / `resize_as_` / `set_` / `transpose_`) to the returned tensor
|
|
|
|
|
also update the original tensor. Now, these in-place changes will not update the
|
|
|
|
|
original tensor anymore, and will instead trigger an error.
|
|
|
|
|
For sparse tensors:
|
|
|
|
|
In-place indices / values changes (such as `zero_` / `copy_` / `add_`) to the
|
|
|
|
|
returned tensor will not update the original tensor anymore, and will instead
|
|
|
|
|
trigger an error.
|
2021-08-12 18:39:31 +00:00
|
|
|
""")
|
2018-04-03 20:29:25 +00:00
|
|
|
|
2021-08-12 18:39:31 +00:00
|
|
|
detach_ = _C._add_docstr(_C._TensorBase.detach_, r"""
|
2018-04-04 17:36:56 +00:00
|
|
|
Detaches the Tensor from the graph that created it, making it a leaf.
|
2018-04-03 20:29:25 +00:00
|
|
|
Views cannot be detached in-place.
|
2021-05-07 22:50:27 +00:00
|
|
|
|
|
|
|
|
This method also affects forward mode AD gradients and the result will never
|
|
|
|
|
have forward mode AD gradients.
|
2021-08-12 18:39:31 +00:00
|
|
|
""")
|
2018-04-03 20:29:25 +00:00
|
|
|
|
|
|
|
|
def is_shared(self):
|
|
|
|
|
r"""Checks if tensor is in shared memory.
|
|
|
|
|
|
|
|
|
|
This is always ``True`` for CUDA tensors.
|
|
|
|
|
"""
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
|
|
|
|
return handle_torch_function(Tensor.is_shared, (self,), self)
|
2018-04-03 20:29:25 +00:00
|
|
|
return self.storage().is_shared()
|
|
|
|
|
|
|
|
|
|
def share_memory_(self):
|
|
|
|
|
r"""Moves the underlying storage to shared memory.
|
|
|
|
|
|
|
|
|
|
This is a no-op if the underlying storage is already in shared memory
|
|
|
|
|
and for CUDA tensors. Tensors in shared memory cannot be resized.
|
|
|
|
|
"""
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
|
|
|
|
return handle_torch_function(Tensor.share_memory_, (self,), self)
|
2018-04-03 20:29:25 +00:00
|
|
|
self.storage().share_memory_()
|
|
|
|
|
return self
|
|
|
|
|
|
2018-07-13 02:24:10 +00:00
|
|
|
def __reversed__(self):
|
|
|
|
|
r"""Reverses the tensor along dimension 0."""
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
|
|
|
|
return handle_torch_function(Tensor.__reversed__, (self,), self)
|
2018-07-13 02:24:10 +00:00
|
|
|
if self.dim() == 0:
|
|
|
|
|
return self
|
|
|
|
|
else:
|
|
|
|
|
return self.flip(0)
|
|
|
|
|
|
2019-01-17 06:12:13 +00:00
|
|
|
def norm(self, p="fro", dim=None, keepdim=False, dtype=None):
|
2019-02-15 01:07:12 +00:00
|
|
|
r"""See :func:`torch.norm`"""
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
2021-08-12 18:39:31 +00:00
|
|
|
return handle_torch_function(Tensor.norm, (self,), self, p=p, dim=dim, keepdim=keepdim, dtype=dtype)
|
2019-01-17 06:12:13 +00:00
|
|
|
return torch.norm(self, p, dim, keepdim, dtype=dtype)
|
2018-09-20 21:40:17 +00:00
|
|
|
|
2019-03-29 07:27:48 +00:00
|
|
|
def lu(self, pivot=True, get_infos=False):
|
|
|
|
|
r"""See :func:`torch.lu`"""
|
|
|
|
|
# If get_infos is True, then we don't need to check for errors and vice versa
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
2021-08-12 18:39:31 +00:00
|
|
|
return handle_torch_function(Tensor.lu, (self,), self, pivot=pivot, get_infos=get_infos)
|
2020-10-23 17:11:05 +00:00
|
|
|
|
2021-08-12 18:39:31 +00:00
|
|
|
LU, pivots, infos = torch._lu_with_info(self, pivot=pivot, check_errors=(not get_infos))
|
2019-03-29 07:27:48 +00:00
|
|
|
if get_infos:
|
|
|
|
|
return LU, pivots, infos
|
|
|
|
|
else:
|
|
|
|
|
return LU, pivots
|
|
|
|
|
|
2021-08-12 18:39:31 +00:00
|
|
|
def stft(self, n_fft: int, hop_length: Optional[int] = None,
|
|
|
|
|
win_length: Optional[int] = None, window: 'Optional[Tensor]' = None,
|
|
|
|
|
center: bool = True, pad_mode: str = 'reflect', normalized: bool = False,
|
|
|
|
|
onesided: Optional[bool] = None, return_complex: Optional[bool] = None):
|
2018-07-17 17:54:03 +00:00
|
|
|
r"""See :func:`torch.stft`
|
|
|
|
|
|
|
|
|
|
.. warning::
|
|
|
|
|
This function changed signature at version 0.4.1. Calling with
|
|
|
|
|
the previous signature may cause error or return incorrect result.
|
|
|
|
|
"""
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
2020-08-06 03:39:27 +00:00
|
|
|
return handle_torch_function(
|
2021-08-12 18:39:31 +00:00
|
|
|
Tensor.stft, (self,), self, n_fft, hop_length=hop_length,
|
|
|
|
|
win_length=win_length, window=window, center=center, pad_mode=pad_mode, normalized=normalized,
|
|
|
|
|
onesided=onesided, return_complex=return_complex
|
2020-08-06 03:39:27 +00:00
|
|
|
)
|
2021-08-12 18:39:31 +00:00
|
|
|
return torch.stft(self, n_fft, hop_length, win_length, window, center,
|
|
|
|
|
pad_mode, normalized, onesided, return_complex=return_complex)
|
|
|
|
|
|
|
|
|
|
def istft(self, n_fft: int, hop_length: Optional[int] = None,
|
|
|
|
|
win_length: Optional[int] = None, window: 'Optional[Tensor]' = None,
|
|
|
|
|
center: bool = True, normalized: bool = False,
|
|
|
|
|
onesided: Optional[bool] = None, length: Optional[int] = None,
|
|
|
|
|
return_complex: bool = False):
|
2020-04-24 19:12:33 +00:00
|
|
|
r"""See :func:`torch.istft`"""
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
2020-08-06 03:39:27 +00:00
|
|
|
return handle_torch_function(
|
2021-08-12 18:39:31 +00:00
|
|
|
Tensor.istft, (self,), self, n_fft, hop_length=hop_length, win_length=win_length,
|
|
|
|
|
window=window, center=center, normalized=normalized, onesided=onesided, length=length,
|
|
|
|
|
return_complex=return_complex
|
2020-08-06 03:39:27 +00:00
|
|
|
)
|
2021-08-12 18:39:31 +00:00
|
|
|
return torch.istft(self, n_fft, hop_length, win_length, window, center,
|
|
|
|
|
normalized, onesided, length, return_complex=return_complex)
|
2020-04-24 19:12:33 +00:00
|
|
|
|
2018-04-03 20:29:25 +00:00
|
|
|
def resize(self, *sizes):
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
|
|
|
|
return handle_torch_function(Tensor.resize, (self,), self, *sizes)
|
2018-04-03 20:29:25 +00:00
|
|
|
warnings.warn("non-inplace resize is deprecated")
|
|
|
|
|
from torch.autograd._functions import Resize
|
|
|
|
|
return Resize.apply(self, sizes)
|
|
|
|
|
|
2018-04-04 17:36:56 +00:00
|
|
|
def resize_as(self, tensor):
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_variadic(self, tensor):
|
|
|
|
|
return handle_torch_function(Tensor.resize_as, (self, tensor), self, tensor)
|
2018-04-03 20:29:25 +00:00
|
|
|
warnings.warn("non-inplace resize_as is deprecated")
|
|
|
|
|
from torch.autograd._functions import Resize
|
2018-04-04 17:36:56 +00:00
|
|
|
return Resize.apply(self, tensor.size())
|
2018-04-03 20:29:25 +00:00
|
|
|
|
|
|
|
|
def split(self, split_size, dim=0):
|
2021-08-12 18:39:31 +00:00
|
|
|
r"""See :func:`torch.split`
|
|
|
|
|
"""
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
2021-08-12 18:39:31 +00:00
|
|
|
return handle_torch_function(Tensor.split, (self,), self, split_size, dim=dim)
|
2018-04-03 20:29:25 +00:00
|
|
|
if isinstance(split_size, int):
|
|
|
|
|
return super(Tensor, self).split(split_size, dim)
|
2020-02-08 01:06:44 +00:00
|
|
|
elif isinstance(split_size, Tensor):
|
|
|
|
|
try:
|
|
|
|
|
split_size = int(split_size)
|
|
|
|
|
return super(Tensor, self).split(split_size, dim)
|
|
|
|
|
except ValueError:
|
|
|
|
|
return super(Tensor, self).split_with_sizes(split_size, dim)
|
2018-04-03 20:29:25 +00:00
|
|
|
else:
|
|
|
|
|
return super(Tensor, self).split_with_sizes(split_size, dim)
|
|
|
|
|
|
2019-04-16 20:55:37 +00:00
|
|
|
def unique(self, sorted=True, return_inverse=False, return_counts=False, dim=None):
|
|
|
|
|
r"""Returns the unique elements of the input tensor.
|
2018-04-03 20:29:25 +00:00
|
|
|
|
|
|
|
|
See :func:`torch.unique`
|
|
|
|
|
"""
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
2020-08-06 03:39:27 +00:00
|
|
|
return handle_torch_function(
|
2021-08-12 18:39:31 +00:00
|
|
|
Tensor.unique, (self,), self, sorted=sorted, return_inverse=return_inverse,
|
|
|
|
|
return_counts=return_counts, dim=dim
|
2020-08-06 03:39:27 +00:00
|
|
|
)
|
2021-08-12 18:39:31 +00:00
|
|
|
return torch.unique(self, sorted=sorted, return_inverse=return_inverse, return_counts=return_counts, dim=dim)
|
2018-04-03 20:29:25 +00:00
|
|
|
|
Add torch.unique_consecutive (#19060)
Summary:
Fixes: https://github.com/pytorch/pytorch/issues/19045
Please review: VitalyFedyunin ngimel
This is independent on the #18649 series. This will cause merge conflicts in #18649 series, but please merge this first, and I will resolve the merge conflicts there.
The new feature is exposed in `_unique2_temporary_will_remove_soon` and `_unique_dim2_temporary_will_remove_soon`. But not at `torch.unique` yet. I will take care of the API after #18649 series get merged completely.
Benchmark on a tensor of shape `torch.Size([15320, 2])`:
```python
print(torch.__version__)
print()
a = tensor.sort().values.to('cpu')
print('cpu, sorted_input=False:')
%timeit torch._unique2_temporary_will_remove_soon(a)
%timeit torch._unique2_temporary_will_remove_soon(a, return_inverse=True)
%timeit torch._unique2_temporary_will_remove_soon(a, return_counts=True)
%timeit torch._unique2_temporary_will_remove_soon(a, return_inverse=True, return_counts=True)
print()
print('cpu, sorted_input=True:')
%timeit torch._unique2_temporary_will_remove_soon(a, sorted_input=True)
%timeit torch._unique2_temporary_will_remove_soon(a, sorted_input=True, return_inverse=True)
%timeit torch._unique2_temporary_will_remove_soon(a, sorted_input=True, return_counts=True)
%timeit torch._unique2_temporary_will_remove_soon(a, sorted_input=True, return_inverse=True, return_counts=True)
print()
a = a.to('cuda')
print('cuda, sorted_input=False:')
%timeit torch._unique2_temporary_will_remove_soon(a); torch.cuda.synchronize()
%timeit torch._unique2_temporary_will_remove_soon(a, return_inverse=True); torch.cuda.synchronize()
%timeit torch._unique2_temporary_will_remove_soon(a, return_counts=True); torch.cuda.synchronize()
%timeit torch._unique2_temporary_will_remove_soon(a, return_inverse=True, return_counts=True); torch.cuda.synchronize()
print()
print('cuda, sorted_input=True:')
%timeit torch._unique2_temporary_will_remove_soon(a, sorted_input=True); torch.cuda.synchronize()
%timeit torch._unique2_temporary_will_remove_soon(a, sorted_input=True, return_inverse=True); torch.cuda.synchronize()
%timeit torch._unique2_temporary_will_remove_soon(a, sorted_input=True, return_counts=True); torch.cuda.synchronize()
%timeit torch._unique2_temporary_will_remove_soon(a, sorted_input=True, return_inverse=True, return_counts=True); torch.cuda.synchronize()
```
```
1.1.0a0+2addccc
cpu, sorted_input=False:
340 µs ± 5.88 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
717 µs ± 14.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
52.3 ms ± 2.75 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
52.3 ms ± 1.79 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
cpu, sorted_input=True:
32.8 µs ± 285 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
49.9 µs ± 557 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
51.6 µs ± 1.08 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
78 µs ± 782 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
cuda, sorted_input=False:
213 µs ± 1.52 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
291 µs ± 3.81 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
250 µs ± 1.05 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
321 µs ± 1.59 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
cuda, sorted_input=True:
45.6 µs ± 2.13 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
110 µs ± 2.47 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
82 µs ± 857 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
143 µs ± 409 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
```
```python
print(torch.__version__)
print()
a1, a2 = tensor.unbind(1)
indices = (a1 * tensor.max() + a2).sort().indices
a = tensor.index_select(0, indices).to('cpu')
print('cpu, sorted_input=False:')
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0)
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, return_inverse=True)
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, return_counts=True)
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, return_inverse=True, return_counts=True)
print()
print('cpu, sorted_input=True:')
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, sorted_input=True)
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, sorted_input=True, return_inverse=True)
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, sorted_input=True, return_counts=True)
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, sorted_input=True, return_inverse=True, return_counts=True)
print()
a = a.to('cuda')
print('cuda, sorted_input=False:')
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0); torch.cuda.synchronize()
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, return_inverse=True); torch.cuda.synchronize()
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, return_counts=True); torch.cuda.synchronize()
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, return_inverse=True, return_counts=True); torch.cuda.synchronize()
print()
print('cuda, sorted_input=True:')
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, sorted_input=True); torch.cuda.synchronize()
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, sorted_input=True, return_inverse=True); torch.cuda.synchronize()
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, sorted_input=True, return_counts=True); torch.cuda.synchronize()
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, sorted_input=True, return_inverse=True, return_counts=True); torch.cuda.synchronize()
```
```
cpu, sorted_input=False:
55.4 ms ± 1.12 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
55.8 ms ± 616 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
55.2 ms ± 402 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
55.1 ms ± 725 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
cpu, sorted_input=True:
54.7 ms ± 585 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
55.2 ms ± 1.23 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
54.5 ms ± 865 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
54.9 ms ± 577 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
cuda, sorted_input=False:
171 µs ± 783 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
220 µs ± 1.65 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
203 µs ± 2.95 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
251 µs ± 2.83 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
cuda, sorted_input=True:
59.6 µs ± 757 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
113 µs ± 431 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
93.2 µs ± 2.13 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
147 µs ± 2.81 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
```
The CPU implementation of `unique_dim` is super slow, see https://github.com/pytorch/pytorch/issues/18987, but this PR will not worry about this issue.
Pull Request resolved: https://github.com/pytorch/pytorch/pull/19060
Differential Revision: D14866909
Pulled By: ezyang
fbshipit-source-id: d20012cec68c37b05cf770a6f4d6524f910b950f
2019-04-10 14:33:15 +00:00
|
|
|
def unique_consecutive(self, return_inverse=False, return_counts=False, dim=None):
|
|
|
|
|
r"""Eliminates all but the first element from every consecutive group of equivalent elements.
|
|
|
|
|
|
|
|
|
|
See :func:`torch.unique_consecutive`
|
|
|
|
|
"""
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
2020-08-06 03:39:27 +00:00
|
|
|
return handle_torch_function(
|
2021-08-12 18:39:31 +00:00
|
|
|
Tensor.unique_consecutive, (self,), self, return_inverse=return_inverse,
|
|
|
|
|
return_counts=return_counts, dim=dim
|
2020-08-06 03:39:27 +00:00
|
|
|
)
|
2021-08-12 18:39:31 +00:00
|
|
|
return torch.unique_consecutive(self, return_inverse=return_inverse, return_counts=return_counts, dim=dim)
|
Add torch.unique_consecutive (#19060)
Summary:
Fixes: https://github.com/pytorch/pytorch/issues/19045
Please review: VitalyFedyunin ngimel
This is independent on the #18649 series. This will cause merge conflicts in #18649 series, but please merge this first, and I will resolve the merge conflicts there.
The new feature is exposed in `_unique2_temporary_will_remove_soon` and `_unique_dim2_temporary_will_remove_soon`. But not at `torch.unique` yet. I will take care of the API after #18649 series get merged completely.
Benchmark on a tensor of shape `torch.Size([15320, 2])`:
```python
print(torch.__version__)
print()
a = tensor.sort().values.to('cpu')
print('cpu, sorted_input=False:')
%timeit torch._unique2_temporary_will_remove_soon(a)
%timeit torch._unique2_temporary_will_remove_soon(a, return_inverse=True)
%timeit torch._unique2_temporary_will_remove_soon(a, return_counts=True)
%timeit torch._unique2_temporary_will_remove_soon(a, return_inverse=True, return_counts=True)
print()
print('cpu, sorted_input=True:')
%timeit torch._unique2_temporary_will_remove_soon(a, sorted_input=True)
%timeit torch._unique2_temporary_will_remove_soon(a, sorted_input=True, return_inverse=True)
%timeit torch._unique2_temporary_will_remove_soon(a, sorted_input=True, return_counts=True)
%timeit torch._unique2_temporary_will_remove_soon(a, sorted_input=True, return_inverse=True, return_counts=True)
print()
a = a.to('cuda')
print('cuda, sorted_input=False:')
%timeit torch._unique2_temporary_will_remove_soon(a); torch.cuda.synchronize()
%timeit torch._unique2_temporary_will_remove_soon(a, return_inverse=True); torch.cuda.synchronize()
%timeit torch._unique2_temporary_will_remove_soon(a, return_counts=True); torch.cuda.synchronize()
%timeit torch._unique2_temporary_will_remove_soon(a, return_inverse=True, return_counts=True); torch.cuda.synchronize()
print()
print('cuda, sorted_input=True:')
%timeit torch._unique2_temporary_will_remove_soon(a, sorted_input=True); torch.cuda.synchronize()
%timeit torch._unique2_temporary_will_remove_soon(a, sorted_input=True, return_inverse=True); torch.cuda.synchronize()
%timeit torch._unique2_temporary_will_remove_soon(a, sorted_input=True, return_counts=True); torch.cuda.synchronize()
%timeit torch._unique2_temporary_will_remove_soon(a, sorted_input=True, return_inverse=True, return_counts=True); torch.cuda.synchronize()
```
```
1.1.0a0+2addccc
cpu, sorted_input=False:
340 µs ± 5.88 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
717 µs ± 14.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
52.3 ms ± 2.75 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
52.3 ms ± 1.79 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
cpu, sorted_input=True:
32.8 µs ± 285 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
49.9 µs ± 557 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
51.6 µs ± 1.08 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
78 µs ± 782 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
cuda, sorted_input=False:
213 µs ± 1.52 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
291 µs ± 3.81 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
250 µs ± 1.05 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
321 µs ± 1.59 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
cuda, sorted_input=True:
45.6 µs ± 2.13 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
110 µs ± 2.47 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
82 µs ± 857 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
143 µs ± 409 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
```
```python
print(torch.__version__)
print()
a1, a2 = tensor.unbind(1)
indices = (a1 * tensor.max() + a2).sort().indices
a = tensor.index_select(0, indices).to('cpu')
print('cpu, sorted_input=False:')
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0)
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, return_inverse=True)
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, return_counts=True)
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, return_inverse=True, return_counts=True)
print()
print('cpu, sorted_input=True:')
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, sorted_input=True)
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, sorted_input=True, return_inverse=True)
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, sorted_input=True, return_counts=True)
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, sorted_input=True, return_inverse=True, return_counts=True)
print()
a = a.to('cuda')
print('cuda, sorted_input=False:')
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0); torch.cuda.synchronize()
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, return_inverse=True); torch.cuda.synchronize()
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, return_counts=True); torch.cuda.synchronize()
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, return_inverse=True, return_counts=True); torch.cuda.synchronize()
print()
print('cuda, sorted_input=True:')
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, sorted_input=True); torch.cuda.synchronize()
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, sorted_input=True, return_inverse=True); torch.cuda.synchronize()
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, sorted_input=True, return_counts=True); torch.cuda.synchronize()
%timeit torch._unique_dim2_temporary_will_remove_soon(a, dim=0, sorted_input=True, return_inverse=True, return_counts=True); torch.cuda.synchronize()
```
```
cpu, sorted_input=False:
55.4 ms ± 1.12 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
55.8 ms ± 616 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
55.2 ms ± 402 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
55.1 ms ± 725 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
cpu, sorted_input=True:
54.7 ms ± 585 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
55.2 ms ± 1.23 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
54.5 ms ± 865 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
54.9 ms ± 577 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
cuda, sorted_input=False:
171 µs ± 783 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
220 µs ± 1.65 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
203 µs ± 2.95 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
251 µs ± 2.83 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
cuda, sorted_input=True:
59.6 µs ± 757 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
113 µs ± 431 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
93.2 µs ± 2.13 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
147 µs ± 2.81 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
```
The CPU implementation of `unique_dim` is super slow, see https://github.com/pytorch/pytorch/issues/18987, but this PR will not worry about this issue.
Pull Request resolved: https://github.com/pytorch/pytorch/pull/19060
Differential Revision: D14866909
Pulled By: ezyang
fbshipit-source-id: d20012cec68c37b05cf770a6f4d6524f910b950f
2019-04-10 14:33:15 +00:00
|
|
|
|
2021-05-19 20:08:37 +00:00
|
|
|
@_wrap_type_error_to_not_implemented
|
2018-04-03 20:29:25 +00:00
|
|
|
def __rsub__(self, other):
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_variadic(self, other):
|
|
|
|
|
return handle_torch_function(Tensor.__rsub__, (self, other), self, other)
|
2018-10-30 23:18:55 +00:00
|
|
|
return _C._VariableFunctions.rsub(self, other)
|
2018-04-03 20:29:25 +00:00
|
|
|
|
2021-05-19 20:08:37 +00:00
|
|
|
@_wrap_type_error_to_not_implemented
|
2020-06-20 01:29:36 +00:00
|
|
|
def __rdiv__(self, other):
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_variadic(self, other):
|
|
|
|
|
return handle_torch_function(Tensor.__rdiv__, (self, other), self, other)
|
2020-12-19 00:13:38 +00:00
|
|
|
return self.reciprocal() * other
|
2018-05-03 21:34:59 +00:00
|
|
|
|
2020-06-20 01:29:36 +00:00
|
|
|
__rtruediv__ = __rdiv__
|
|
|
|
|
__itruediv__ = _C._TensorBase.__idiv__
|
|
|
|
|
|
2021-05-19 20:08:37 +00:00
|
|
|
__pow__ = _wrap_type_error_to_not_implemented(_C._TensorBase.pow)
|
2018-04-03 20:29:25 +00:00
|
|
|
|
2021-06-05 23:18:10 +00:00
|
|
|
@_wrap_type_error_to_not_implemented
|
|
|
|
|
def __rmod__(self, other):
|
|
|
|
|
if has_torch_function_variadic(self, other):
|
|
|
|
|
return handle_torch_function(Tensor.__rmod__, (self, other), self, other)
|
|
|
|
|
return torch.remainder(other, self)
|
|
|
|
|
|
2018-04-03 20:29:25 +00:00
|
|
|
def __format__(self, format_spec):
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
|
|
|
|
return handle_torch_function(Tensor.__format__, (self,), self, format_spec)
|
2018-04-03 20:29:25 +00:00
|
|
|
if self.dim() == 0:
|
|
|
|
|
return self.item().__format__(format_spec)
|
|
|
|
|
return object.__format__(self, format_spec)
|
|
|
|
|
|
2020-09-24 15:20:06 +00:00
|
|
|
def __ipow__(self, other): # type: ignore[misc]
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_variadic(self, other):
|
|
|
|
|
return handle_torch_function(Tensor.__ipow__, (self, other), self, other)
|
2019-10-28 21:21:34 +00:00
|
|
|
return NotImplemented
|
2018-04-03 20:29:25 +00:00
|
|
|
|
2019-10-28 21:21:34 +00:00
|
|
|
@_wrap_type_error_to_not_implemented
|
2018-04-03 20:29:25 +00:00
|
|
|
def __rpow__(self, other):
|
`torch.pow` Add type promotion support and fix issue with __rpow__ (#37098)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/37098
### **Cherry-picked from another stack:**
Some code review already occurred here: https://github.com/pytorch/pytorch/pull/32582
### Summary:
Fixes: https://github.com/pytorch/pytorch/issues/32436
The issue caused incorrect handling of dtypes for scalar ** tensor.
e.g. before this change:
```
>>> 5.5 ** torch.ones(5, dtype=torch.int32)
tensor([5, 5, 5, 5, 5], dtype=torch.int32)
```
should return a float tensor.
Also fixes a number of incorrect cases:
* tensors to negative powers were giving incorrect results (1 instead
of 0 or error)
* Behavior wasn't consistent between cuda/cpu
* large_value ** 1 in some cases gave a result not equal
to large_value because of truncation in conversion to double and back.
BC-breaking:
Previously incorrect behavior (in 1.4):
```
>>> a
tensor([1, 1, 1, 1, 1], dtype=torch.int32)
>>> a.pow_(.5)
tensor([1, 1, 1, 1, 1], dtype=torch.int32)
```
After this change:
`RuntimeError: result type Float can't be cast to the desired output type Int`
Test Plan: Imported from OSS
Differential Revision: D21686207
Pulled By: nairbv
fbshipit-source-id: e797e7b195d224fa46404f668bb714e312ea78ac
2020-05-24 20:11:43 +00:00
|
|
|
dtype = torch.result_type(other, self)
|
|
|
|
|
return torch.tensor(other, dtype=dtype, device=self.device) ** self
|
2018-04-03 20:29:25 +00:00
|
|
|
|
2019-10-28 21:21:34 +00:00
|
|
|
@_wrap_type_error_to_not_implemented
|
2018-05-03 21:34:59 +00:00
|
|
|
def __floordiv__(self, other):
|
Use stacklevel for floordiv deprecation warnings (#64034)
Summary:
Fixes https://github.com/pytorch/pytorch/issues/60548
`Tensor.__floordiv__` was indirectly deprecated by deprecation of `torch.floor_divide` (see https://github.com/pytorch/pytorch/issues/43874). Deprecating it directly provides clearer feedback.
Repro:
```
import torch
x = torch.tensor(0)
x // 1
```
Before this change, a deprecation warning was triggered within the C++ implementation of floor_divide:
```
UserWarning: floor_divide is deprecated, and will be removed in a future version of pytorch. It currently rounds toward 0 (like the 'trunc' function NOT 'floor'). This results in incorrect rounding for negative values.
To keep the current behavior, use torch.div(a, b, rounding_mode='trunc'), or for actual floor division, use torch.div(a, b, rounding_mode='floor'). (Triggered internally at ../aten/src/ATen/native/BinaryOps.cpp:571.)
return torch.floor_divide(self, other)
```
After this change, the warning instead cites the user's offending line of Python code:
```
UserWarning: __floordiv__ is deprecated, and its behavior will change in a future version of pytorch. It currently rounds toward 0 (like the 'trunc' function NOT 'floor'). This results in incorrect rounding for negative values.
To keep the current behavior, use torch.div(a, b, rounding_mode='trunc'), or for actual floor division, use torch.div(a, b, rounding_mode='floor').
x // 1
```
Pull Request resolved: https://github.com/pytorch/pytorch/pull/64034
Reviewed By: mruberry
Differential Revision: D30658010
Pulled By: saketh-are
fbshipit-source-id: b0e6c5008d741897509d102f4a89efb47de4aa2a
2021-08-31 17:59:57 +00:00
|
|
|
warnings.warn("__floordiv__ is deprecated, and its behavior will change in a future version of pytorch. "
|
|
|
|
|
"It currently rounds toward 0 (like the 'trunc' function NOT 'floor'). "
|
|
|
|
|
"This results in incorrect rounding for negative values. "
|
|
|
|
|
"To keep the current behavior, use torch.div(a, b, rounding_mode='trunc'), "
|
|
|
|
|
"or for actual floor division, use torch.div(a, b, rounding_mode='floor').", stacklevel=3)
|
|
|
|
|
return torch.div(self, other, rounding_mode='trunc')
|
2018-05-03 21:34:59 +00:00
|
|
|
|
2019-10-28 21:21:34 +00:00
|
|
|
@_wrap_type_error_to_not_implemented
|
2018-05-03 21:34:59 +00:00
|
|
|
def __rfloordiv__(self, other):
|
Use stacklevel for floordiv deprecation warnings (#64034)
Summary:
Fixes https://github.com/pytorch/pytorch/issues/60548
`Tensor.__floordiv__` was indirectly deprecated by deprecation of `torch.floor_divide` (see https://github.com/pytorch/pytorch/issues/43874). Deprecating it directly provides clearer feedback.
Repro:
```
import torch
x = torch.tensor(0)
x // 1
```
Before this change, a deprecation warning was triggered within the C++ implementation of floor_divide:
```
UserWarning: floor_divide is deprecated, and will be removed in a future version of pytorch. It currently rounds toward 0 (like the 'trunc' function NOT 'floor'). This results in incorrect rounding for negative values.
To keep the current behavior, use torch.div(a, b, rounding_mode='trunc'), or for actual floor division, use torch.div(a, b, rounding_mode='floor'). (Triggered internally at ../aten/src/ATen/native/BinaryOps.cpp:571.)
return torch.floor_divide(self, other)
```
After this change, the warning instead cites the user's offending line of Python code:
```
UserWarning: __floordiv__ is deprecated, and its behavior will change in a future version of pytorch. It currently rounds toward 0 (like the 'trunc' function NOT 'floor'). This results in incorrect rounding for negative values.
To keep the current behavior, use torch.div(a, b, rounding_mode='trunc'), or for actual floor division, use torch.div(a, b, rounding_mode='floor').
x // 1
```
Pull Request resolved: https://github.com/pytorch/pytorch/pull/64034
Reviewed By: mruberry
Differential Revision: D30658010
Pulled By: saketh-are
fbshipit-source-id: b0e6c5008d741897509d102f4a89efb47de4aa2a
2021-08-31 17:59:57 +00:00
|
|
|
warnings.warn("__rfloordiv__ is deprecated, and its behavior will change in a future version of pytorch. "
|
|
|
|
|
"It currently rounds toward 0 (like the 'trunc' function NOT 'floor'). "
|
|
|
|
|
"This results in incorrect rounding for negative values. "
|
|
|
|
|
"To keep the current behavior, use torch.div(a, b, rounding_mode='trunc'), "
|
|
|
|
|
"or for actual floor division, use torch.div(a, b, rounding_mode='floor').", stacklevel=3)
|
|
|
|
|
return torch.div(other, self, rounding_mode='trunc')
|
2018-05-03 21:34:59 +00:00
|
|
|
|
2021-05-19 20:08:37 +00:00
|
|
|
@_wrap_type_error_to_not_implemented
|
2021-06-24 06:52:00 +00:00
|
|
|
def __rlshift__(self, other):
|
|
|
|
|
return torch.bitwise_left_shift(other, self)
|
|
|
|
|
|
|
|
|
|
@_wrap_type_error_to_not_implemented
|
|
|
|
|
def __rrshift__(self, other):
|
|
|
|
|
return torch.bitwise_right_shift(other, self)
|
|
|
|
|
|
|
|
|
|
@_wrap_type_error_to_not_implemented
|
2021-05-19 20:08:37 +00:00
|
|
|
def __rmatmul__(self, other):
|
|
|
|
|
if has_torch_function_variadic(self, other):
|
|
|
|
|
return handle_torch_function(Tensor.__rmatmul__, (self, other), self, other)
|
|
|
|
|
return torch.matmul(other, self)
|
|
|
|
|
|
2021-04-27 20:22:54 +00:00
|
|
|
__pos__ = _C._TensorBase.positive
|
2018-04-03 20:29:25 +00:00
|
|
|
__neg__ = _C._TensorBase.neg
|
|
|
|
|
__abs__ = _C._TensorBase.abs
|
|
|
|
|
|
|
|
|
|
def __len__(self):
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
|
|
|
|
return handle_torch_function(Tensor.__len__, (self,), self)
|
2018-04-03 20:29:25 +00:00
|
|
|
if self.dim() == 0:
|
|
|
|
|
raise TypeError("len() of a 0-d tensor")
|
[ONNX] Warning when using __len__ to calculate tensor shape (#55151) (#57595)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/57595
Difference in traced graph and outputs, when using len(tensor) as compared to tensor.shape[0]
An example model is (with tensor.shape):
```
# Test len fix with variable inputs
import torch
import onnxruntime
class Model(torch.nn.Module):
def forward(self, x):
return x.size(1) + x.shape[0]
# Call export
dummy_x = torch.randn(3, 5)
model = Model()
import io
onnx_io = io.BytesIO()
torch.onnx.export(model, (dummy_x,), onnx_io,
input_names=['input'],
dynamic_axes={'input': {0:'h'}},
verbose=True)
# Call onnxruntime runtime and compare outputs on dynamic inputs
ort_session = onnxruntime.InferenceSession(onnx_io.getvalue())
x = torch.randn(2, 5)
print(model(x))
print(ort_session.run(None, {ort_session.get_inputs()[0].name: x.numpy()}))
```
The output graph is as follows:
```
graph(%input : Float(*, 5, strides=[5, 1], requires_grad=0, device=cpu)):
%1 : Long(2, strides=[1], device=cpu) = onnx::Shape(%input)
%2 : Long(device=cpu) = onnx::Constant[value={1}]()
%3 : Long(device=cpu) = onnx::Gather[axis=0](%1, %2) # test/onnx/test_m.py:9:0
%4 : Long(2, strides=[1], device=cpu) = onnx::Shape(%input)
%5 : Long(device=cpu) = onnx::Constant[value={0}]()
%6 : Long(device=cpu) = onnx::Gather[axis=0](%4, %5) # test/onnx/test_m.py:9:0
%7 : Long(requires_grad=0, device=cpu) = onnx::Add(%3, %6) # test/onnx/test_m.py:9:0
return (%7)
```
Torch output: 7
ORT output: 7
Now replacing tensor.shape[0] with len(tensor), the graph looks like:
```
graph(%input : Float(*, 5, strides=[5, 1], requires_grad=0, device=cpu)):
%1 : Long(2, strides=[1], device=cpu) = onnx::Shape(%input)
%2 : Long(device=cpu) = onnx::Constant[value={1}]()
%3 : Long(device=cpu) = onnx::Gather[axis=0](%1, %2) # test/onnx/test_m.py:9:0
%4 : Long(requires_grad=0, device=cpu) = onnx::Constant[value={3}]()
%5 : Long(requires_grad=0, device=cpu) = onnx::Add(%3, %4)
return (%5)
```
Torch output: 7
ORT output: 8
In the case with __len__, %4 is traced as a constant
**Workaround to avoid the mismatch when using len to get tensor.shape**
Add the following pattern around _export call
```
import builtins
len_backup = builtins.len
builtins.len = lambda x : x.__len__()
# Call export
_export(model, args, .....
builtins.len = len_backup
```
Test Plan: Imported from OSS
Reviewed By: malfet
Differential Revision: D28393526
Pulled By: SplitInfinity
fbshipit-source-id: a7d50740442c7e913119f9f92deab48aa8c02843
Co-authored-by: shubhambhokare1 <shubhambhokare1@gmail.com>
2021-05-13 20:37:10 +00:00
|
|
|
if torch._C._get_tracing_state():
|
2021-08-12 18:39:31 +00:00
|
|
|
warnings.warn('Using len to get tensor shape might cause the trace to be incorrect. '
|
|
|
|
|
'Recommended usage would be tensor.shape[0]. '
|
|
|
|
|
'Passing a tensor of different shape might lead to errors or silently give '
|
|
|
|
|
'incorrect results.', category=torch.jit.TracerWarning, stacklevel=2)
|
2018-04-03 20:29:25 +00:00
|
|
|
return self.shape[0]
|
|
|
|
|
|
|
|
|
|
def __iter__(self):
|
2020-08-06 03:39:27 +00:00
|
|
|
# NB: we use 'imap' and not 'map' here, so that in Python 2 we get a
|
|
|
|
|
# generator and don't eagerly perform all the indexes. This could
|
|
|
|
|
# save us work, and also helps keep trace ordering deterministic
|
|
|
|
|
# (e.g., if you zip(*hiddens), the eager map will force all the
|
|
|
|
|
# indexes of hiddens[0] before hiddens[1], while the generator
|
|
|
|
|
# map will interleave them.)
|
2021-03-30 15:26:19 +00:00
|
|
|
# NB: We have intentionally skipped __torch_function__ dispatch here.
|
|
|
|
|
# See gh-54457
|
2018-04-03 20:29:25 +00:00
|
|
|
if self.dim() == 0:
|
2021-08-12 18:39:31 +00:00
|
|
|
raise TypeError('iteration over a 0-d tensor')
|
2018-08-31 21:16:31 +00:00
|
|
|
if torch._C._get_tracing_state():
|
2021-08-12 18:39:31 +00:00
|
|
|
warnings.warn('Iterating over a tensor might cause the trace to be incorrect. '
|
|
|
|
|
'Passing a tensor of different shape won\'t change the number of '
|
|
|
|
|
'iterations executed (and might lead to errors or silently give '
|
|
|
|
|
'incorrect results).', category=torch.jit.TracerWarning, stacklevel=2)
|
2020-07-06 17:51:08 +00:00
|
|
|
return iter(self.unbind(0))
|
2018-04-03 20:29:25 +00:00
|
|
|
|
|
|
|
|
def __hash__(self):
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
|
|
|
|
return handle_torch_function(Tensor.__hash__, (self,), self)
|
2018-04-03 20:29:25 +00:00
|
|
|
return id(self)
|
|
|
|
|
|
|
|
|
|
def __dir__(self):
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
|
|
|
|
return handle_torch_function(Tensor.__dir__, (self,), self)
|
2018-04-04 17:36:56 +00:00
|
|
|
tensor_methods = dir(self.__class__)
|
2021-08-12 18:39:31 +00:00
|
|
|
tensor_methods.remove('volatile') # deprecated
|
2018-04-03 20:29:25 +00:00
|
|
|
attrs = list(self.__dict__.keys())
|
2018-04-04 17:36:56 +00:00
|
|
|
keys = tensor_methods + attrs
|
2018-10-12 20:33:43 +00:00
|
|
|
|
|
|
|
|
# property only available dense, cuda tensors
|
|
|
|
|
if (not self.is_cuda) or self.is_sparse:
|
|
|
|
|
keys.remove("__cuda_array_interface__")
|
|
|
|
|
|
2018-04-03 20:29:25 +00:00
|
|
|
return sorted(keys)
|
|
|
|
|
|
|
|
|
|
# Numpy array interface, to support `numpy.asarray(tensor) -> ndarray`
|
2021-08-12 18:39:31 +00:00
|
|
|
__array_priority__ = 1000 # prefer Tensor ops over numpy ones
|
2018-07-30 21:37:21 +00:00
|
|
|
|
2018-04-03 20:29:25 +00:00
|
|
|
def __array__(self, dtype=None):
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
|
|
|
|
return handle_torch_function(Tensor.__array__, (self,), self, dtype=dtype)
|
2018-04-03 20:29:25 +00:00
|
|
|
if dtype is None:
|
2018-08-16 19:02:45 +00:00
|
|
|
return self.numpy()
|
2018-04-03 20:29:25 +00:00
|
|
|
else:
|
2018-08-16 19:02:45 +00:00
|
|
|
return self.numpy().astype(dtype, copy=False)
|
2018-04-03 20:29:25 +00:00
|
|
|
|
|
|
|
|
# Wrap Numpy array again in a suitable tensor when done, to support e.g.
|
|
|
|
|
# `numpy.sin(tensor) -> tensor` or `numpy.greater(tensor, 0) -> ByteTensor`
|
|
|
|
|
def __array_wrap__(self, array):
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
2021-08-12 18:39:31 +00:00
|
|
|
return handle_torch_function(Tensor.__array_wrap__, (self,), self, array=array)
|
2018-04-03 20:29:25 +00:00
|
|
|
if array.dtype == bool:
|
|
|
|
|
# Workaround, torch has no built-in bool tensor
|
2021-08-12 18:39:31 +00:00
|
|
|
array = array.astype('uint8')
|
2018-04-03 20:29:25 +00:00
|
|
|
return torch.from_numpy(array)
|
|
|
|
|
|
2019-03-11 15:55:01 +00:00
|
|
|
def __contains__(self, element):
|
|
|
|
|
r"""Check if `element` is present in tensor
|
|
|
|
|
|
2020-12-28 17:33:01 +00:00
|
|
|
Args:
|
2019-03-11 15:55:01 +00:00
|
|
|
element (Tensor or scalar): element to be checked
|
|
|
|
|
for presence in current tensor"
|
|
|
|
|
"""
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
|
|
|
|
return handle_torch_function(Tensor.__contains__, (self,), self, element)
|
2019-03-11 15:55:01 +00:00
|
|
|
if isinstance(element, (torch.Tensor, Number)):
|
2020-09-24 15:20:06 +00:00
|
|
|
# type hint doesn't understand the __contains__ result array
|
|
|
|
|
return (element == self).any().item() # type: ignore[union-attr]
|
2019-09-13 16:26:02 +00:00
|
|
|
|
|
|
|
|
raise RuntimeError(
|
2021-08-12 18:39:31 +00:00
|
|
|
"Tensor.__contains__ only supports Tensor or scalar, but you passed in a %s." %
|
|
|
|
|
type(element)
|
2019-09-13 16:26:02 +00:00
|
|
|
)
|
2019-03-11 15:55:01 +00:00
|
|
|
|
2018-10-12 20:33:43 +00:00
|
|
|
@property
|
|
|
|
|
def __cuda_array_interface__(self):
|
|
|
|
|
"""Array view description for cuda tensors.
|
|
|
|
|
|
|
|
|
|
See:
|
|
|
|
|
https://numba.pydata.org/numba-doc/latest/cuda/cuda_array_interface.html
|
|
|
|
|
"""
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
2020-09-24 15:20:06 +00:00
|
|
|
# TODO mypy doesn't support @property, see: https://github.com/python/mypy/issues/6185
|
2021-01-11 03:16:04 +00:00
|
|
|
return handle_torch_function(Tensor.__cuda_array_interface__.__get__, (self,), self) # type: ignore[attr-defined]
|
2018-10-12 20:33:43 +00:00
|
|
|
|
|
|
|
|
# raise AttributeError for unsupported tensors, so that
|
|
|
|
|
# hasattr(cpu_tensor, "__cuda_array_interface__") is False.
|
|
|
|
|
if not self.is_cuda:
|
|
|
|
|
raise AttributeError(
|
|
|
|
|
"Can't get __cuda_array_interface__ on non-CUDA tensor type: %s "
|
2021-08-12 18:39:31 +00:00
|
|
|
"If CUDA data is required use tensor.cuda() to copy tensor to device memory." %
|
|
|
|
|
self.type()
|
2018-10-12 20:33:43 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
if self.is_sparse:
|
|
|
|
|
raise AttributeError(
|
|
|
|
|
"Can't get __cuda_array_interface__ on sparse type: %s "
|
2021-08-12 18:39:31 +00:00
|
|
|
"Use Tensor.to_dense() to convert to a dense tensor first." %
|
|
|
|
|
self.type()
|
2018-10-12 20:33:43 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
# RuntimeError, matching tensor.__array__() behavior.
|
|
|
|
|
if self.requires_grad:
|
|
|
|
|
raise RuntimeError(
|
|
|
|
|
"Can't get __cuda_array_interface__ on Variable that requires grad. "
|
|
|
|
|
"If gradients aren't required, use var.detach() to get Variable that doesn't require grad."
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
# CUDA devices are little-endian and tensors are stored in native byte
|
|
|
|
|
# order. 1-byte entries are endian-agnostic.
|
|
|
|
|
typestr = {
|
2020-08-14 17:24:22 +00:00
|
|
|
torch.complex64: "<c8",
|
|
|
|
|
torch.complex128: "<c16",
|
2018-10-12 20:33:43 +00:00
|
|
|
torch.float16: "<f2",
|
|
|
|
|
torch.float32: "<f4",
|
|
|
|
|
torch.float64: "<f8",
|
|
|
|
|
torch.uint8: "|u1",
|
|
|
|
|
torch.int8: "|i1",
|
|
|
|
|
torch.int16: "<i2",
|
|
|
|
|
torch.int32: "<i4",
|
|
|
|
|
torch.int64: "<i8",
|
|
|
|
|
}[self.dtype]
|
|
|
|
|
|
|
|
|
|
itemsize = self.storage().element_size()
|
|
|
|
|
|
2019-08-23 15:54:16 +00:00
|
|
|
shape = tuple(self.shape)
|
2019-12-06 15:33:41 +00:00
|
|
|
if self.is_contiguous():
|
|
|
|
|
# __cuda_array_interface__ v2 requires the strides to be omitted
|
|
|
|
|
# (either not set or set to None) for C-contiguous arrays.
|
|
|
|
|
strides = None
|
|
|
|
|
else:
|
|
|
|
|
strides = tuple(s * itemsize for s in self.stride())
|
|
|
|
|
data_ptr = self.data_ptr() if self.numel() > 0 else 0
|
|
|
|
|
data = (data_ptr, False) # read-only is false
|
2018-10-12 20:33:43 +00:00
|
|
|
|
2019-12-06 15:33:41 +00:00
|
|
|
return dict(typestr=typestr, shape=shape, strides=strides, data=data, version=2)
|
2018-10-12 20:33:43 +00:00
|
|
|
|
Remove dtype from torch.Storage and use only torch.ByteStorage (#62030)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/62030
Remove dtype tracking from Python Storage interface, remove all the different `<type>Storage` classes except for `ByteStorage`, and update serialization accordingly, while maintaining as much FC/BC as possible
Fixes https://github.com/pytorch/pytorch/issues/47442
* **THE SERIALIZATION FORMAT IS FULLY FC/BC.** We worked very hard to make sure this is the case. We will probably want to break FC at some point to make the serialization structure of tensors make more sense, but not today.
* There is now only a single torch.ByteStorage class. Methods like `Tensor.set_` no longer check that the dtype of storage is appropriate.
* As we no longer know what dtype of a storage is, we've **removed** the size method from Storage, replacing it with nbytes. This is to help catch otherwise silent errors where you confuse number of elements with number of bytes.
* `Storage._new_shared` takes a `nbytes` kwarg and will reject previous positional only calls. `Storage._new_with_file` and `_set_from_file` require explicit element size arguments.
* It's no longer possible to convert storages to different types using the float/double/etc methods. Instead, do the conversion using a tensor.
* It's no longer possible to allocate a typed storage directly using FloatStorage/DoubleStorage/etc constructors. Instead, construct a tensor and extract its storage. The classes still exist but they are used purely for unpickling.
* The preexisting serialization format stores dtype with storage, and in fact this dtype is used to determine the dtype of the tensor overall.
To accommodate this case, we introduce a new TypedStorage concept that exists only during unpickling time which is used to temporarily store the dtype so we can construct a tensor. **If you overrode the handling of pickling/unpickling, you MUST add handling for TypedStorage** or your serialization code will degrade to standard file-based serialization.
Original pull request: https://github.com/pytorch/pytorch/pull/59671
Reviewed By: soulitzer, ngimel
Differential Revision: D29466819
Pulled By: ezyang
fbshipit-source-id: 4a14e5d3c2b08e06e558683d97f7378a3180b00e
2021-10-05 20:48:45 +00:00
|
|
|
def storage_type(self):
|
|
|
|
|
r"""storage_type() -> type
|
|
|
|
|
|
|
|
|
|
Returns the type of the underlying storage.
|
|
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
# NB: this returns old fashioned TypedStorage, e.g., FloatStorage, as it
|
|
|
|
|
# would be pretty pointless otherwise (it would always return
|
|
|
|
|
# UntypedStorage)
|
|
|
|
|
return type(self.storage())
|
|
|
|
|
|
2019-09-13 05:51:52 +00:00
|
|
|
def refine_names(self, *names):
|
2019-10-09 05:20:20 +00:00
|
|
|
r"""Refines the dimension names of :attr:`self` according to :attr:`names`.
|
|
|
|
|
|
|
|
|
|
Refining is a special case of renaming that "lifts" unnamed dimensions.
|
|
|
|
|
A ``None`` dim can be refined to have any name; a named dim can only be
|
|
|
|
|
refined to have the same name.
|
|
|
|
|
|
|
|
|
|
Because named tensors can coexist with unnamed tensors, refining names
|
|
|
|
|
gives a nice way to write named-tensor-aware code that works with both
|
|
|
|
|
named and unnamed tensors.
|
|
|
|
|
|
|
|
|
|
:attr:`names` may contain up to one Ellipsis (``...``).
|
|
|
|
|
The Ellipsis is expanded greedily; it is expanded in-place to fill
|
|
|
|
|
:attr:`names` to the same length as ``self.dim()`` using names from the
|
|
|
|
|
corresponding indices of ``self.names``.
|
|
|
|
|
|
|
|
|
|
Python 2 does not support Ellipsis but one may use a string literal
|
|
|
|
|
instead (``'...'``).
|
|
|
|
|
|
2020-12-28 17:33:01 +00:00
|
|
|
Args:
|
2019-10-09 05:20:20 +00:00
|
|
|
names (iterable of str): The desired names of the output tensor. May
|
|
|
|
|
contain up to one Ellipsis.
|
|
|
|
|
|
|
|
|
|
Examples::
|
|
|
|
|
|
|
|
|
|
>>> imgs = torch.randn(32, 3, 128, 128)
|
|
|
|
|
>>> named_imgs = imgs.refine_names('N', 'C', 'H', 'W')
|
|
|
|
|
>>> named_imgs.names
|
|
|
|
|
('N', 'C', 'H', 'W')
|
|
|
|
|
|
|
|
|
|
>>> tensor = torch.randn(2, 3, 5, 7, 11)
|
|
|
|
|
>>> tensor = tensor.refine_names('A', ..., 'B', 'C')
|
|
|
|
|
>>> tensor.names
|
|
|
|
|
('A', None, None, 'B', 'C')
|
|
|
|
|
|
|
|
|
|
.. warning::
|
|
|
|
|
The named tensor API is experimental and subject to change.
|
|
|
|
|
|
|
|
|
|
"""
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
|
|
|
|
return handle_torch_function(Tensor.refine_names, (self,), self, *names)
|
2021-08-12 18:39:31 +00:00
|
|
|
names = resolve_ellipsis(names, self.names, 'refine_names')
|
2019-09-13 05:51:52 +00:00
|
|
|
return super(Tensor, self).refine_names(names)
|
|
|
|
|
|
2019-09-13 05:51:52 +00:00
|
|
|
def align_to(self, *names):
|
2019-10-09 05:20:20 +00:00
|
|
|
r"""Permutes the dimensions of the :attr:`self` tensor to match the order
|
|
|
|
|
specified in :attr:`names`, adding size-one dims for any new names.
|
|
|
|
|
|
|
|
|
|
All of the dims of :attr:`self` must be named in order to use this method.
|
|
|
|
|
The resulting tensor is a view on the original tensor.
|
|
|
|
|
|
|
|
|
|
All dimension names of :attr:`self` must be present in :attr:`names`.
|
|
|
|
|
:attr:`names` may contain additional names that are not in ``self.names``;
|
|
|
|
|
the output tensor has a size-one dimension for each of those new names.
|
|
|
|
|
|
|
|
|
|
:attr:`names` may contain up to one Ellipsis (``...``).
|
|
|
|
|
The Ellipsis is expanded to be equal to all dimension names of :attr:`self`
|
|
|
|
|
that are not mentioned in :attr:`names`, in the order that they appear
|
|
|
|
|
in :attr:`self`.
|
|
|
|
|
|
|
|
|
|
Python 2 does not support Ellipsis but one may use a string literal
|
|
|
|
|
instead (``'...'``).
|
|
|
|
|
|
2020-12-28 17:33:01 +00:00
|
|
|
Args:
|
2019-10-09 05:20:20 +00:00
|
|
|
names (iterable of str): The desired dimension ordering of the
|
|
|
|
|
output tensor. May contain up to one Ellipsis that is expanded
|
|
|
|
|
to all unmentioned dim names of :attr:`self`.
|
|
|
|
|
|
|
|
|
|
Examples::
|
|
|
|
|
|
|
|
|
|
>>> tensor = torch.randn(2, 2, 2, 2, 2, 2)
|
|
|
|
|
>>> named_tensor = tensor.refine_names('A', 'B', 'C', 'D', 'E', 'F')
|
|
|
|
|
|
|
|
|
|
# Move the F and E dims to the front while keeping the rest in order
|
|
|
|
|
>>> named_tensor.align_to('F', 'E', ...)
|
|
|
|
|
|
|
|
|
|
.. warning::
|
|
|
|
|
The named tensor API is experimental and subject to change.
|
|
|
|
|
|
|
|
|
|
"""
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
|
|
|
|
return handle_torch_function(Tensor.align_to, (self,), self, *names)
|
2021-08-12 18:39:31 +00:00
|
|
|
ellipsis_idx = single_ellipsis_index(names, 'align_to')
|
Allow `align_to` to take in partially named tensors (#27308)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/27308
Currently, `tensor.align_to(*names)` has the restriction that the
`tensor` must be fully named. This doesn't need to be the case, when
using Ellipsis, we "expand the ellipsis to all unmentioned dimensions,
in the order which they appear in the original tensor".
For example, consider `tensor: Tensor[None, None, C]`.
`tensor.align_to(C, None, None)` is ambiguous because the user might
have wanted to switch the order of the None dimensions and there is no
way to specify that using this API. However, `tensor.align_to('C', ...)`
isn't ambiguous: we can select the two unnamed dimensions in the order
in which they appear.
To actually implement this, we write a brand-new `align_to(names,
ellipsis_idx)` function in c++ that is separate from the regular
`align_to(names)` implementation. Ideally we would support "..." as a
special name in c++ and combine the two implementations; we'll need to
support "..." in c++ in the future but that requires a bit of extra work.
In this PR, Python processees the ellipsis and then calls the correct
overload.
Test Plan: - run tests
Differential Revision: D17745179
Pulled By: zou3519
fbshipit-source-id: 9fed06d224215cfb7efecd8c002604baab3c45e6
2019-10-09 23:27:09 +00:00
|
|
|
if ellipsis_idx is None:
|
|
|
|
|
return super(Tensor, self).align_to(names)
|
Fix ellipsis behavior for `Tensor.align_to` to glob all missing dims (#26648)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/26648
Previously:
- `Tensor.align_to(*names)` only works on fully named tensors. In addition, the
desired ordering `names` must not have any None-names.
- `Tensor.align_to(*names)` accepted `...`, but expanded it based on
position. i.e., in `tensor.align_to('N', ..., 'C', 'H')`, `...` expand
to `*tensor.names[1:-2]`. This is wildly incorrect: see the following
concrete example.
```
tensor = tensor.refine_names('N', 'C', 'H, 'W')
tensor.align_to('W', ...) # ... expands to 'C', 'H, 'W'
```
This PR changes it so that `...` in `tensor.align_to` grabs all
unmentioned dimensions from `tensor`, in the order that they appear.
`align_to` is the only function that takes ellipsis that requires this
change. This is because all other functions (`refine_to`) require their
list of names to work in a positional manner, but `align_to` lets the
user reorder dimensions.
This does not add very much overhead to `align_to`, as shown in the
following benchmark. However, in the future, we should resolve to make
these operations faster; align_to should be as fast as view but isn't
most likely due to Python overhead.
```
[ins] In [2]: import torch
...: named = torch.randn(3, 3, 3, 3, names=('N', 'C', 'H', 'W'))
...: unnamed = torch.randn(3, 3, 3, 3)
...: %timeit unnamed[:]
...: %timeit unnamed.view(-1)
...: %timeit named.align_to(...)
...: %timeit named.align_to('N', 'C', 'H', 'W')
31 µs ± 126 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
43.8 µs ± 146 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
69.6 µs ± 142 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
66.1 µs ± 1.13 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
```
Test Plan:
- new tests [namedtensor ci]
allows the user to transpose and permute dimensions.
Differential Revision: D17528207
Pulled By: zou3519
fbshipit-source-id: 4efc70329f84058c245202d0b267d0bc5ce42069
2019-09-23 19:14:57 +00:00
|
|
|
return super(Tensor, self).align_to(
|
2021-08-12 18:39:31 +00:00
|
|
|
[name for name in names if not is_ellipsis(name)],
|
|
|
|
|
ellipsis_idx)
|
2019-09-13 05:51:52 +00:00
|
|
|
|
2020-08-12 20:08:54 +00:00
|
|
|
def unflatten(self, dim, sizes):
|
|
|
|
|
r"""Expands the dimension :attr:`dim` of the :attr:`self` tensor over multiple dimensions
|
|
|
|
|
of sizes given by :attr:`sizes`.
|
|
|
|
|
|
|
|
|
|
* :attr:`sizes` is the new shape of the unflattened dimension and it can be a `Tuple[int]` as well
|
|
|
|
|
as `torch.Size` if :attr:`self` is a `Tensor`, or `namedshape` (Tuple[(name: str, size: int)])
|
|
|
|
|
if :attr:`self` is a `NamedTensor`. The total number of elements in sizes must match the number
|
|
|
|
|
of elements in the original dim being unflattened.
|
2019-10-09 05:20:20 +00:00
|
|
|
|
2020-12-28 17:33:01 +00:00
|
|
|
Args:
|
2020-08-12 20:08:54 +00:00
|
|
|
dim (Union[int, str]): Dimension to unflatten
|
|
|
|
|
sizes (Union[Tuple[int] or torch.Size, Tuple[Tuple[str, int]]]): New shape of the unflattened dimension
|
2019-10-09 05:20:20 +00:00
|
|
|
|
2020-08-12 20:08:54 +00:00
|
|
|
Examples:
|
|
|
|
|
>>> torch.randn(3, 4, 1).unflatten(1, (2, 2)).shape
|
|
|
|
|
torch.Size([3, 2, 2, 1])
|
2021-02-18 16:35:58 +00:00
|
|
|
>>> torch.randn(3, 4, 1).unflatten(1, (-1, 2)).shape # the size -1 is inferred from the size of dimension 1
|
|
|
|
|
torch.Size([3, 2, 2, 1])
|
2020-08-12 20:08:54 +00:00
|
|
|
>>> torch.randn(2, 4, names=('A', 'B')).unflatten('B', (('B1', 2), ('B2', 2)))
|
|
|
|
|
tensor([[[-1.1772, 0.0180],
|
|
|
|
|
[ 0.2412, 0.1431]],
|
|
|
|
|
[[-1.1819, -0.8899],
|
|
|
|
|
[ 1.5813, 0.2274]]], names=('A', 'B1', 'B2'))
|
2021-02-18 16:35:58 +00:00
|
|
|
>>> torch.randn(2, names=('A',)).unflatten('A', (('B1', -1), ('B2', 1)))
|
|
|
|
|
tensor([[-0.8591],
|
|
|
|
|
[ 0.3100]], names=('B1', 'B2'))
|
2019-10-09 05:20:20 +00:00
|
|
|
|
|
|
|
|
.. warning::
|
|
|
|
|
The named tensor API is experimental and subject to change.
|
2021-02-18 16:35:58 +00:00
|
|
|
|
2019-10-09 05:20:20 +00:00
|
|
|
"""
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
|
|
|
|
return handle_torch_function(Tensor.unflatten, (self,), self, dim, sizes)
|
2020-08-12 20:08:54 +00:00
|
|
|
|
|
|
|
|
if not sizes:
|
|
|
|
|
raise RuntimeError("unflatten: sizes must be non-empty")
|
|
|
|
|
|
|
|
|
|
names = None
|
2021-08-12 18:39:31 +00:00
|
|
|
if isinstance(sizes, OrderedDict) or (isinstance(sizes, (tuple, list)) and isinstance(sizes[0], (tuple, list))):
|
2020-08-12 20:08:54 +00:00
|
|
|
names, sizes = unzip_namedshape(sizes)
|
2019-09-18 04:22:53 +00:00
|
|
|
return super(Tensor, self).unflatten(dim, sizes, names)
|
|
|
|
|
|
2021-08-12 18:39:31 +00:00
|
|
|
|
2019-09-22 22:36:47 +00:00
|
|
|
def rename_(self, *names, **rename_map):
|
2019-10-09 05:20:20 +00:00
|
|
|
"""In-place version of :meth:`~Tensor.rename`."""
|
|
|
|
|
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
2021-08-12 18:39:31 +00:00
|
|
|
return handle_torch_function(Tensor.rename_, (self,), self, *names, **rename_map)
|
2020-08-06 03:39:27 +00:00
|
|
|
|
2019-09-22 22:36:47 +00:00
|
|
|
# Note [rename_ / rename API]
|
Update tensor.view_names / tensor.names_ API (#23973)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/23973
Without loss of generality, I describe the API for `tensor.view_names`.
`tensor.names_` has an analogous API.
`tensor.view_names(*names)` returns a view on tensor with named dims `names`.
`names` must be of length `tensor.dim()`; otherwise, if '*' is in `names`,
then it (known as the "glob") is expanded greedily to be equal to the
corresponding names from `tensor.names`.
For example,
```
>>> x = torch.empty(2, 3, 5, 7, names=('N', 'C', 'H', 'W'))
>>> x.view_names('*', 'height', 'width').names
('N', 'C', 'height', 'width')
>>> x.view_names('batch', '*', 'width').names
('batch', 'C', 'H', 'width')
```
tensor.view_names(**rename_map) returns a view on tensor that has
renamed dims as specified in the mapping `rename_map`.
For example,
```
>>> x = torch.empty(2, 3, 5, 7, names=('N', 'C', 'H', 'W'))
>>> x.view_names(W='width', H='height').names
('N', 'C', 'height', 'width')
```
These are different(!!!) from the C++ API, which only allows the
following:
- tensor.view_names(optional<DimnameList>)
C++ API parity for named tensors is not important right now; I am
punting that to the future.
Test Plan: - [namedtensor ci]
Differential Revision: D16710916
Pulled By: zou3519
fbshipit-source-id: 7cb8056c0fb4c97b04c3a2d1dd0f737e0a67ce34
2019-08-14 16:31:54 +00:00
|
|
|
# The Python API for these is different from the C++ API. In Python:
|
2019-09-22 22:36:47 +00:00
|
|
|
# 1) tensor.rename(*names) takes a vararglist of names
|
|
|
|
|
# 2) tensor.rename(**rename_map) takes a map of names to rename.
|
Update tensor.view_names / tensor.names_ API (#23973)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/23973
Without loss of generality, I describe the API for `tensor.view_names`.
`tensor.names_` has an analogous API.
`tensor.view_names(*names)` returns a view on tensor with named dims `names`.
`names` must be of length `tensor.dim()`; otherwise, if '*' is in `names`,
then it (known as the "glob") is expanded greedily to be equal to the
corresponding names from `tensor.names`.
For example,
```
>>> x = torch.empty(2, 3, 5, 7, names=('N', 'C', 'H', 'W'))
>>> x.view_names('*', 'height', 'width').names
('N', 'C', 'height', 'width')
>>> x.view_names('batch', '*', 'width').names
('batch', 'C', 'H', 'width')
```
tensor.view_names(**rename_map) returns a view on tensor that has
renamed dims as specified in the mapping `rename_map`.
For example,
```
>>> x = torch.empty(2, 3, 5, 7, names=('N', 'C', 'H', 'W'))
>>> x.view_names(W='width', H='height').names
('N', 'C', 'height', 'width')
```
These are different(!!!) from the C++ API, which only allows the
following:
- tensor.view_names(optional<DimnameList>)
C++ API parity for named tensors is not important right now; I am
punting that to the future.
Test Plan: - [namedtensor ci]
Differential Revision: D16710916
Pulled By: zou3519
fbshipit-source-id: 7cb8056c0fb4c97b04c3a2d1dd0f737e0a67ce34
2019-08-14 16:31:54 +00:00
|
|
|
# C++ is static, making it difficult to implement similar behavior.
|
2019-09-18 12:44:43 +00:00
|
|
|
return update_names(self, names, rename_map, inplace=True)
|
Update tensor.view_names / tensor.names_ API (#23973)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/23973
Without loss of generality, I describe the API for `tensor.view_names`.
`tensor.names_` has an analogous API.
`tensor.view_names(*names)` returns a view on tensor with named dims `names`.
`names` must be of length `tensor.dim()`; otherwise, if '*' is in `names`,
then it (known as the "glob") is expanded greedily to be equal to the
corresponding names from `tensor.names`.
For example,
```
>>> x = torch.empty(2, 3, 5, 7, names=('N', 'C', 'H', 'W'))
>>> x.view_names('*', 'height', 'width').names
('N', 'C', 'height', 'width')
>>> x.view_names('batch', '*', 'width').names
('batch', 'C', 'H', 'width')
```
tensor.view_names(**rename_map) returns a view on tensor that has
renamed dims as specified in the mapping `rename_map`.
For example,
```
>>> x = torch.empty(2, 3, 5, 7, names=('N', 'C', 'H', 'W'))
>>> x.view_names(W='width', H='height').names
('N', 'C', 'height', 'width')
```
These are different(!!!) from the C++ API, which only allows the
following:
- tensor.view_names(optional<DimnameList>)
C++ API parity for named tensors is not important right now; I am
punting that to the future.
Test Plan: - [namedtensor ci]
Differential Revision: D16710916
Pulled By: zou3519
fbshipit-source-id: 7cb8056c0fb4c97b04c3a2d1dd0f737e0a67ce34
2019-08-14 16:31:54 +00:00
|
|
|
|
2019-09-22 22:36:47 +00:00
|
|
|
def rename(self, *names, **rename_map):
|
2019-10-09 05:20:20 +00:00
|
|
|
"""Renames dimension names of :attr:`self`.
|
|
|
|
|
|
|
|
|
|
There are two main usages:
|
|
|
|
|
|
|
|
|
|
``self.rename(**rename_map)`` returns a view on tensor that has dims
|
|
|
|
|
renamed as specified in the mapping :attr:`rename_map`.
|
|
|
|
|
|
|
|
|
|
``self.rename(*names)`` returns a view on tensor, renaming all
|
|
|
|
|
dimensions positionally using :attr:`names`.
|
|
|
|
|
Use ``self.rename(None)`` to drop names on a tensor.
|
|
|
|
|
|
|
|
|
|
One cannot specify both positional args :attr:`names` and keyword args
|
|
|
|
|
:attr:`rename_map`.
|
|
|
|
|
|
|
|
|
|
Examples::
|
|
|
|
|
|
|
|
|
|
>>> imgs = torch.rand(2, 3, 5, 7, names=('N', 'C', 'H', 'W'))
|
|
|
|
|
>>> renamed_imgs = imgs.rename(N='batch', C='channels')
|
|
|
|
|
>>> renamed_imgs.names
|
|
|
|
|
('batch', 'channels', 'H', 'W')
|
|
|
|
|
|
|
|
|
|
>>> renamed_imgs = imgs.rename(None)
|
|
|
|
|
>>> renamed_imgs.names
|
|
|
|
|
(None,)
|
|
|
|
|
|
|
|
|
|
>>> renamed_imgs = imgs.rename('batch', 'channel', 'height', 'width')
|
|
|
|
|
>>> renamed_imgs.names
|
|
|
|
|
('batch', 'channel', 'height', 'width')
|
|
|
|
|
|
|
|
|
|
.. warning::
|
|
|
|
|
The named tensor API is experimental and subject to change.
|
|
|
|
|
|
|
|
|
|
"""
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
2021-08-12 18:39:31 +00:00
|
|
|
return handle_torch_function(Tensor.rename, (self,), self, *names, **rename_map)
|
2020-08-06 03:39:27 +00:00
|
|
|
|
2019-09-22 22:36:47 +00:00
|
|
|
# See Note [rename_ / rename API]
|
2019-09-18 12:44:43 +00:00
|
|
|
return update_names(self, names, rename_map, inplace=False)
|
Update tensor.view_names / tensor.names_ API (#23973)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/23973
Without loss of generality, I describe the API for `tensor.view_names`.
`tensor.names_` has an analogous API.
`tensor.view_names(*names)` returns a view on tensor with named dims `names`.
`names` must be of length `tensor.dim()`; otherwise, if '*' is in `names`,
then it (known as the "glob") is expanded greedily to be equal to the
corresponding names from `tensor.names`.
For example,
```
>>> x = torch.empty(2, 3, 5, 7, names=('N', 'C', 'H', 'W'))
>>> x.view_names('*', 'height', 'width').names
('N', 'C', 'height', 'width')
>>> x.view_names('batch', '*', 'width').names
('batch', 'C', 'H', 'width')
```
tensor.view_names(**rename_map) returns a view on tensor that has
renamed dims as specified in the mapping `rename_map`.
For example,
```
>>> x = torch.empty(2, 3, 5, 7, names=('N', 'C', 'H', 'W'))
>>> x.view_names(W='width', H='height').names
('N', 'C', 'height', 'width')
```
These are different(!!!) from the C++ API, which only allows the
following:
- tensor.view_names(optional<DimnameList>)
C++ API parity for named tensors is not important right now; I am
punting that to the future.
Test Plan: - [namedtensor ci]
Differential Revision: D16710916
Pulled By: zou3519
fbshipit-source-id: 7cb8056c0fb4c97b04c3a2d1dd0f737e0a67ce34
2019-08-14 16:31:54 +00:00
|
|
|
|
2021-11-18 06:23:37 +00:00
|
|
|
def to_sparse_coo(self):
|
|
|
|
|
""" Convert a tensor to :ref:`coordinate format <sparse-coo-docs>`.
|
|
|
|
|
|
|
|
|
|
Examples::
|
|
|
|
|
|
|
|
|
|
>>> dense = torch.randn(5, 5)
|
|
|
|
|
>>> sparse = dense.to_sparse_coo()
|
|
|
|
|
>>> sparse._nnz()
|
|
|
|
|
25
|
|
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
if self.is_sparse:
|
|
|
|
|
return self
|
|
|
|
|
if self.is_sparse_csr:
|
|
|
|
|
crow_indices = self.crow_indices()
|
|
|
|
|
col_indices = self.col_indices()
|
|
|
|
|
indices = torch._convert_indices_from_csr_to_coo(crow_indices, col_indices,
|
|
|
|
|
out_int32=crow_indices.dtype == torch.int32)
|
|
|
|
|
return torch.sparse_coo_tensor(indices,
|
|
|
|
|
self.values(),
|
|
|
|
|
size=self.shape,
|
|
|
|
|
dtype=self.dtype,
|
|
|
|
|
device=self.device)
|
|
|
|
|
else:
|
|
|
|
|
return self.to_sparse()
|
|
|
|
|
|
2021-04-12 17:07:56 +00:00
|
|
|
def to_sparse_csr(self):
|
2021-08-12 18:39:31 +00:00
|
|
|
""" Convert a tensor to compressed row storage format. Only works with 2D tensors.
|
2021-04-12 17:07:56 +00:00
|
|
|
|
|
|
|
|
Examples::
|
|
|
|
|
|
|
|
|
|
>>> dense = torch.randn(5, 5)
|
|
|
|
|
>>> sparse = dense.to_sparse_csr()
|
|
|
|
|
>>> sparse._nnz()
|
|
|
|
|
25
|
|
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
shape = self.size()
|
|
|
|
|
fill_value = 0
|
|
|
|
|
if len(shape) != 2:
|
2021-08-12 18:39:31 +00:00
|
|
|
raise RuntimeError("Only 2D tensors can be converted to the CSR format but got shape: ", shape)
|
2021-04-12 17:07:56 +00:00
|
|
|
|
|
|
|
|
if self.is_sparse:
|
|
|
|
|
coalesced_self = self.coalesce()
|
|
|
|
|
row_indices = coalesced_self.indices()[0]
|
2021-05-26 23:38:44 +00:00
|
|
|
device = coalesced_self.values().device
|
2021-08-11 18:35:53 +00:00
|
|
|
crow_indices = torch._convert_indices_from_coo_to_csr(
|
2021-08-12 18:39:31 +00:00
|
|
|
row_indices, self.shape[0], out_int32=row_indices.dtype == torch.int32)
|
|
|
|
|
return torch.sparse_csr_tensor(crow_indices,
|
|
|
|
|
coalesced_self.indices()[1].contiguous(),
|
|
|
|
|
coalesced_self.values(),
|
|
|
|
|
size=coalesced_self.shape,
|
|
|
|
|
dtype=coalesced_self.dtype,
|
|
|
|
|
device=device)
|
2021-04-12 17:07:56 +00:00
|
|
|
elif self.is_sparse_csr:
|
|
|
|
|
return self
|
|
|
|
|
else:
|
|
|
|
|
return self.to_sparse().to_sparse_csr()
|
|
|
|
|
|
Update tensor.view_names / tensor.names_ API (#23973)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/23973
Without loss of generality, I describe the API for `tensor.view_names`.
`tensor.names_` has an analogous API.
`tensor.view_names(*names)` returns a view on tensor with named dims `names`.
`names` must be of length `tensor.dim()`; otherwise, if '*' is in `names`,
then it (known as the "glob") is expanded greedily to be equal to the
corresponding names from `tensor.names`.
For example,
```
>>> x = torch.empty(2, 3, 5, 7, names=('N', 'C', 'H', 'W'))
>>> x.view_names('*', 'height', 'width').names
('N', 'C', 'height', 'width')
>>> x.view_names('batch', '*', 'width').names
('batch', 'C', 'H', 'width')
```
tensor.view_names(**rename_map) returns a view on tensor that has
renamed dims as specified in the mapping `rename_map`.
For example,
```
>>> x = torch.empty(2, 3, 5, 7, names=('N', 'C', 'H', 'W'))
>>> x.view_names(W='width', H='height').names
('N', 'C', 'height', 'width')
```
These are different(!!!) from the C++ API, which only allows the
following:
- tensor.view_names(optional<DimnameList>)
C++ API parity for named tensors is not important right now; I am
punting that to the future.
Test Plan: - [namedtensor ci]
Differential Revision: D16710916
Pulled By: zou3519
fbshipit-source-id: 7cb8056c0fb4c97b04c3a2d1dd0f737e0a67ce34
2019-08-14 16:31:54 +00:00
|
|
|
def _update_names(self, names, inplace):
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
2021-08-12 18:39:31 +00:00
|
|
|
return handle_torch_function(Tensor._update_names, (self,), self, names, inplace)
|
2020-08-06 03:39:27 +00:00
|
|
|
|
2019-09-22 22:36:47 +00:00
|
|
|
# See Note [rename_ / rename API]
|
Update tensor.view_names / tensor.names_ API (#23973)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/23973
Without loss of generality, I describe the API for `tensor.view_names`.
`tensor.names_` has an analogous API.
`tensor.view_names(*names)` returns a view on tensor with named dims `names`.
`names` must be of length `tensor.dim()`; otherwise, if '*' is in `names`,
then it (known as the "glob") is expanded greedily to be equal to the
corresponding names from `tensor.names`.
For example,
```
>>> x = torch.empty(2, 3, 5, 7, names=('N', 'C', 'H', 'W'))
>>> x.view_names('*', 'height', 'width').names
('N', 'C', 'height', 'width')
>>> x.view_names('batch', '*', 'width').names
('batch', 'C', 'H', 'width')
```
tensor.view_names(**rename_map) returns a view on tensor that has
renamed dims as specified in the mapping `rename_map`.
For example,
```
>>> x = torch.empty(2, 3, 5, 7, names=('N', 'C', 'H', 'W'))
>>> x.view_names(W='width', H='height').names
('N', 'C', 'height', 'width')
```
These are different(!!!) from the C++ API, which only allows the
following:
- tensor.view_names(optional<DimnameList>)
C++ API parity for named tensors is not important right now; I am
punting that to the future.
Test Plan: - [namedtensor ci]
Differential Revision: D16710916
Pulled By: zou3519
fbshipit-source-id: 7cb8056c0fb4c97b04c3a2d1dd0f737e0a67ce34
2019-08-14 16:31:54 +00:00
|
|
|
if inplace:
|
2019-09-22 22:36:47 +00:00
|
|
|
return super(Tensor, self).rename_(names)
|
Update tensor.view_names / tensor.names_ API (#23973)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/23973
Without loss of generality, I describe the API for `tensor.view_names`.
`tensor.names_` has an analogous API.
`tensor.view_names(*names)` returns a view on tensor with named dims `names`.
`names` must be of length `tensor.dim()`; otherwise, if '*' is in `names`,
then it (known as the "glob") is expanded greedily to be equal to the
corresponding names from `tensor.names`.
For example,
```
>>> x = torch.empty(2, 3, 5, 7, names=('N', 'C', 'H', 'W'))
>>> x.view_names('*', 'height', 'width').names
('N', 'C', 'height', 'width')
>>> x.view_names('batch', '*', 'width').names
('batch', 'C', 'H', 'width')
```
tensor.view_names(**rename_map) returns a view on tensor that has
renamed dims as specified in the mapping `rename_map`.
For example,
```
>>> x = torch.empty(2, 3, 5, 7, names=('N', 'C', 'H', 'W'))
>>> x.view_names(W='width', H='height').names
('N', 'C', 'height', 'width')
```
These are different(!!!) from the C++ API, which only allows the
following:
- tensor.view_names(optional<DimnameList>)
C++ API parity for named tensors is not important right now; I am
punting that to the future.
Test Plan: - [namedtensor ci]
Differential Revision: D16710916
Pulled By: zou3519
fbshipit-source-id: 7cb8056c0fb4c97b04c3a2d1dd0f737e0a67ce34
2019-08-14 16:31:54 +00:00
|
|
|
else:
|
2019-09-22 22:36:47 +00:00
|
|
|
return super(Tensor, self).rename(names)
|
Update tensor.view_names / tensor.names_ API (#23973)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/23973
Without loss of generality, I describe the API for `tensor.view_names`.
`tensor.names_` has an analogous API.
`tensor.view_names(*names)` returns a view on tensor with named dims `names`.
`names` must be of length `tensor.dim()`; otherwise, if '*' is in `names`,
then it (known as the "glob") is expanded greedily to be equal to the
corresponding names from `tensor.names`.
For example,
```
>>> x = torch.empty(2, 3, 5, 7, names=('N', 'C', 'H', 'W'))
>>> x.view_names('*', 'height', 'width').names
('N', 'C', 'height', 'width')
>>> x.view_names('batch', '*', 'width').names
('batch', 'C', 'H', 'width')
```
tensor.view_names(**rename_map) returns a view on tensor that has
renamed dims as specified in the mapping `rename_map`.
For example,
```
>>> x = torch.empty(2, 3, 5, 7, names=('N', 'C', 'H', 'W'))
>>> x.view_names(W='width', H='height').names
('N', 'C', 'height', 'width')
```
These are different(!!!) from the C++ API, which only allows the
following:
- tensor.view_names(optional<DimnameList>)
C++ API parity for named tensors is not important right now; I am
punting that to the future.
Test Plan: - [namedtensor ci]
Differential Revision: D16710916
Pulled By: zou3519
fbshipit-source-id: 7cb8056c0fb4c97b04c3a2d1dd0f737e0a67ce34
2019-08-14 16:31:54 +00:00
|
|
|
|
2019-12-11 17:44:34 +00:00
|
|
|
@property
|
|
|
|
|
def grad(self):
|
|
|
|
|
"""
|
|
|
|
|
This attribute is ``None`` by default and becomes a Tensor the first time a call to
|
|
|
|
|
:func:`backward` computes gradients for ``self``.
|
|
|
|
|
The attribute will then contain the gradients computed and future calls to
|
|
|
|
|
:func:`backward` will accumulate (add) gradients into it.
|
|
|
|
|
"""
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
2020-09-24 15:20:06 +00:00
|
|
|
# TODO mypy doesn't support @property, see: https://github.com/python/mypy/issues/6185
|
2021-01-11 03:16:04 +00:00
|
|
|
return handle_torch_function(Tensor.grad.__get__, (self,), self) # type: ignore[attr-defined]
|
2020-08-06 03:39:27 +00:00
|
|
|
|
2019-12-11 17:44:34 +00:00
|
|
|
return self._grad
|
|
|
|
|
|
|
|
|
|
@grad.setter
|
|
|
|
|
def grad(self, new_grad):
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
2020-09-24 15:20:06 +00:00
|
|
|
# TODO mypy doesn't support @property, see: https://github.com/python/mypy/issues/6185
|
2021-01-11 03:16:04 +00:00
|
|
|
return handle_torch_function(Tensor.grad.__set__, (self,), self, new_grad) # type: ignore[attr-defined]
|
2019-12-11 17:44:34 +00:00
|
|
|
self._grad = new_grad
|
|
|
|
|
|
|
|
|
|
@grad.deleter
|
|
|
|
|
def grad(self):
|
2021-01-11 03:16:04 +00:00
|
|
|
if has_torch_function_unary(self):
|
2020-09-24 15:20:06 +00:00
|
|
|
# TODO mypy doesn't support @property, see: https://github.com/python/mypy/issues/6185
|
2021-01-11 03:16:04 +00:00
|
|
|
return handle_torch_function(Tensor.grad.__delete__, (self,), self) # type: ignore[attr-defined]
|
2019-12-11 17:44:34 +00:00
|
|
|
del self._grad
|
|
|
|
|
|
2020-08-06 03:39:27 +00:00
|
|
|
@classmethod
|
|
|
|
|
def __torch_function__(cls, func, types, args=(), kwargs=None):
|
|
|
|
|
"""
|
|
|
|
|
This __torch_function__ implementation wraps subclasses such that
|
|
|
|
|
methods called on subclasses return a subclass instance instead of
|
|
|
|
|
a ``torch.Tensor`` instance.
|
|
|
|
|
|
|
|
|
|
One corollary to this is that you need coverage for torch.Tensor
|
|
|
|
|
methods if implementing __torch_function__ for subclasses.
|
|
|
|
|
|
|
|
|
|
We recommend always calling ``super().__torch_function__`` as the base
|
|
|
|
|
case when doing the above.
|
|
|
|
|
|
|
|
|
|
While not mandatory, we recommend making `__torch_function__` a classmethod.
|
|
|
|
|
"""
|
|
|
|
|
if kwargs is None:
|
|
|
|
|
kwargs = {}
|
|
|
|
|
|
|
|
|
|
if not all(issubclass(cls, t) for t in types):
|
|
|
|
|
return NotImplemented
|
|
|
|
|
|
|
|
|
|
with _C.DisableTorchFunction():
|
|
|
|
|
ret = func(*args, **kwargs)
|
2021-06-22 19:48:07 +00:00
|
|
|
if func in get_default_nowrap_functions():
|
|
|
|
|
return ret
|
|
|
|
|
else:
|
|
|
|
|
return _convert(ret, cls)
|
2020-08-06 03:39:27 +00:00
|
|
|
|
2021-09-13 02:45:57 +00:00
|
|
|
def __dlpack__(self, stream=None):
|
|
|
|
|
"""
|
|
|
|
|
Creates a DLpack `capsule https://data-apis.org/array-api/latest/design_topics/data_interchange.html#data-interchange`_
|
|
|
|
|
of the current tensor to be exported to other libraries.
|
|
|
|
|
|
|
|
|
|
This function will be called from the `from_dlpack` method
|
|
|
|
|
of the library that will consume the capsule. `from_dlpack` passes the current
|
|
|
|
|
stream to this method as part of the specification.
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
stream (integer or None): An optional Python integer representing a
|
|
|
|
|
pointer to a CUDA stream. The current stream is synchronized with
|
|
|
|
|
this stream before the capsule is created, and since the capsule
|
|
|
|
|
shares its storage with the tensor this make it safe to access from
|
|
|
|
|
both streams. If None or -1 is passed then no synchronization is performed.
|
|
|
|
|
"""
|
|
|
|
|
if has_torch_function_unary(self):
|
|
|
|
|
return handle_torch_function(Tensor.__dlpack__, (self,), self, stream)
|
|
|
|
|
|
|
|
|
|
# DLPack capsules can't capture all of PyTorch's semantics,
|
|
|
|
|
# so we prohibit exporting tensors that would lose their properties like
|
|
|
|
|
# requires_grad and having the conjugate bit set.
|
|
|
|
|
if self.requires_grad:
|
|
|
|
|
raise RuntimeError('Can\'t export tensors that require gradient, use tensor.detach()')
|
|
|
|
|
if self.is_conj():
|
|
|
|
|
raise RuntimeError('Can\'t export tensors with the conjugate bit set')
|
|
|
|
|
if self.layout != torch.strided:
|
|
|
|
|
raise RuntimeError('Can\'t export tensors with layout other than torch.strided')
|
|
|
|
|
|
|
|
|
|
if stream is not None and type(stream) is not int:
|
|
|
|
|
# Stream pointers in CUDA/ROCm are uniquely numbered and can
|
|
|
|
|
# be retrieved from their integer value.
|
|
|
|
|
raise TypeError('stream must be ``int`` or ``none``')
|
|
|
|
|
elif stream is not None and stream != -1:
|
|
|
|
|
if self.device.type == 'cuda':
|
|
|
|
|
stream = torch.cuda.streams.ExternalStream(stream)
|
|
|
|
|
# Only synchronize on different streams
|
|
|
|
|
if stream != torch.cuda.current_stream:
|
|
|
|
|
event = torch.cuda.Event()
|
|
|
|
|
event.record(torch.cuda.current_stream())
|
|
|
|
|
stream.wait_event(event)
|
|
|
|
|
return torch.to_dlpack(self)
|
|
|
|
|
|
|
|
|
|
def __dlpack_device__(self) -> Tuple[enum.IntEnum, int]:
|
|
|
|
|
# Avoid circular import
|
|
|
|
|
from torch.utils.dlpack import DLDeviceType
|
|
|
|
|
if has_torch_function_unary(self):
|
|
|
|
|
return handle_torch_function(Tensor.__dlpack_device__, (self,), self)
|
|
|
|
|
idx = self.device.index if self.device.index is not None else 0
|
|
|
|
|
if self.device.type == 'cuda' and torch.version.hip is not None:
|
|
|
|
|
device_type = DLDeviceType.kDLROCM
|
|
|
|
|
elif self.device.type == 'cpu' and self.is_pinned():
|
|
|
|
|
device_type = DLDeviceType.kDLCPUPinned
|
|
|
|
|
elif self.device.type == 'cuda':
|
|
|
|
|
device_type = DLDeviceType.kDLGPU
|
|
|
|
|
elif self.device.type == 'cpu':
|
|
|
|
|
device_type = DLDeviceType.kDLCPU
|
|
|
|
|
else:
|
|
|
|
|
raise ValueError('Unknown device type {} for Dlpack'.format(self.device.type))
|
|
|
|
|
return (device_type, idx)
|
|
|
|
|
|
2021-08-12 18:39:31 +00:00
|
|
|
__module__ = 'torch'
|
2020-08-06 03:39:27 +00:00
|
|
|
|
|
|
|
|
def _convert(ret, cls):
|
|
|
|
|
if cls is Tensor:
|
|
|
|
|
return ret
|
|
|
|
|
|
Dispatch to Python via __torch_dispatch__ (#59760)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/59760
See https://github.com/pytorch/pytorch/issues/59049
There are some moving parts to this PR, I'll structure this explanation so the straightforward parts go first, and then the less straightforward parts.
**The actual dispatch to Python.** The core logic of dispatch to Python lives in `concrete_dispatch_fn` in `torch/csrc/autograd/python_variable.cpp`. It takes the input IValue stack, scans all the arguments for Tensor arguments, and defers most of the heavy lifting to `handle_torch_function_no_python_arg_parser` which actually does all of the logic for calling out to torch dispatch (in particular, this function handles multiple dispatch situations for you). Because we have a different function name than regular `__torch_function__` handling, `handle_torch_function_no_python_arg_parser` is generalized to accept a magic method name to look for when testing if Tensors have custom handling or not. Unlike `__torch_function__`, by default there is no `__torch_dispatch__` on Tensor classes.
**Maintaining the Python dispatch key.** In order to get to the dispatch to Python logic, we must tag Tensors with the `__torch_dispatch__` magic method with the newly added Python dispatch key (separated from PythonFuncTorch to allow for a transitional period while they migrate to this mechanism). We expose a new private property `_is_python_dispatch` that assists in debugging if a Tensor is participating in Python dispatch or not. We apply the Python dispatch key the first time a PyObject for a Tensor is constructed (THPVariable_NewWithVar), testing if `__torch_dispatch__` exists with then newly added `check_has_torch_dispatch`.
**Shallow copy and detach.** For the simple examples tested in this PR, most creations of Tensor route through the dispatcher. The exception to this is `shallow_copy_and_detach`, which bypasses the dispatcher and is used when saving tensors for backwards. When a Tensor is Python dispatch, we override the behavior of `shallow_copy_and_detach` to instead directly call into `__torch_dispatch__` to perform a `detach` operation (in the same way it would be invoked if you called `detach` directly). Because this Python call is triggered directly from c10::TensorImpl, it must be indirected through `PyInterpreter::detach`, which is the general mechanism for dynamic dispatching to the Python interpreter associated with a TensorImpl.
**torchdeploy compatibility.** The dispatch to Python logic cannot be directly registered to the dispatcher as it is compiled in the Python library, which will get loaded multiple times per torchdeploy interpreter. Thus, we must employ a two phase process. First, we register a fallback inside a non-Python library (aten/src/ATen/core/PythonFallbackKernel.cpp). Its job is to determine the appropriate PyInterpreter to handle the Python dispatch by going through all of the arguments and finding the first argument that has a PyObject/PyInterpreter. With this PyInterpreter, it makes another dynamic dispatch via "dispatch" which will go to the correct torchdeploy interpreter to handle dispatching to actual Python.
**Testing.** We provide a simple example of a LoggingTensor for testing, which can be used to generate TorchScript-like traces to observe what operations are being called when a Tensor is invoked. Although a LoggingTensor would be better implemented via an is-a relationship rather than a has-a relationship (as is done in the test), we've done it this way to show that arbitrarily complex compositions of tensors inside a tensor work properly.
**Known limitations.**
* We haven't adjusted any operator code, so some patterns may not work (as they lose the Python subclass in an unrecoverable way)
* `__torch_function__` must be explicitly disabled with `_disabled_torch_function_impl` otherwise things don't work quite correctly (in particular, what is being disabled is default subclass preservation behavior.)
* We don't ever populate kwargs, even when an argument is kwarg-only
Signed-off-by: Edward Z. Yang <ezyang@fb.com>
Differential Revision:
D29017912
D29017912
Test Plan: Imported from OSS
Reviewed By: bdhirsh
Pulled By: ezyang
fbshipit-source-id: a67714d9e541d09203a8cfc85345b8967db86238
2021-06-25 18:49:20 +00:00
|
|
|
if isinstance(ret, Tensor) and not isinstance(ret, cls):
|
2020-08-06 03:39:27 +00:00
|
|
|
ret = ret.as_subclass(cls)
|
|
|
|
|
|
2020-11-11 03:43:48 +00:00
|
|
|
if isinstance(ret, (tuple, list)):
|
|
|
|
|
# Also handles things like namedtuples
|
|
|
|
|
ret = type(ret)(_convert(r, cls) for r in ret)
|
2020-08-06 03:39:27 +00:00
|
|
|
|
|
|
|
|
return ret
|