as_tensor

Documentation

treetensor.torch.as_tensor(data, *args, **kwargs)[source]

Convert the data into a treetensor.torch.Tensor or torch.Tensor.

Examples:

>>> import torch
>>> import treetensor.torch as ttorch
>>> ttorch.as_tensor(True)
tensor(True)

>>> ttorch.as_tensor([1, 2, 3], dtype=torch.float32)
tensor([1., 2., 3.])

>>> ttorch.as_tensor({
...     'a': torch.tensor([1, 2, 3]),
...     'b': {'x': [[4, 5], [6, 7]]}
... }, dtype=torch.float32)
<Tensor 0x7fc2b80c25c0>
├── a --> tensor([1., 2., 3.])
└── b --> <Tensor 0x7fc2b80c24e0>
    └── x --> tensor([[4., 5.],
                      [6., 7.]])

Torch Version Related

This documentation is based on torch.as_tensor in torch v1.10.0+cu102. 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 v1.10.0+cu102 is listed below.

Description From Torch v1.10.0+cu102

torch.as_tensor(data, dtype=None, device=None)Tensor

Convert the data into a torch.Tensor. If the data is already a Tensor with the same dtype and device, no copy will be performed, otherwise a new Tensor will be returned with computational graph retained if data Tensor has requires_grad=True. Similarly, if the data is an ndarray of the corresponding dtype and the device is the cpu, no copy will be performed.

Args:
data (array_like): Initial data for the tensor. Can be a list, tuple,

NumPy ndarray, scalar, and other types.

dtype (torch.dtype, optional): the desired data type of returned tensor.

Default: if None, infers data type from data.

device (torch.device, optional): the desired device of returned tensor.

Default: if None, uses the current device for the default tensor type (see torch.set_default_tensor_type()). device will be the CPU for CPU tensor types and the current CUDA device for CUDA tensor types.

Example:

>>> a = numpy.array([1, 2, 3])
>>> t = torch.as_tensor(a)
>>> t
tensor([ 1,  2,  3])
>>> t[0] = -1
>>> a
array([-1,  2,  3])

>>> a = numpy.array([1, 2, 3])
>>> t = torch.as_tensor(a, device=torch.device('cuda'))
>>> t
tensor([ 1,  2,  3])
>>> t[0] = -1
>>> a
array([1,  2,  3])