SparseSemiStructuredTensorCUTLASS
- class torch.sparse.semi_structured.SparseSemiStructuredTensorCUTLASS(shape, packed, meta, packed_t, meta_t, compressed_swizzled_bitmask, fuse_transpose_cusparselt=False, alg_id_cusparselt=0,
This class implements semi-structured sparsity for the CUTLASS backend.
In this implementation, the specified elements and metadata are stored separately, in packed and meta respectively.
When _FORCE_CUTLASS is set, or when cuSPARSELt is not available, this subclass calls into _sparse_semi_structured_(mm|addmm) and sparse_semi_structured_from_dense for conversion to the compressed format.
Returns a view of a matrix (2-D tensor) conjugated and transposed.
x.H is equivalent to x.transpose(0, 1).conj() for complex matrices and
x.transpose(0, 1) for real matrices.
Returns a view of this tensor with its dimensions reversed.
If n is the number of dimensions in x,
x.T is equivalent to x.permute(n-1, n-2, ..., 0).
See torch.abs()
In-place version of abs()
See torch.acos()
In-place version of acos()
See torch.acosh()
In-place version of acosh()
Add a scalar or tensor to self tensor. If both alpha
and other are specified, each element of other is scaled by
alpha before being used.
When is a tensor, the shape of must be
with the shape of the underlying
tensor
In-place version of add()
See torch.addbmm()
In-place version of addbmm()
See torch.addcdiv()
In-place version of addcdiv()
See torch.addcmul()
In-place version of addcmul()
See torch.addmm()
In-place version of addmm()
See torch.addmv()
In-place version of addmv()
See torch.addr()
In-place version of addr()
See torch.all()
See torch.allclose()
See torch.amax()
See torch.amin()
See torch.aminmax()
See torch.angle()
See torch.any()
Applies the function callable to each element in the tensor, replacing
each element with the value returned by callable.
See torch.arccos()
In-place version of arccos()
acosh() -> Tensor
See torch.arccosh()
acosh_() -> Tensor
In-place version of arccosh()
See torch.arcsin()
In-place version of arcsin()
See torch.arcsinh()
In-place version of arcsinh()
See torch.arctan()
See torch.arctan2()
atan2_(other) -> Tensor
In-place version of arctan2()
In-place version of arctan()
See torch.arctanh()
In-place version of arctanh()
See torch.argmax()
See torch.argmin()
See torch.argsort()
See torch.argwhere()
In-place version of as_strided()
Makes a cls instance with the same data pointer as self. Changes
in the output mirror changes in self, and the output stays attached
to the autograd graph. cls must be a subclass of Tensor.
See torch.asin()
In-place version of asin()
See torch.asinh()
In-place version of asinh()
See torch.atan()
See torch.atan2()
In-place version of atan2()
In-place version of atan()
See torch.atanh()
In-place version of atanh()
Computes the gradient of current tensor wrt graph leaves.
The graph is differentiated using the chain rule. If the tensor is
non-scalar (i.e. its data has more than one element) and requires
gradient, the function additionally requires specifying a gradient.
It should be a tensor of matching type and shape, that represents
the gradient of the differentiated function w.r.t. self.
This function accumulates gradients in the leaves - you might need to zero
attributes or set them to before calling it.
See
for details on the memory layout of accumulated gradients.
See torch.baddbmm()
In-place version of baddbmm()
Returns a result tensor where each is independently sampled from . must have floating point , and the result will have the same .
Fills each location of self with an independent sample from
. can have integral
.
self.bfloat16() is equivalent to self.to(torch.bfloat16). See to().
See torch.bincount()
In-place version of bitwise_and()
In-place version of bitwise_left_shift()
In-place version of bitwise_not()
In-place version of bitwise_or()
In-place version of bitwise_right_shift()
In-place version of bitwise_xor()
See torch.bmm()
self.bool() is equivalent to self.to(torch.bool). See to().
See torch.broadcast_to().
self.byte() is equivalent to self.to(torch.uint8). See to().
Fills the tensor with numbers drawn from the Cauchy distribution:
self.cdouble() is equivalent to self.to(torch.complex128). See to().
See torch.ceil()
In-place version of ceil()
self.cfloat() is equivalent to self.to(torch.complex64). See to().
self.chalf() is equivalent to self.to(torch.complex32). See to().
self.char() is equivalent to self.to(torch.int8). See to().
See torch.chunk()
See torch.clamp()
In-place version of clamp()
Alias for clamp().
Alias for clamp_().
See torch.clone()
Returns a coalesced copy of self if self is an
uncoalesced tensor.
Returns self if self is a coalesced tensor.
Returns the tensor containing the column indices of the self
tensor when self is a sparse CSR tensor of layout sparse_csr.
The col_indices tensor is strictly of shape (self.nnz())
and of type int32 or int64. When using MKL routines such as sparse
matrix multiplication, it is necessary to use indexing in order
to avoid downcasting and potentially losing information.
See torch.conj()
In-place version of conj_physical()
Returns the address of the first element of self tensor.
Unlike data_ptr(), this is guaranteed to be a read-only access
that will not trigger copy-on-write materialization. For regular
(non-COW) tensors, the return value is identical to data_ptr().
Returns a contiguous in memory tensor containing the same data as self tensor. If
self tensor is already in the specified memory format, this function returns the
self tensor.
Copies the elements from src into self tensor and returns
self.
The src tensor must be broadcastable
with the tensor. It may be of a different data type or reside on a
different device.
See torch.copysign()
In-place version of copysign()
See torch.corrcoef()
See torch.cos()
In-place version of cos()
See torch.cosh()
In-place version of cosh()
See torch.cov()
Returns a copy of this object in CPU memory.
If this object is already in CPU memory, then no copy is performed and the original object is returned.
memory_format (torch.memory_format, optional) – the desired memory format of
returned Tensor. Default: torch.preserve_format.
See torch.cross()
Returns the tensor containing the compressed row indices of the self
tensor when self is a sparse CSR tensor of layout sparse_csr.
The crow_indices tensor is strictly of shape (self.size(0) + 1)
and of type int32 or int64. When using MKL routines such as sparse
matrix multiplication, it is necessary to use indexing in order
to avoid downcasting and potentially losing information.
Returns a copy of this object in CUDA memory.
If this object is already in CUDA memory and on the correct device, then no copy is performed and the original object is returned.
See torch.cummax()
See torch.cummin()
See torch.cumprod()
In-place version of cumprod()
See torch.cumsum()
In-place version of cumsum()
Returns the address of the first element of self tensor.
See torch.deg2rad()
In-place version of deg2rad()
Return the number of dense dimensions in a sparse tensor self.
See also Tensor.sparse_dim() and .
Given a quantized Tensor, dequantize it and return the dequantized float Tensor.
See torch.det()
Returns a new Tensor, detached from the current graph.
The result will never require gradient.
This method also affects forward mode AD gradients and the result will never have forward mode AD gradients.
Detaches the Tensor from the graph that created it, making it a leaf. Views cannot be detached in-place.
This method also affects forward mode AD gradients and the result will never have forward mode AD gradients.
Is the torch.device where this Tensor is.
See torch.diag()
See torch.diagflat()
See torch.diagonal()
See torch.diff()
See torch.digamma()
In-place version of digamma()
Returns the number of dimensions of self tensor.
Returns the uniquely determined tuple of int describing the dim order or
physical layout of self.
The dim order represents how dimensions are laid out in memory of dense tensors, starting from the outermost to the innermost dimension.
Note that the dim order may not always be uniquely determined. If ambiguity_check is True, this function raises a RuntimeError when the dim order cannot be uniquely determined; If ambiguity_check is a list of memory formats, this function raises a RuntimeError when tensor can not be interpreted into exactly one of the given memory formats, or it cannot be uniquely determined. If ambiguity_check is False, it will return one of legal dim order(s) without checking its uniqueness. Otherwise, it will raise TypeError.
See torch.dist()
See torch.div()
In-place version of div()
See torch.divide()
In-place version of divide()
See torch.dot()
self.double() is equivalent to self.to(torch.float64). See to().
See torch.dsplit()
Returns the size in bytes of an individual element.
Example:
>>> torch.tensor([]).element_size()
4
>>> torch.tensor([], dtype=torch
See torch.eq()
In-place version of eq()
See torch.equal()
See torch.erf()
In-place version of erf()
See torch.erfc()
In-place version of erfc()
See torch.erfinv()
In-place version of erfinv()
See torch.exp()
See torch.exp2()
In-place version of exp2()
In-place version of exp()
Returns a new view of the self tensor with singleton dimensions expanded
to a larger size.
Passing -1 as the size for a dimension means not changing the size of that dimension.
Tensor can be also expanded to a larger number of dimensions, and the new ones will be appended at the front. For the new dimensions, the size cannot be set to -1.
Expanding a tensor does not allocate new memory, but only creates a
new view on the existing tensor where a dimension of size one is
expanded to a larger size by setting the stride to 0. Any dimension
of size 1 can be expanded to an arbitrary value without allocating new
memory.
Expand this tensor to the same size as other.
self.expand_as(other) is equivalent to self.expand(other.size()).
Please see expand() for more information about expand.
See torch.expm1()
In-place version of expm1()
Fills self tensor with elements drawn from the PDF (probability density function):
Fills self tensor with the specified value.
Fill the main diagonal of a tensor that has at least 2-dimensions. When dims>2, all dimensions of input must be of equal length. This function modifies the input tensor in-place, and returns the input tensor.
fill_value (Scalar) – the fill value
wrap (bool, optional) – the diagonal ‘wrapped’ after N columns for tall matrices. Default:
See torch.fix().
In-place version of fix()
See torch.flatten()
See torch.flip()
See torch.fliplr()
See torch.flipud()
self.float() is equivalent to self.to(torch.float32). See to().
In-place version of float_power()
See torch.floor()
In-place version of floor()
In-place version of floor_divide()
See torch.fmax()
See torch.fmin()
See torch.fmod()
In-place version of fmod()
See torch.frac()
In-place version of frac()
See torch.frexp()
See torch.gather()
See torch.gcd()
In-place version of gcd()
See torch.ge().
In-place version of ge().
Fills self tensor with elements drawn from the geometric distribution:
See torch.geqrf()
See torch.ger()
For CUDA tensors, this function returns the device ordinal of the GPU on which the tensor resides. For CPU tensors, this function returns -1.
Example:
>>> x = torch.randn(3, 4, 5, device='cuda:0')
>>>
This attribute is None by default and becomes a Tensor the first time a call to
backward() computes gradients for self.
The attribute will then contain the gradients computed and future calls to
backward() will accumulate (add) gradients into it.
The allowed dtype of :attr:grad for this tensor.
:attr:grad_dtype can be set to a specific dtype or None. By default,
t.grad_dtype == t.dtype. When not None, the autograd engine casts
incoming gradients to this dtype. This attribute is only accessible and
settable for leaf tensors.
Example:
See torch.greater().
In-place version of greater().
In-place version of greater_equal().
See torch.gt().
In-place version of gt().
self.half() is equivalent to self.to(torch.float16). See to().
In-place version of heaviside()
See torch.histc()
See torch.hsplit()
See torch.hypot()
In-place version of hypot()
See torch.i0()
In-place version of i0()
See torch.igamma()
In-place version of igamma()
See torch.igammac()
In-place version of igammac()
Returns a new tensor containing imaginary values of the self tensor.
The returned tensor and self share the same underlying storage.
Example:
>>> x=torch
Index a regular tensor by binding specified positions to dims.
This converts a regular tensor to a first-class tensor by binding the specified positional dimensions to Dim objects.
positions – Tuple of dimension positions to bind
dims – Dim objects or tuple of Dim objects to bind to
First-class tensor with specified dimensions bound
Out-of-place version of torch.Tensor.index_add_().
Accumulate the elements of alpha times source into the self
tensor by adding to the indices in the order given in . For example,
if , , and , then the th row of
is subtracted from the th row of .
Out-of-place version of torch.Tensor.index_copy_().
Copies the elements of tensor into the self tensor by selecting
the indices in the order given in index. For example, if dim == 0
and , then the th row of is copied to the
th row of .
Out-of-place version of torch.Tensor.index_fill_().
Fills the elements of the self tensor with value value by
selecting the indices in the order given in index.
Out-place version of index_put_().
Puts values from the tensor values into the tensor self using
the indices specified in indices (which is a tuple of Tensors). The
expression is equivalent to
. Returns .
Accumulate the elements of source into the self
tensor by accumulating to the indices in the order given in
using the reduction given by the argument. For example, if ,
, and then the th
row of is multiplied by the th row of . If
, the values in the tensor are included
in the reduction, otherwise, rows in the tensor that are accumulated
to are treated as if they were filled with the reduction identities.
Return the indices tensor of a sparse COO tensor.
See also Tensor.values().
See torch.inner().
self.int() is equivalent to self.to(torch.int32). See to().
Given a quantized Tensor,
self.int_repr() returns a CPU Tensor with uint8_t as data type that stores the
underlying uint8_t values of the given Tensor.
See torch.inverse()
Returns a copy of this object in IPU memory.
If this object is already in IPU memory and on the correct device, then no copy is performed and the original object is returned.
Returns True if self is a sparse COO tensor that is coalesced, False otherwise.
See and .
Returns True if the data type of self is a complex data type.
Returns True if the conjugate bit of self is set to true.
Returns True if self tensor is contiguous in memory in the order specified
by memory format.
memory_format (torch.memory_format, optional) – Specifies memory allocation
order. Default: .
Is True if the Tensor is stored on the CPU, False otherwise.
Is True if the Tensor is stored on the GPU, False otherwise.
Returns True if the data type of self is a floating point data type.
Is True if the Tensor is stored on the IPU, False otherwise.
All Tensors that have requires_grad which is False will be leaf Tensors by convention.
For Tensors that have requires_grad which is True, they will be leaf Tensors if they were
created by the user. This means that they are not the result of an operation and so
grad_fn is None.
Only leaf Tensors will have their populated during a call to .
To get populated for non-leaf Tensors, you can use .
Is True if the Tensor is a meta tensor, False otherwise. Meta tensors
are like normal tensors, but they carry no data.
Is True if the Tensor is stored on the MPS device, False otherwise.
Returns True if the negative bit of self is set to true.
Returns true if this tensor resides in pinned memory. By default, the device pinned memory on will be the current accelerator.
Is True if the Tensor is quantized, False otherwise.
Returns True if both tensors are pointing to the exact same memory (same storage, offset, size and stride).
Checks if tensor is in shared memory.
This is always True for CUDA tensors.
Returns True if the data type of self is a signed data type.
Is True if the Tensor uses sparse COO storage layout, False otherwise.
Is True if the Tensor uses sparse CSR storage layout, False otherwise.
Is True if the Tensor is stored on an XLA device, False otherwise.
Is True if the Tensor is stored on the XPU, False otherwise.
See torch.isclose()
See torch.isfinite()
See torch.isinf()
See torch.isnan()
See torch.isneginf()
See torch.isposinf()
See torch.isreal()
Returns the value of this tensor as a standard Python number. This only works
for tensors with one element. For other cases, see tolist().
This operation is not differentiable.
Example:
>>> x = torch.tensor([1.0])
>>> x.item()
1.0
Alias for element_size()
See torch.kron()
See torch.kthvalue()
See torch.lcm()
In-place version of lcm()
See torch.ldexp()
In-place version of ldexp()
See torch.le().
In-place version of le().
See torch.lerp()
In-place version of lerp()
lt(other) -> Tensor
See torch.less().
In-place version of less().
See torch.less_equal().
In-place version of less_equal().
See torch.lgamma()
In-place version of lgamma()
See torch.log()
See torch.log10()
In-place version of log10()
See torch.log1p()
In-place version of log1p()
See torch.log2()
In-place version of log2()
In-place version of log()
Fills self tensor with numbers samples from the log-normal distribution
parameterized by the given mean and standard deviation
. Note that and are the mean and
standard deviation of the underlying normal distribution, and not of the
returned distribution:
See torch.logdet()
In-place version of logical_and()
In-place version of logical_not()
In-place version of logical_or()
In-place version of logical_xor()
See torch.logit()
In-place version of logit()
self.long() is equivalent to self.to(torch.int64). See to().
See torch.lt().
In-place version of lt().
See torch.lu()
See torch.lu_solve()
Accessing this property is equivalent to calling adjoint().
Returns a view of this tensor with the last two dimensions transposed.
x.mT is equivalent to x.transpose(-2, -1).
Applies callable for each element in self tensor and the given
tensor and stores the results in self tensor. self tensor and
the given tensor must be broadcastable.
The callable should have the signature:
Out-of-place version of torch.Tensor.masked_fill_()
Fills elements of self tensor with value where mask is
True. The shape of mask must be
broadcastable with the shape of the underlying
tensor.
mask (BoolTensor) – the boolean mask
Out-of-place version of torch.Tensor.masked_scatter_()
Copies elements from source into self tensor at positions where
the mask is True. Elements from source are copied into self
starting at position 0 of source and continuing in order one-by-one for each
occurrence of mask being True.
The shape of must be
with the shape of the underlying tensor. The should have at least
as many elements as the number of ones in .
See torch.matmul()
See torch.max()
See torch.maximum()
See torch.mean()
See torch.median()
See torch.min()
See torch.minimum()
See torch.mm()
See torch.mode()
Defines how to transform other when loading it into self in load_state_dict().
Used when get_swap_module_params_on_conversion() is True.
It is expected that is a parameter or buffer in an and is the
value in the state dictionary with the corresponding key, this method defines
how is remapped before being swapped with via
in .
See torch.moveaxis()
See torch.movedim()
See torch.msort()
Returns a copy of this object in MTIA memory.
If this object is already in MTIA memory and on the correct device, then no copy is performed and the original object is returned.
See torch.mul().
In-place version of mul().
See torch.multiply().
In-place version of multiply().
See torch.mv()
See torch.mvlgamma()
In-place version of mvlgamma()
See torch.nan_to_num().
In-place version of nan_to_num().
See torch.nanmean()
See torch.nansum()
See torch.narrow().
See torch.narrow_copy().
Returns the number of bytes consumed by the “view” of elements of the Tensor
if the Tensor does not use sparse storage layout.
Defined to be numel() * element_size()
Alias for dim()
Alias for dim()
See torch.ne().
In-place version of ne().
See torch.neg()
In-place version of neg()
See torch.negative()
In-place version of negative()
Alias for numel()
Returns a Tensor of size filled with uninitialized data. By default, the returned Tensor has the same and as this tensor.
Returns a Tensor of size and strides filled with uninitialized data. By default, the returned Tensor has the same and as this tensor.
Returns a Tensor of size filled with . By default, the returned Tensor has the same and as this tensor.
Returns a new Tensor with as the tensor data. By default, the returned Tensor has the same and as this tensor.
Returns a Tensor of size filled with . By default, the returned Tensor has the same and as this tensor.
In-place version of nextafter()
See torch.nonzero()
Fills self tensor with elements samples from the normal distribution
parameterized by mean and .
See torch.not_equal().
In-place version of not_equal().
See torch.numel()
Returns the tensor as a NumPy ndarray.
If force is False (the default), the conversion
is performed only if the tensor is on the CPU, does not require grad,
does not have its conjugate bit set, and is a dtype and layout that
NumPy supports. The returned ndarray and the tensor will share their
storage, so changes to the tensor will be reflected in the ndarray
and vice versa.
If force is this is equivalent to
calling .
If the tensor isn’t on the CPU or the conjugate or negative bit is set,
the tensor won’t share its storage with the returned ndarray.
Setting to can be a useful shorthand.
See torch.orgqr()
See torch.ormqr()
See torch.outer().
Returns a view of the tensor with its dimensions permuted.
dims (torch.Size, int..., tuple of ) – the desired ordering of dimensions.
Copies the tensor to pinned memory, if it’s not already pinned. By default, the device pinned memory on will be the current accelerator.
See torch.pinverse()
In-place version of polygamma()
See torch.positive()
See torch.pow()
In-place version of pow()
See torch.prod()
This function takes in a unpruned dense tensor and runs a (branchless) static sort across a 4x4 tile.
It greedily picks the largest values in the tile, upholding the 2:4 sparsity constraint across both rows and columns. The algorithm used to prune the matrix is implemented in _sparse_semi_structured_tile.
Then it creates the packed and meta tensors for the compressed sparse representation of the pruned dense tensor. It also calculates the packed_t and meta_t tensors for the compressed sparse representation of the transposed pruned dense tensor. Since we cannot transpose the compressed representations, we store both for the fw/bw pass respectively.
Finally, this function also computes a compressed swizzled bitmask that encodes the sparsity pattern. This can be used in the backward pass to mask the gradients.
[9 1 7
Out-of-place version of torch.Tensor.put_().
input corresponds to self in torch.Tensor.put_().
Copies the elements from source into the positions specified by
index. For the purpose of indexing, the self tensor is treated as if
it were a 1-D tensor.
and need to have the same number of elements, but not necessarily the same shape.
Given a Tensor quantized by linear (affine) per-channel quantization, returns the index of dimension on which per-channel quantization is applied.
Given a Tensor quantized by linear (affine) per-channel quantization, returns a Tensor of scales of the underlying quantizer. It has the number of elements that matches the corresponding dimensions (from q_per_channel_axis) of the tensor.
Given a Tensor quantized by linear (affine) per-channel quantization, returns a tensor of zero_points of the underlying quantizer. It has the number of elements that matches the corresponding dimensions (from q_per_channel_axis) of the tensor.
Given a Tensor quantized by linear(affine) quantization, returns the scale of the underlying quantizer().
Given a Tensor quantized by linear(affine) quantization, returns the zero_point of the underlying quantizer().
Returns the quantization scheme of a given QTensor.
See torch.quantile()
See torch.rad2deg()
In-place version of rad2deg()
Fills self tensor with numbers sampled from the discrete uniform
distribution over [from, to - 1]. If not specified, the values are usually
only bounded by self tensor’s data type. However, for floating point
types, if unspecified, range will be [0, 2^mantissa] to ensure that every
value is representable. For example,
will be uniform in .
see torch.ravel()
Returns a new tensor containing real values of the self tensor for a complex-valued input tensor.
The returned tensor and self share the same underlying storage.
Returns self if self is a real-valued tensor.
Example:
>>> x=torch.randn(4, dtype=
In-place version of reciprocal()
Marks the tensor as having been used by this stream. When the tensor
is deallocated, ensure the tensor memory is not reused for another tensor
until all work queued on stream at the time of deallocation is
complete.
Registers a backward hook.
The hook will be called every time a gradient with respect to the Tensor is computed. The hook should have the following signature:
hook(grad) -> Tensor or None
The hook should not modify its argument, but it can optionally return
a new gradient which will be used in place of grad.
This function returns a handle with a method
that removes the hook from the module.
Registers a backward hook that runs after grad accumulation.
The hook will be called after all gradients for a tensor have been accumulated, meaning that the .grad field has been updated on that tensor. The post accumulate grad hook is ONLY applicable for leaf tensors (tensors without a .grad_fn field). Registering this hook on a non-leaf tensor will error!
The hook should have the following signature:
hook(param: Tensor) -> None
Note that, unlike other autograd hooks, this hook operates on the tensor that requires grad and not the grad itself. The hook can in-place modify and access its Tensor argument, including its .grad field.
This function returns a handle with a method
that removes the hook from the module.
In-place version of remainder()
See torch.renorm()
In-place version of renorm()
Repeats this tensor along the specified dimensions.
Unlike expand(), this function copies the tensor’s data.
Is True if gradients need to be computed for this Tensor, False otherwise.
Change if autograd should record operations on this tensor: sets this tensor’s
requires_grad attribute in-place. Returns this tensor.
requires_grad_()’s main use case is to tell autograd to begin recording
operations on a Tensor tensor. If has
(because it was obtained through a DataLoader, or required preprocessing or
initialization), makes it so that autograd will
begin to record operations on .
Returns a tensor with the same data and number of elements as self
but with the specified shape. This method returns a view if shape is
compatible with the current shape. See torch.Tensor.view() on when it is
possible to return a view.
Returns this tensor as the same shape as other.
self.reshape_as(other) is equivalent to self.reshape(other.sizes()).
This method returns a view if other.sizes() is compatible with the current
shape. See torch.Tensor.view() on when it is possible to return a view.
Resizes self tensor to the specified size. If the number of elements is
larger than the current storage size, then the underlying storage is resized
to fit the new number of elements. If the number of elements is smaller, the
underlying storage is not changed. Existing elements are preserved but any new
memory is uninitialized.
Resizes the self tensor to be the same size as the specified
tensor. This is equivalent to self.resize_(tensor.size()).
Enables this Tensor to have their grad populated during
backward(). This is a no-op for leaf tensors.
Is True if this Tensor is non-leaf and its grad is enabled to be
populated during backward(), False otherwise.
See torch.roll()
See torch.rot90()
See torch.round()
In-place version of round()
See torch.rsqrt()
In-place version of rsqrt()
Out-of-place version of torch.Tensor.scatter_()
Writes all values from the tensor src into self at the indices
specified in the index tensor. For each value in , its output
index is specified by its index in for and by
the corresponding value in for .
Out-of-place version of torch.Tensor.scatter_add_()
Adds all values from the tensor src into self at the indices
specified in the index tensor in a similar fashion as
scatter_(). For each value in , it is added to
an index in which is specified by its index in
for and by the corresponding value in for
.
Out-of-place version of torch.Tensor.scatter_reduce_()
Reduces all values from the src tensor to the indices specified in
the index tensor in the tensor using the applied reduction
defined via the argument (, , ,
, ). For each value in , it is reduced to an
index in which is specified by its index in for
and by the corresponding value in for
. If , the values in the
tensor are included in the reduction.
See torch.select()
Sets the underlying storage, size, and strides. If source is a tensor,
self tensor will share the same storage and have the same size and
strides as . Changes to elements in one tensor will be reflected
in the other.
See torch.sgn()
In-place version of sgn()
Returns the size of the self tensor. Alias for size.
See also Tensor.size().
Example:
>>> t = torch.empty(3, 4, 5
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.
See torch.UntypedStorage.share_memory_() for more details.
self.short() is equivalent to self.to(torch.int16). See to().
See torch.sigmoid()
In-place version of sigmoid()
See torch.sign()
In-place version of sign()
See torch.signbit()
See torch.sin()
In-place version of sin()
See torch.sinc()
In-place version of sinc()
See torch.sinh()
In-place version of sinh()
Returns the size of the self tensor. If dim is not specified,
the returned value is a torch.Size, a subclass of tuple.
If dim is specified, returns an int holding the size of that dimension.
See torch.slogdet()
See torch.smm()
Alias for torch.nn.functional.softmax().
See torch.sort()
Return the number of sparse dimensions in a sparse tensor self.
See also Tensor.dense_dim() and .
Returns a new sparse tensor with values from a
strided tensor self filtered by the indices of the sparse
tensor mask. The values of mask sparse tensor are
ignored. self and mask tensors must have the same
shape.
Resizes self sparse tensor to the desired
size and the number of sparse and dense dimensions.
Removes all specified elements from a sparse tensor self and resizes self to the desired
size and the number of sparse and dense dimensions.
See torch.split()
See torch.sqrt()
In-place version of sqrt()
See torch.square()
In-place version of square()
See torch.squeeze()
In-place version of squeeze()
See torch.sspaddmm()
See torch.std()
Returns the underlying TypedStorage.
Returns self tensor’s offset in the underlying storage in terms of
number of storage elements (not bytes).
Example:
>>> x = torch.tensor([1, 2, 3, 4
Returns the type of the underlying storage.
Returns the stride of self tensor.
Stride is the jump necessary to go from one element to the next one in the
specified dimension dim. A tuple of all strides is returned when no
argument is passed in. Otherwise, an integer value is returned as the stride in
the particular dimension dim.
See torch.sub().
In-place version of sub()
See torch.subtract().
In-place version of subtract().
See torch.sum()
Sum this tensor to size.
size must be broadcastable to this tensor size.
See torch.svd()
See torch.swapaxes()
In-place version of swapaxes()
See torch.swapdims()
In-place version of swapdims()
In-place version of t()
See torch.take()
See torch.tan()
In-place version of tan()
See torch.tanh()
In-place version of tanh()
See torch.tile()
Performs Tensor dtype and/or device conversion. A torch.dtype and torch.device are
inferred from the arguments of self.to(*args, **kwargs).
Returns a copy of the tensor in torch.mkldnn layout.
Returns a sparse copy of the tensor. PyTorch supports sparse tensors in coordinate format.
sparseDims (int, optional) – the number of sparse dimensions to include in the new sparse tensor
Example:
Convert a tensor to a block sparse column (BSC) storage format of
given blocksize. If the self is strided, then the number of
dense dimensions could be specified, and a hybrid BSC tensor will be
created, with dense_dim dense dimensions and self.dim() - 2 -
dense_dim batch dimension.
Convert a tensor to a block sparse row (BSR) storage format of given
blocksize. If the self is strided, then the number of dense
dimensions could be specified, and a hybrid BSR tensor will be
created, with dense_dim dense dimensions and self.dim() - 2 -
dense_dim batch dimension.
Convert a tensor to coordinate format.
Examples:
>>> dense = torch.randn(5, 5)
>>> sparse = dense.to_sparse_coo()
>>>
Convert a tensor to compressed column storage (CSC) format. Except
for strided tensors, only works with 2D tensors. If the self
is strided, then the number of dense dimensions could be specified,
and a hybrid CSC tensor will be created, with dense_dim dense
dimensions and self.dim() - 2 - dense_dim batch dimension.
dense_dim (int, optional) – Number of dense dimensions of the
resulting CSC tensor. This argument should be used only if
self is a strided tensor, and must be a value between 0
and dimension of tensor minus two.
Convert a tensor to compressed row storage format (CSR). Except for
strided tensors, only works with 2D tensors. If the self is
strided, then the number of dense dimensions could be specified, and a
hybrid CSR tensor will be created, with dense_dim dense dimensions
and self.dim() - 2 - dense_dim batch dimension.
dense_dim (int, optional) – Number of dense dimensions of the resulting CSR tensor. This argument should be used only if is a strided tensor, and must be a value between 0 and dimension of tensor minus two.
Returns the tensor as a (nested) list. For scalars, a standard
Python number is returned, just like with item().
Tensors are automatically moved to the CPU first if necessary.
This operation is not differentiable.
Examples:
>>> a = torch.randn(2, 2)
>>> a
See torch.topk()
See torch.trace()
In-place version of transpose()
See torch.tril()
In-place version of tril()
See torch.triu()
In-place version of triu()
In-place version of true_divide_()
See torch.trunc()
In-place version of trunc()
Returns the type if dtype is not provided, else casts this object to the specified type.
If this is already of the correct type, no copy is performed and the original object is returned.
Returns this tensor cast to the type of the given tensor.
This is a no-op if the tensor is already of the correct type. This is
equivalent to self.type(tensor.type())
tensor (Tensor) – the tensor which has the desired type
See torch.unbind()
See torch.unflatten().
Returns a view of the original tensor which contains all slices of size size from
self tensor in the dimension dimension.
Step between two slices is given by step.
If sizedim is the size of dimension for , the size of dimension in the returned tensor will be .
Fills self tensor with numbers sampled from the continuous uniform
distribution:
Returns the unique elements of the input tensor.
See torch.unique()
Eliminates all but the first element from every consecutive group of equivalent elements.
See torch.unsafe_chunk()
See torch.unsafe_split()
In-place version of unsqueeze()
Returns the underlying UntypedStorage.
Return the values tensor of a sparse COO tensor.
See also Tensor.indices().
See torch.var()
See torch.vdot()
Returns a new tensor with the same data as the self tensor but of a
different shape.
The returned tensor shares the same data and must have the same number of elements, but may have a different size. For a tensor to be viewed, the new view size must be compatible with its original size and stride, i.e., each new view dimension must either be a subspace of an original dimension, or only span across original dimensions that satisfy the following contiguity-like condition that ,
View this tensor as the same size as other.
self.view_as(other) is equivalent to self.view(other.size()).
Please see view() for more information about view.
See torch.vsplit()
self.where(condition, y) is equivalent to torch.where(condition, self, y).
See torch.where()
See torch.xlogy()
In-place version of xlogy()
Returns a copy of this object in XPU memory.
If this object is already in XPU memory and on the correct device, then no copy is performed and the original object is returned.
Fills self tensor with zeros.
mTotherSee torch.add()
Nonegradient (Tensor, optional) – The gradient of the function
being differentiated w.r.t. self.
This argument can be omitted if self is a scalar. Defaults to None.
retain_graph (bool, optional) – If False, the graph used to compute the grads will be freed;
If True, it will be retained. The default is None, in which case the value is inferred from create_graph
(i.e., the graph is retained only when higher-order derivative tracking is requested). 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.
create_graph (bool, optional) – If True, graph of the derivative will
be constructed, allowing to compute higher order derivative
products. Defaults to False.
inputs (Sequence[Tensor] or dict[str, Tensor], optional) – 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 used to compute the tensors. A dict of tensors
(e.g. dict(model.named_parameters())) is also accepted.
Defaults to None.
selfdtypedtypedtypep should either be a scalar or tensor containing probabilities to be
used for drawing the binary random number.
If it is a tensor, the element of self tensor
will be set to a value sampled from
. In this case p must have
floating point dtype.
See also bernoulli() and torch.bernoulli()
torch.memory_formattorch.preserve_formattorch.memory_formattorch.preserve_formattorch.memory_formattorch.preserve_formattorch.memory_formattorch.preserve_formattorch.memory_formattorch.preserve_formattorch.memory_formattorch.preserve_formattorch.memory_formattorch.preserve_formatselfExample:
>>> csr = torch.eye(5,5).to_sparse_csr()
>>> csr.col_indices()
tensor([0, 1, 2, 3, 4], dtype=torch.int32)
The returned pointer must not be used to mutate the tensor data.
Use data_ptr() when write access is needed.
torch.memory_formattorch.contiguous_formatExample:
>>> csr = torch.eye(5,5).to_sparse_csr()
>>> csr.crow_indices()
tensor([0, 1, 2, 3, 4, 5], dtype=torch.int32)
torch.devicenon_blocking (bool, optional) – If True and the source is in pinned memory,
the copy will be asynchronous with respect to the host.
Otherwise, the argument has no effect. Default: False.
memory_format (torch.memory_format, optional) – the desired memory format of
returned Tensor. Default: torch.preserve_format.
ambiguity_check (bool or List[torch.memory_format]) – The check method for ambiguity of dim order.
Examples:
>>> torch.empty((2, 3, 5, 7)).dim_order()
(0, 1, 2, 3)
>>> torch.empty((2, 3, 5, 7)).transpose(1, 2).dim_order()
(0, 2, 1, 3)
>>> torch.empty((2, 3, 5, 7), memory_format=torch.channels_last).dim_order()
(0, 2, 3, 1)
>>> torch.empty((1, 2, 3, 4)).dim_order()
(0, 1, 2, 3)
>>> try:
... torch.empty((1, 2, 3, 4)).dim_order(ambiguity_check=True)
... except RuntimeError as e:
... print(e)
The tensor does not have unique dim order, or cannot map to exact one of the given memory formats.
>>> torch.empty((1, 2, 3, 4)).dim_order(
... ambiguity_check=[torch.contiguous_format, torch.channels_last]
... ) # It can be mapped to contiguous format
(0, 1, 2, 3)
>>> try:
... torch.empty((1, 2, 3, 4)).dim_order(ambiguity_check="ILLEGAL") # type: ignore[arg-type]
... except TypeError as e:
... print(e)
The ambiguity_check argument must be a bool or a list of memory formats.
torch.memory_formattorch.preserve_formatOperations on an expanded view may still allocate memory if they need to
materialize the expanded values. For example, changing dtype after
expand() can allocate memory for the full expanded shape.
*size (torch.Size or int...) – the desired expanded size
Example:
>>> x = torch.tensor([[1], [2], [3]])
>>> x.size()
torch.Size([3, 1])
>>> x.expand(3, 4)
tensor([[ 1, 1, 1, 1],
[ 2, 2, 2, 2],
[ 3, 3, 3, 3]])
>>> x.expand(-1, 4) # -1 means not changing the size of that dimension
tensor([[ 1, 1, 1, 1],
[ 2, 2, 2, 2],
[ 3, 3, 3, 3]])
other (torch.Tensor) – The result tensor has the same size
as other.
FalseExample:
>>> a = torch.zeros(3, 3)
>>> a.fill_diagonal_(5)
tensor([[5., 0., 0.],
[0., 5., 0.],
[0., 0., 5.]])
>>> b = torch.zeros(7, 3)
>>> b.fill_diagonal_(5)
tensor([[5., 0., 0.],
[0., 5., 0.],
[0., 0., 5.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
>>> c = torch.zeros(7, 3)
>>> c.fill_diagonal_(5, wrap=True)
tensor([[5., 0., 0.],
[0., 5., 0.],
[0., 0., 5.],
[0., 0., 0.],
[5., 0., 0.],
[0., 5., 0.],
[0., 0., 5.]])
torch.memory_formattorch.preserve_formattorch.memory_formattorch.preserve_formatdim == 0index[i] == jalpha=-1isourcejselfThe dimth dimension of source must have the same size as the
length of index (which must be a vector), and all other dimensions must
match self, or an error will be raised.
For a 3-D tensor the output is given as:
self[index[i], :, :] += alpha * src[i, :, :] # if dim == 0
self[:, index[i], :] += alpha * src[:, i, :] # if dim == 1
self[:, :, index[i]] += alpha * src[:, :, i] # if dim == 2
Example:
>>> x = torch.ones(5, 3)
>>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float)
>>> index = torch.tensor([0, 4, 2])
>>> x.index_add_(0, index, t)
tensor([[ 2., 3., 4.],
[ 1., 1., 1.],
[ 8., 9., 10.],
[ 1., 1., 1.],
[ 5., 6., 7.]])
>>> x.index_add_(0, index, t, alpha=-1)
tensor([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
itensorjselfThe dimth dimension of tensor must have the same size as the
length of index (which must be a vector), and all other dimensions must
match self, or an error will be raised.
Example:
>>> x = torch.zeros(5, 3)
>>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float)
>>> index = torch.tensor([0, 4, 2])
>>> x.index_copy_(0, index, t)
tensor([[ 1., 2., 3.],
[ 0., 0., 0.],
[ 7., 8., 9.],
[ 0., 0., 0.],
[ 4., 5., 6.]])
dim (int) – dimension along which to index
index (LongTensor) – indices of self tensor to fill in
value (float) – the value to fill with
Example:
>>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float)
>>> index = torch.tensor([0, 2])
>>> x.index_fill_(1, index, -1)
tensor([[-1., 2., -1.],
[-1., 5., -1.],
[-1., 8., -1.]])
tensor.index_put_(indices, values)tensor[indices] = valuesselfIf accumulate is True, the elements in values are added to
self. If accumulate is False, the behavior is undefined if indices
contain duplicate elements.
reducedim == 0index[i] == jreduce == prodinclude_self == Trueisourcejselfinclude_self="True"selfselfThe dimth dimension of source must have the same size as the
length of index (which must be a vector), and all other dimensions must
match self, or an error will be raised.
For a 3-D tensor with reduce="prod" and include_self=True the
output is given as:
self[index[i], :, :] *= src[i, :, :] # if dim == 0
self[:, index[i], :] *= src[:, i, :] # if dim == 1
self[:, :, index[i]] *= src[:, :, i] # if dim == 2
include_self (bool) – whether the elements from the self tensor are
included in the reduction
Example:
>>> x = torch.empty(5, 3).fill_(2)
>>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], dtype=torch.float)
>>> index = torch.tensor([0, 4, 2, 0])
>>> x.index_reduce_(0, index, t, 'prod')
tensor([[20., 44., 72.],
[ 2., 2., 2.],
[14., 16., 18.],
[ 2., 2., 2.],
[ 8., 10., 12.]])
>>> x = torch.empty(5, 3).fill_(2)
>>> x.index_reduce_(0, index, t, 'prod', include_self=False)
tensor([[10., 22., 36.],
[ 2., 2., 2.],
[ 7., 8., 9.],
[ 2., 2., 2.],
[ 4., 5., 6.]])
This method can only be called on a coalesced sparse tensor. See
Tensor.coalesce() for details.
torch.memory_formattorch.preserve_formattorch.devicenon_blocking (bool, optional) – If True and the source is in pinned memory,
the copy will be asynchronous with respect to the host.
Otherwise, the argument has no effect. Default: False.
memory_format (torch.memory_format, optional) – the desired memory format of
returned Tensor. Default: torch.preserve_format.
Example:
>>> a = torch.rand(10, requires_grad=True)
>>> a.is_leaf
True
>>> b = torch.rand(10, requires_grad=True).cuda()
>>> b.is_leaf
False
# b was created by the operation that cast a cpu Tensor into a cuda Tensor
>>> c = torch.rand(10, requires_grad=True) + 2
>>> c.is_leaf
False
# c was created by the addition operation
>>> d = torch.rand(10).cuda()
>>> d.is_leaf
True
# d does not require gradients and so has no operation creating it (that is tracked by the autograd engine)
>>> e = torch.rand(10).cuda().requires_grad_()
>>> e.is_leaf
True
# e requires gradients and has no operations creating it
>>> f = torch.rand(10, requires_grad=True, device="cuda")
>>> f.is_leaf
True
# f requires grad, has no operation creating it
See torch.istft()
torch.memory_formattorch.preserve_formatdef callable(a, b) -> number
value (float) – the value to fill in with
>>> self = torch.tensor([0, 0, 0, 0, 0])
>>> mask = torch.tensor(
... [[0, 0, 0, 1, 1], [1, 1, 0, 1, 1]],
... dtype=torch.bool,
... )
>>> source = torch.tensor([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])
>>> self.masked_scatter(mask, source)
tensor([[0, 0, 0, 0, 1],
[2, 3, 0, 4, 5]])
sourcemaskmask (BoolTensor) – the boolean mask
source (Tensor) – the tensor to copy from
>>> self = torch.tensor([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])
>>> mask = torch.tensor(
... [[0, 0, 0, 1, 1], [1, 1, 0, 1, 1]],
... dtype=torch.bool,
... )
>>> source = torch.tensor([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])
>>> self.masked_scatter_(mask, source)
tensor([[0, 0, 0, 0, 1],
[2, 3, 0, 4, 5]])
nn.Moduleotherotherselfload_state_dict()torch.devicenon_blocking (bool, optional) – If True and the source is in pinned memory,
the copy will be asynchronous with respect to the host.
Otherwise, the argument has no effect. Default: False.
memory_format (torch.memory_format, optional) – the desired memory format of
returned Tensor. Default: torch.preserve_format.
size (int...) – a list, tuple, or torch.Size of integers defining the
shape of the output tensor.
dtype (torch.dtype, optional) – the desired type of returned tensor.
Default: if None, same torch.dtype as this tensor.
device (torch.device, optional) – the desired device of returned tensor.
Default: if None, same torch.device as this tensor.
requires_grad (bool, optional) – If autograd should record operations on the
returned tensor. Default: False.
layout (torch.layout, optional) – the desired layout of returned Tensor.
Default: torch.strided.
pin_memory (bool, optional) – If set, returned tensor would be allocated in
the pinned memory. Works only for CPU tensors. Default: False.
Example:
>>> tensor = torch.ones(())
>>> tensor.new_empty((2, 3))
tensor([[ 5.8182e-18, 4.5765e-41, -1.0545e+30],
[ 3.0949e-41, 4.4842e-44, 0.0000e+00]])
size (int...) – a list, tuple, or torch.Size of integers defining the
shape of the output tensor.
dtype (torch.dtype, optional) – the desired type of returned tensor.
Default: if None, same torch.dtype as this tensor.
device (torch.device, optional) – the desired device of returned tensor.
Default: if None, same torch.device as this tensor.
requires_grad (bool, optional) – If autograd should record operations on the
returned tensor. Default: False.
layout (torch.layout, optional) – the desired layout of returned Tensor.
Default: torch.strided.
pin_memory (bool, optional) – If set, returned tensor would be allocated in
the pinned memory. Works only for CPU tensors. Default: False.
Example:
>>> tensor = torch.ones(())
>>> tensor.new_empty_strided((2, 3), (3, 1))
tensor([[ 5.8182e-18, 4.5765e-41, -1.0545e+30],
[ 3.0949e-41, 4.4842e-44, 0.0000e+00]])
Returns a Tensor of size size filled with fill_value.
By default, the returned Tensor has the same torch.dtype and
torch.device as this tensor.
fill_value (scalar) – the number to fill the output tensor with.
dtype (torch.dtype, optional) – the desired type of returned tensor.
Default: if None, same torch.dtype as this tensor.
device (torch.device, optional) – the desired device of returned tensor.
Default: if None, same torch.device as this tensor.
requires_grad (bool, optional) – If autograd should record operations on the
returned tensor. Default: False.
layout (torch.layout, optional) – the desired layout of returned Tensor.
Default: torch.strided.
pin_memory (bool, optional) – If set, returned tensor would be allocated in
the pinned memory. Works only for CPU tensors. Default: False.
Example:
>>> tensor = torch.ones((2,), dtype=torch.float64)
>>> tensor.new_full((3, 4), 3.141592)
tensor([[ 3.1416, 3.1416, 3.1416, 3.1416],
[ 3.1416, 3.1416, 3.1416, 3.1416],
[ 3.1416, 3.1416, 3.1416, 3.1416]], dtype=torch.float64)
1size (int...) – a list, tuple, or torch.Size of integers defining the
shape of the output tensor.
dtype (torch.dtype, optional) – the desired type of returned tensor.
Default: if None, same torch.dtype as this tensor.
device (torch.device, optional) – the desired device of returned tensor.
Default: if None, same torch.device as this tensor.
requires_grad (bool, optional) – If autograd should record operations on the
returned tensor. Default: False.
layout (torch.layout, optional) – the desired layout of returned Tensor.
Default: torch.strided.
pin_memory (bool, optional) – If set, returned tensor would be allocated in
the pinned memory. Works only for CPU tensors. Default: False.
Example:
>>> tensor = torch.tensor((), dtype=torch.int32)
>>> tensor.new_ones((2, 3))
tensor([[ 1, 1, 1],
[ 1, 1, 1]], dtype=torch.int32)
datadata (array_like) – The returned Tensor copies data.
dtype (torch.dtype, optional) – the desired type of returned tensor.
Default: if None, same torch.dtype as this tensor.
device (torch.device, optional) – the desired device of returned tensor.
Default: if None, same torch.device as this tensor.
requires_grad (bool, optional) – If autograd should record operations on the
returned tensor. Default: False.
layout (torch.layout, optional) – the desired layout of returned Tensor.
Default: torch.strided.
pin_memory (bool, optional) – If set, returned tensor would be allocated in
the pinned memory. Works only for CPU tensors. Default: False.
Example:
>>> tensor = torch.ones((2,), dtype=torch.int8)
>>> data = [[0, 1], [2, 3]]
>>> tensor.new_tensor(data)
tensor([[ 0, 1],
[ 2, 3]], dtype=torch.int8)
0size (int...) – a list, tuple, or torch.Size of integers defining the
shape of the output tensor.
dtype (torch.dtype, optional) – the desired type of returned tensor.
Default: if None, same torch.dtype as this tensor.
device (torch.device, optional) – the desired device of returned tensor.
Default: if None, same torch.device as this tensor.
requires_grad (bool, optional) – If autograd should record operations on the
returned tensor. Default: False.
layout (torch.layout, optional) – the desired layout of returned Tensor.
Default: torch.strided.
pin_memory (bool, optional) – If set, returned tensor would be allocated in
the pinned memory. Works only for CPU tensors. Default: False.
Example:
>>> tensor = torch.tensor((), dtype=torch.float64)
>>> tensor.new_zeros((2, 3))
tensor([[ 0., 0., 0.],
[ 0., 0., 0.]], dtype=torch.float64)
stdt.detach().cpu().resolve_conj().resolve_neg().numpy()forceTrueforce (bool) – if True, the ndarray may be a copy of the tensor
instead of always sharing memory, defaults to False.
>>> x = torch.randn(2, 3, 5)
>>> x.size()
torch.Size([2, 3, 5])
>>> x.permute(2, 0, 1).size()
torch.Size([5, 2, 3])
The equivalent PyTorch code to create the same five outputs from the dense tensor can be found below:
from torch.sparse import SparseSemiStructuredTensorCUTLASS
from torch.sparse._semi_structured_conversions import (
_sparse_semi_structured_tile,
_compute_compressed_swizzled_bitmask,
)
pruned = _sparse_semi_structured_tile(dense)
packed_cutlass, meta_cutlass = sparse_semi_structured_from_dense_cutlass(
pruned
)
packed_t_cutlass, meta_t_cutlass = (
sparse_semi_structured_from_dense_cutlass(pruned.t().contiguous())
)
bitmask = _compute_compressed_swizzled_bitmask(pruned)
SparseSemiStructuredTensorCUTLASS(
dense.shape,
packed_cutlass,
meta_cutlass,
packed_t_cutlass,
meta_t_cutlass,
bitmask,
)
SparseSemiStructuredTensor
indexsourceIf accumulate is True, the elements in source are added to
self. If accumulate is False, the behavior is undefined if index
contain duplicate elements.
Example:
>>> src = torch.tensor([[4, 3, 5],
... [6, 7, 8]])
>>> src.put_(torch.tensor([1, 3]), torch.tensor([9, 10]))
tensor([[ 4, 9, 5],
[ 10, 7, 8]])
[0, 2^53]You can safely use tensors allocated on side streams without
record_stream(); you must manually ensure that
any non-creation stream uses of a tensor are synced back to the creation
stream before you deallocate the tensor. As the CUDA caching allocator
guarantees that the memory will only be reused with the same creation stream,
this is sufficient to ensure that writes to future reallocations of the
memory will be delayed until non-creation stream uses are done.
(Counterintuitively, you may observe that on the CPU side we have already
reallocated the tensor, even though CUDA kernels on the old tensor are
still in progress. This is fine, because CUDA operations on the new
tensor will appropriately wait for the old operations to complete, as they
are all on the same stream.)
Concretely, this looks like this:
with torch.cuda.stream(s0):
x = torch.zeros(N)
s1.wait_stream(s0)
with torch.cuda.stream(s1):
y = some_comm_op(x)
... some compute on s0 ...
# synchronize creation stream s0 to side stream s1
# before deallocating x
s0.wait_stream(s1)
del x
Note that some discretion is required when deciding when to perform
s0.wait_stream(s1). In particular, if we were to wait immediately
after some_comm_op, there wouldn’t be any point in having the side
stream; it would be equivalent to have run some_comm_op on s0.
Instead, the synchronization must be placed at some appropriate, later
point in time where you expect the side stream s1 to have finished
work. This location is typically identified via profiling, e.g., using
Chrome traces produced
torch.autograd.profiler.profile.export_chrome_trace(). If you
place the wait too early, work on s0 will block until s1 has finished,
preventing further overlapping of communication and computation. If you
place the wait too late, you will use more memory than is strictly
necessary (as you are keeping x live for longer.) For a concrete
example of how this guidance can be applied in practice, see this post:
FSDP and CUDACachingAllocator.
Example:
>>> v = torch.tensor([0., 0., 0.], requires_grad=True)
>>> h = v.register_hook(lambda grad: grad * 2) # double the gradient
>>> v.backward(torch.tensor([1., 2., 3.]))
>>> v.grad
2
4
6
[torch.FloatTensor of size (3,)]
>>> h.remove() # removes the hook
Example:
>>> v = torch.tensor([0., 0., 0.], requires_grad=True)
>>> lr = 0.01
>>> # simulate a simple SGD update
>>> h = v.register_post_accumulate_grad_hook(lambda p: p.add_(p.grad, alpha=-lr))
>>> v.backward(torch.tensor([1., 2., 3.]))
>>> v
tensor([-0.0100, -0.0200, -0.0300], requires_grad=True)
>>> h.remove() # removes the hook
Example:
>>> x = torch.tensor([1, 2, 3])
>>> x.repeat(4, 2)
tensor([[ 1, 2, 3, 1, 2, 3],
[ 1, 2, 3, 1, 2, 3],
[ 1, 2, 3, 1, 2, 3],
[ 1, 2, 3, 1, 2, 3]])
>>> x.repeat(4, 2, 1).size()
torch.Size([4, 2, 3])
requires_grad=Falsetensor.requires_grad_()tensorrequires_grad (bool) – If autograd should record operations on this tensor.
Default: True.
Example:
>>> # Let's say we want to preprocess some saved weights and use
>>> # the result as new weights.
>>> saved_weights = [0.1, 0.2, 0.3, 0.25]
>>> loaded_weights = torch.tensor(saved_weights)
>>> weights = preprocess(loaded_weights) # some function
>>> weights
tensor([-0.5503, 0.4926, -2.1158, -0.8303])
>>> # Now, start to record operations done to weights
>>> weights.requires_grad_()
>>> out = weights.pow(2).sum()
>>> out.backward()
>>> weights.grad
tensor([-1.1007, 0.9853, -4.2316, -1.6606])
reshape()reshapeother (torch.Tensor) – The result tensor has the same shape
as other.
reshape()set_()sizes (torch.Size or int...) – the desired size
memory_format (torch.memory_format, optional) – the desired memory format of
Tensor. Default: torch.contiguous_format. Note that memory format of
self is going to be unaffected if self.size() matches sizes.
Example:
>>> x = torch.tensor([[1, 2], [3, 4], [5, 6]])
>>> x.resize_(2, 2)
tensor([[ 1, 2],
[ 3, 4]])
torch.memory_formattorch.contiguous_formatselfself.size()tensor.size()srcdimension != dimdimension = dimFor a 3-D tensor, self is updated as:
self[index[i][j][k]][j][k] = src[i][j][k] # if dim == 0
self[i][index[i][j][k]][k] = src[i][j][k] # if dim == 1
self[i][j][index[i][j][k]] = src[i][j][k] # if dim == 2
This is the reverse operation of the manner described in gather().
It is also required that
index.size(d) <= src.size(d) for all dimensions d, and that
index.size(d) <= self.size(d) for all dimensions d != dim.
Note that input and index do not broadcast against each other for NPUs,
so when running on NPUs, input and index must have the same number of dimensions.
Standard broadcasting occurs in all other cases.
Moreover, as for gather(), the values of index must be
between 0 and self.size(dim) - 1 inclusive.
Additionally accepts an optional reduce argument that allows
specification of an optional reduction operation, which is applied to all
values in the tensor src into self at the indices
specified in the index. For each value in src, the reduction
operation is applied to an index in self which is specified by
its index in src for dimension != dim and by the corresponding
value in index for dimension = dim.
Given a 3-D tensor and reduction using the multiplication operation, self
is updated as:
self[index[i][j][k]][j][k] *= src[i][j][k] # if dim == 0
self[i][index[i][j][k]][k] *= src[i][j][k] # if dim == 1
self[i][j][index[i][j][k]] *= src[i][j][k] # if dim == 2
Reducing with the addition operation is the same as using
scatter_add_().
reduce (str, optional) – reduction operation to apply, can be either
'add' or 'multiply'.
Example:
>>> src = torch.arange(1, 11).reshape((2, 5))
>>> src
tensor([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10]])
>>> index = torch.tensor([[0, 1, 2, 0]])
>>> torch.zeros(3, 5, dtype=src.dtype).scatter_(0, index, src)
tensor([[1, 0, 0, 4, 0],
[0, 2, 0, 0, 0],
[0, 0, 3, 0, 0]])
>>> index = torch.tensor([[0, 1, 2], [0, 1, 4]])
>>> torch.zeros(3, 5, dtype=src.dtype).scatter_(1, index, src)
tensor([[1, 2, 3, 0, 0],
[6, 7, 0, 0, 8],
[0, 0, 0, 0, 0]])
>>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]),
... 1.23, reduce='multiply')
tensor([[2.0000, 2.0000, 2.4600, 2.0000],
[2.0000, 2.0000, 2.0000, 2.4600]])
>>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]),
... 1.23, reduce='add')
tensor([[2.0000, 2.0000, 3.2300, 2.0000],
[2.0000, 2.0000, 2.0000, 3.2300]])
Writes the value from value into self at the indices
specified in the index tensor. This operation is equivalent to the previous version,
with the src tensor filled entirely with value.
dim (int) – the axis along which to index
index (LongTensor) – the indices of elements to scatter, can be either empty
or of the same dimensionality as src. When empty, the operation
returns self unchanged.
value (Scalar) – the value to scatter.
reduce (str, optional) – reduction operation to apply, can be either
'add' or 'multiply'.
Example:
>>> index = torch.tensor([[0, 1]])
>>> value = 2
>>> torch.zeros(3, 5).scatter_(0, index, value)
tensor([[2., 0., 0., 0., 0.],
[0., 2., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
srcselfsrcdimension != dimdimension = dimFor a 3-D tensor, self is updated as:
self[index[i][j][k]][j][k] += src[i][j][k] # if dim == 0
self[i][index[i][j][k]][k] += src[i][j][k] # if dim == 1
self[i][j][index[i][j][k]] += src[i][j][k] # if dim == 2
self, index and src should have same number of
dimensions. It is also required that index.size(d) <= src.size(d) for all
dimensions d, and that index.size(d) <= self.size(d) for all dimensions
d != dim. Note that index and src do not broadcast.
When index is empty, we always return the original tensor
without further error checking.
Example:
>>> src = torch.ones((2, 5))
>>> index = torch.tensor([[0, 1, 2, 0, 0]])
>>> torch.zeros(3, 5, dtype=src.dtype).scatter_add_(0, index, src)
tensor([[1., 0., 0., 1., 1.],
[0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0.]])
>>> index = torch.tensor([[0, 1, 2, 0, 0], [0, 1, 2, 2, 2]])
>>> torch.zeros(3, 5, dtype=src.dtype).scatter_add_(0, index, src)
tensor([[2., 0., 0., 1., 1.],
[0., 2., 0., 0., 0.],
[0., 0., 2., 1., 1.]])
reduce"sum""prod""mean""amax""amin"srcselfsrcdimension != dimdimension = diminclude_self="True"selfself, index and src should all have
the same number of dimensions. It is also required that
index.size(d) <= src.size(d) for all dimensions d, and that
index.size(d) <= self.size(d) for all dimensions d != dim.
Note that index and src do not broadcast.
For a 3-D tensor with reduce="sum" and include_self=True the
output is given as:
self[index[i][j][k]][j][k] += src[i][j][k] # if dim == 0
self[i][index[i][j][k]][k] += src[i][j][k] # if dim == 1
self[i][j][index[i][j][k]] += src[i][j][k] # if dim == 2
dim (int) – the axis along which to index
index (LongTensor) – the indices of elements to scatter and reduce.
src (Tensor) – the source elements to scatter and reduce
reduce (str) – the reduction operation to apply for non-unique indices
("sum", "prod", "mean", "amax", "amin")
include_self (bool) – whether elements from the self tensor are
included in the reduction
Example:
>>> src = torch.tensor([1., 2., 3., 4., 5., 6.])
>>> index = torch.tensor([0, 1, 0, 1, 2, 1])
>>> input = torch.tensor([1., 2., 3., 4.])
>>> input.scatter_reduce(0, index, src, reduce="sum")
tensor([5., 14., 8., 4.])
>>> input.scatter_reduce(0, index, src, reduce="sum", include_self=False)
tensor([4., 12., 5., 4.])
>>> input2 = torch.tensor([5., 4., 3., 2.])
>>> input2.scatter_reduce(0, index, src, reduce="amax")
tensor([5., 6., 5., 2.])
>>> input2.scatter_reduce(0, index, src, reduce="amax", include_self=False)
tensor([3., 6., 5., 2.])
If source is a Storage, the method sets the underlying
storage, offset, size, and stride.
source (Tensor or Storage) – the tensor or storage to use
storage_offset (int, optional) – the offset in the storage
size (torch.Size, optional) – the desired size. Defaults to the size of the source.
stride (tuple, optional) – the desired stride. Defaults to C-contiguous strides.
torch.memory_formattorch.preserve_formatdim (int, optional) – The dimension for which to retrieve the size.
Example:
>>> t = torch.empty(3, 4, 5)
>>> t.size()
torch.Size([3, 4, 5])
>>> t.size(dim=1)
4
The returned sparse tensor might contain duplicate values if mask
is not coalesced. It is therefore advisable to pass mask.coalesce()
if such behavior is not desired.
mask (Tensor) – a sparse tensor whose indices are used as a filter
Example:
>>> nse = 5
>>> dims = (5, 5, 2, 2)
>>> I = torch.cat([torch.randint(0, dims[0], size=(nse,)),
... torch.randint(0, dims[1], size=(nse,))], 0).reshape(2, nse)
>>> V = torch.randn(nse, dims[2], dims[3])
>>> S = torch.sparse_coo_tensor(I, V, dims).coalesce()
>>> D = torch.randn(dims)
>>> D.sparse_mask(S)
tensor(indices=tensor([[0, 0, 0, 2],
[0, 1, 4, 3]]),
values=tensor([[[ 1.6550, 0.2397],
[-0.1611, -0.0779]],
[[ 0.2326, -1.0558],
[ 1.4711, 1.9678]],
[[-0.5138, -0.0411],
[ 1.9417, 0.5158]],
[[ 0.0793, 0.0036],
[-0.2569, -0.1055]]]),
size=(5, 5, 2, 2), nnz=4, layout=torch.sparse_coo)
sizelen(size) == sparse_dim +
dense_dimIf self specifies one or more elements, however, then each
dimension in size must not be smaller than the corresponding
dimension of self, sparse_dim must equal the number
of sparse dimensions in self, and dense_dim must
equal the number of dense dimensions in self.
size (torch.Size) – the desired size. If self is non-empty
sparse tensor, the desired size cannot be smaller than the
original size.
sparse_dim (int) – the number of sparse dimensions
dense_dim (int) – the number of dense dimensions
sparse_dim (int) – the number of sparse dimensions
dense_dim (int) – the number of dense dimensions
See torch.stft()
dim (int, optional) – the desired dimension in which stride is required
Example:
>>> x = torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
>>> x.stride()
(5, 1)
>>> x.stride(0)
5
>>> x.stride(-1)
1
size (int...) – a sequence of integers defining the shape of the output tensor.
If the self Tensor already
has the correct torch.dtype and torch.device, then self is returned.
Otherwise, the returned tensor is a copy of self with the desired
torch.dtype and torch.device.
Here are the ways to call to:
Returns a Tensor with the specified
dtype
- Args:
memory_format (
torch.memory_format, optional): the desired memory format of returned Tensor. Default:torch.preserve_format.
Returns a Tensor with the specified
deviceand (optional)dtype. IfdtypeisNoneit is inferred to beself.dtype. Whennon_blockingis set toTrue, the function attempts to perform the conversion asynchronously with respect to the host, if possible. This asynchronous behavior applies to both pinned and pageable memory. However, caution is advised when using this feature. For more information, refer to the tutorial on good usage of non_blocking and pin_memory. Whencopyis set, a new Tensor is created even when the Tensor already matches the desired conversion.
Returns a Tensor with same
torch.dtypeandtorch.deviceas the Tensorother. Whennon_blockingis set toTrue, the function attempts to perform the conversion asynchronously with respect to the host, if possible. This asynchronous behavior applies to both pinned and pageable memory. However, caution is advised when using this feature. For more information, refer to the tutorial on good usage of non_blocking and pin_memory. Whencopyis set, a new Tensor is created even when the Tensor already matches the desired conversion.
Example:
>>> tensor = torch.randn(2, 2) # Initially dtype=float32, device=cpu
>>> tensor.to(torch.float64)
tensor([[-0.5044, 0.0005],
[ 0.3310, -0.0584]], dtype=torch.float64)
>>> cuda0 = torch.device('cuda:0')
>>> tensor.to(cuda0)
tensor([[-0.5044, 0.0005],
[ 0.3310, -0.0584]], device='cuda:0')
>>> tensor.to(cuda0, dtype=torch.float64)
tensor([[-0.5044, 0.0005],
[ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0')
>>> other = torch.randn((), dtype=torch.float64, device=cuda0)
>>> tensor.to(other, non_blocking=True)
tensor([[-0.5044, 0.0005],
[ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0')
Returns a sparse tensor with the specified layout and blocksize. If
the self is strided, the number of dense dimensions could be
specified, and a hybrid sparse tensor will be created, with
dense_dim dense dimensions and self.dim() - 2 - dense_dim batch
dimension.
layout (torch.layout, optional) – The desired sparse
layout. One of torch.sparse_coo, torch.sparse_csr,
torch.sparse_csc, torch.sparse_bsr, or
torch.sparse_bsc. Default: if None,
torch.sparse_coo.
blocksize (list, tuple, torch.Size, optional) – Block size
of the resulting BSR or BSC tensor. For other layouts,
specifying the block size that is not None will result in a
RuntimeError exception. A block size must be a tuple of length
two such that its items evenly divide the two sparse dimensions.
dense_dim (int, optional) – Number of dense dimensions of the
resulting CSR, CSC, BSR or BSC tensor. This argument should be
used only if self is a strided tensor, and must be a
value between 0 and dimension of self tensor minus two.
Example:
>>> x = torch.tensor([[1, 0], [0, 0], [2, 3]])
>>> x.to_sparse(layout=torch.sparse_coo)
tensor(indices=tensor([[0, 2, 2],
[0, 0, 1]]),
values=tensor([1, 2, 3]),
size=(3, 2), nnz=3, layout=torch.sparse_coo)
>>> x.to_sparse(layout=torch.sparse_bsr, blocksize=(1, 2))
tensor(crow_indices=tensor([0, 1, 1, 2]),
col_indices=tensor([0, 0]),
values=tensor([[[1, 0]],
[[2, 3]]]), size=(3, 2), nnz=2, layout=torch.sparse_bsr)
>>> x.to_sparse(layout=torch.sparse_bsr, blocksize=(2, 1))
RuntimeError: Tensor size(-2) 3 needs to be divisible by blocksize[0] 2
>>> x.to_sparse(layout=torch.sparse_csr, blocksize=(3, 1))
RuntimeError: to_sparse for Strided to SparseCsr conversion does not use specified blocksize
>>> x = torch.tensor([[[1], [0]], [[0], [0]], [[2], [3]]])
>>> x.to_sparse(layout=torch.sparse_csr, dense_dim=1)
tensor(crow_indices=tensor([0, 1, 1, 3]),
col_indices=tensor([0, 0, 1]),
values=tensor([[1],
[2],
[3]]), size=(3, 2, 1), nnz=3, layout=torch.sparse_csr)
dense_dim (int, optional) – Number of dense dimensions of the
resulting BSC tensor. This argument should be used only if
self is a strided tensor, and must be a value between 0
and dimension of self tensor minus two.
Example:
>>> dense = torch.randn(10, 10)
>>> sparse = dense.to_sparse_csr()
>>> sparse_bsc = sparse.to_sparse_bsc((5, 5))
>>> sparse_bsc.row_indices()
tensor([0, 1, 0, 1])
>>> dense = torch.zeros(4, 3, 1)
>>> dense[0:2, 0] = dense[0:2, 2] = dense[2:4, 1] = 1
>>> dense.to_sparse_bsc((2, 1), 1)
tensor(ccol_indices=tensor([0, 1, 2, 3]),
row_indices=tensor([0, 1, 0]),
values=tensor([[[[1.]],
[[1.]]],
[[[1.]],
[[1.]]],
[[[1.]],
[[1.]]]]), size=(4, 3, 1), nnz=3,
layout=torch.sparse_bsc)
dense_dim (int, optional) – Number of dense dimensions of the
resulting BSR tensor. This argument should be used only if
self is a strided tensor, and must be a value between 0
and dimension of self tensor minus two.
Example:
>>> dense = torch.randn(10, 10)
>>> sparse = dense.to_sparse_csr()
>>> sparse_bsr = sparse.to_sparse_bsr((5, 5))
>>> sparse_bsr.col_indices()
tensor([0, 1, 0, 1])
>>> dense = torch.zeros(4, 3, 1)
>>> dense[0:2, 0] = dense[0:2, 2] = dense[2:4, 1] = 1
>>> dense.to_sparse_bsr((2, 1), 1)
tensor(crow_indices=tensor([0, 2, 3]),
col_indices=tensor([0, 2, 1]),
values=tensor([[[[1.]],
[[1.]]],
[[[1.]],
[[1.]]],
[[[1.]],
[[1.]]]]), size=(4, 3, 1), nnz=3,
layout=torch.sparse_bsr)
selfExample:
>>> dense = torch.randn(5, 5)
>>> sparse = dense.to_sparse_csc()
>>> sparse._nnz()
25
>>> dense = torch.zeros(3, 3, 1, 1)
>>> dense[0, 0] = dense[1, 2] = dense[2, 1] = 1
>>> dense.to_sparse_csc(dense_dim=2)
tensor(ccol_indices=tensor([0, 1, 2, 3]),
row_indices=tensor([0, 2, 1]),
values=tensor([[[1.]],
[[1.]],
[[1.]]]), size=(3, 3, 1, 1), nnz=3,
layout=torch.sparse_csc)
selfselfExample:
>>> dense = torch.randn(5, 5)
>>> sparse = dense.to_sparse_csr()
>>> sparse._nnz()
25
>>> dense = torch.zeros(3, 3, 1, 1)
>>> dense[0, 0] = dense[1, 2] = dense[2, 1] = 1
>>> dense.to_sparse_csr(dense_dim=2)
tensor(crow_indices=tensor([0, 1, 2, 3]),
col_indices=tensor([0, 2, 1]),
values=tensor([[[1.]],
[[1.]],
[[1.]]]), size=(3, 3, 1, 1), nnz=3,
layout=torch.sparse_csr)
non_blocking (bool) – If True, and the source is in pinned memory
and destination is on the GPU or vice versa, the copy is performed
asynchronously with respect to the host. Otherwise, the argument
has no effect.
**kwargs – For compatibility, may contain the key async in place of
the non_blocking argument. The async arg is deprecated.
dimensionselfdimensionAn additional dimension of size size is appended in the returned tensor.
Example:
>>> x = torch.arange(1., 8)
>>> x
tensor([ 1., 2., 3., 4., 5., 6., 7.])
>>> x.unfold(0, 2, 1)
tensor([[ 1., 2.],
[ 2., 3.],
[ 3., 4.],
[ 4., 5.],
[ 5., 6.],
[ 6., 7.]])
>>> x.unfold(0, 2, 2)
tensor([[ 1., 2.],
[ 3., 4.],
[ 5., 6.]])
This method can only be called on a coalesced sparse tensor. See
Tensor.coalesce() for details.
Otherwise, it will not be possible to view self tensor as shape
without copying it (e.g., via contiguous()). When it is unclear whether a
view() can be performed, it is advisable to use reshape(), which
returns a view if the shapes are compatible, and copies (equivalent to calling
contiguous()) otherwise.
shape (torch.Size or int...) – the desired size
Example:
>>> x = torch.randn(4, 4)
>>> x.size()
torch.Size([4, 4])
>>> y = x.view(16)
>>> y.size()
torch.Size([16])
>>> z = x.view(-1, 8) # the size -1 is inferred from other dimensions
>>> z.size()
torch.Size([2, 8])
>>> a = torch.randn(1, 2, 3, 4)
>>> a.size()
torch.Size([1, 2, 3, 4])
>>> b = a.transpose(1, 2) # Swaps 2nd and 3rd dimension
>>> b.size()
torch.Size([1, 3, 2, 4])
>>> c = a.view(1, 3, 2, 4) # Does not change tensor layout in memory
>>> c.size()
torch.Size([1, 3, 2, 4])
>>> torch.equal(b, c)
False
Returns a new tensor with the same data as the self tensor but of a
different dtype.
If the element size of dtype is different than that of self.dtype,
then the size of the last dimension of the output will be scaled
proportionally. For instance, if dtype element size is twice that of
self.dtype, then each pair of elements in the last dimension of
self will be combined, and the size of the last dimension of the output
will be half that of self. If dtype element size is half that
of self.dtype, then each element in the last dimension of self will
be split in two, and the size of the last dimension of the output will be
double that of self. For this to be possible, the following conditions
must be true:
self.dim()must be greater than 0.
self.stride(-1)must be 1.
Additionally, if the element size of dtype is greater than that of
self.dtype, the following conditions must be true as well:
self.size(-1)must be divisible by the ratio between the element sizes of the dtypes.
self.storage_offset()must be divisible by the ratio between the element sizes of the dtypes.The strides of all dimensions, except the last dimension, must be divisible by the ratio between the element sizes of the dtypes.
If any of the above conditions are not met, an error is thrown.
dtype (torch.dtype) – the desired dtype
Example:
>>> x = torch.randn(4, 4)
>>> x
tensor([[ 0.9482, -0.0310, 1.4999, -0.5316],
[-0.1520, 0.7472, 0.5617, -0.8649],
[-2.4724, -0.0334, -0.2976, -0.8499],
[-0.2109, 1.9913, -0.9607, -0.6123]])
>>> x.dtype
torch.float32
>>> y = x.view(torch.int32)
>>> y
tensor([[ 1064483442, -1124191867, 1069546515, -1089989247],
[-1105482831, 1061112040, 1057999968, -1084397505],
[-1071760287, -1123489973, -1097310419, -1084649136],
[-1101533110, 1073668768, -1082790149, -1088634448]],
dtype=torch.int32)
>>> y[0, 0] = 1000000000
>>> x
tensor([[ 0.0047, -0.0310, 1.4999, -0.5316],
[-0.1520, 0.7472, 0.5617, -0.8649],
[-2.4724, -0.0334, -0.2976, -0.8499],
[-0.2109, 1.9913, -0.9607, -0.6123]])
>>> x.view(torch.cfloat)
tensor([[ 0.0047-0.0310j, 1.4999-0.5316j],
[-0.1520+0.7472j, 0.5617-0.8649j],
[-2.4724-0.0334j, -0.2976-0.8499j],
[-0.2109+1.9913j, -0.9607-0.6123j]])
>>> x.view(torch.cfloat).size()
torch.Size([4, 2])
>>> x.view(torch.uint8)
tensor([[ 0, 202, 154, 59, 182, 243, 253, 188, 185, 252, 191, 63, 240, 22,
8, 191],
[227, 165, 27, 190, 128, 72, 63, 63, 146, 203, 15, 63, 22, 106,
93, 191],
[205, 59, 30, 192, 112, 206, 8, 189, 7, 95, 152, 190, 12, 147,
89, 191],
[ 43, 246, 87, 190, 235, 226, 254, 63, 111, 240, 117, 191, 177, 191,
28, 191]], dtype=torch.uint8)
>>> x.view(torch.uint8).size()
torch.Size([4, 16])
other (torch.Tensor) – The result tensor has the same size
as other.
torch.devicenon_blocking (bool, optional) – If True and the source is in pinned memory,
the copy will be asynchronous with respect to the host.
Otherwise, the argument has no effect. Default: False.
memory_format (torch.memory_format, optional) – the desired memory format of
returned Tensor. Default: torch.preserve_format.
memory_format (torch.memory_format, optional): the desired memory format of
returned Tensor. Default: torch.preserve_format.