torch.as_tensor — PyTorch 2.7 documentation (original) (raw)

torch.as_tensor(data: Any, dtype: Optional[dtype] = None, device: Optional[DeviceLikeType]) → Tensor

Converts data into a tensor, sharing data and preserving autograd history if possible.

If data is already a tensor with the requested dtype and device then data itself is returned, but if data is a tensor with a different dtype or device then it’s copied as if usingdata.to(dtype=dtype, device=device).

If data is a NumPy array (an ndarray) with the same dtype and device then a tensor is constructed using torch.from_numpy().

If data is a CuPy array, the returned tensor will be located on the same device as the CuPy array unless specifically overwritten by device or a default device.

Parameters

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])