reshape

Documentation

treetensor.torch.reshape(input, shape)[source]

Returns a tensor with the same data and number of elements as input, but with the specified shape. When possible, the returned tensor will be a view of input.

Examples:

>>> import torch
>>> import treetensor.torch as ttorch
>>> ttorch.reshape(torch.tensor([[1, 2], [3, 4]]), (-1, ))
tensor([1, 2, 3, 4])

>>> ttorch.reshape(ttorch.tensor({
...     'a': [[1, 2], [3, 4]],
...     'b': {'x': [[2], [3], [5], [7], [11], [13]]},
... }), (-1, ))
<Tensor 0x7fc9efa3bda0>
├── a --> tensor([1, 2, 3, 4])
└── b --> <Tensor 0x7fc9efa3bcf8>
    └── x --> tensor([ 2,  3,  5,  7, 11, 13])

Note

If the given shape is only one tuple, it should make sure that all the tensors in this tree can be reshaped to the given shape. Or you can give a tree of tuples to reshape the tensors to different shapes.

>>> import torch
>>> import treetensor.torch as ttorch
>>> ttorch.reshape(ttorch.tensor({
...     'a': [[1, 2], [3, 4]],
...     'b': {'x': [[2], [3], [5], [7], [11], [13]]},
... }), {'a': (4, ), 'b': {'x': (3, 2)}})
<Tensor 0x7fc9efa3bd68>
├── a --> tensor([1, 2, 3, 4])
└── b --> <Tensor 0x7fc9efa3bf28>
    └── x --> tensor([[ 2,  3],
                      [ 5,  7],
                      [11, 13]])

Torch Version Related

This documentation is based on torch.reshape in torch v2.0.1+cu117. Its arguments’ arrangements depend on the version of pytorch you installed.

If some arguments listed here are not working properly, please check your pytorch’s version with the following command and find its documentation.

1
python -c 'import torch;print(torch.__version__)'

The arguments and keyword arguments supported in torch v2.0.1+cu117 is listed below.

Description From Torch v2.0.1+cu117

torch.reshape(input, shape)Tensor

Returns a tensor with the same data and number of elements as input, but with the specified shape. When possible, the returned tensor will be a view of input. Otherwise, it will be a copy. Contiguous inputs and inputs with compatible strides can be reshaped without copying, but you should not depend on the copying vs. viewing behavior.

See torch.Tensor.view() on when it is possible to return a view.

A single dimension may be -1, in which case it’s inferred from the remaining dimensions and the number of elements in input.

Args:

input (Tensor): the tensor to be reshaped shape (tuple of ints): the new shape

Example:

>>> a = torch.arange(4.)
>>> torch.reshape(a, (2, 2))
tensor([[ 0.,  1.],
        [ 2.,  3.]])
>>> b = torch.tensor([[0, 1], [2, 3]])
>>> torch.reshape(b, (-1,))
tensor([ 0,  1,  2,  3])