Tensors: Creation, Attributes & Dtypes
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
A tensor is a multidimensional array of numbers of a single dtype that lives on a device and can optionally record the operations applied to it for automatic differentiation. It is the one data structure the rest of PyTorch is built on: inputs, labels, parameters, activations and gradients are all tensors. This page covers creation, attributes, dtypes and type promotion. Indexing and views are on Indexing, Views and Broadcasting, NumPy exchange on NumPy and DLPack Interop, and gradients on Autograd Fundamentals.
It targets Python 3.13 and PyTorch 2.15. Examples were run on Python 3.13 with PyTorch 2.15 (CPU) on 2026-10-31. The outputs shown in comments are what the run printed. The linear-algebra background is in Math for ML and the equivalent NumPy ideas are in NumPy array creation and NumPy data types.
Creating tensors
import torch
# From Python data: always copies, dtype inferred from the data
a = torch.tensor([[1, 2, 3], [4, 5, 6]]) # int64
b = torch.tensor([1.0, 2.5]) # float32 (default dtype)
c = torch.tensor([True, False]) # bool
# Factory functions: shape first, dtype/device/requires_grad as keywords
z = torch.zeros(2, 3)
o = torch.ones((2, 3), dtype=torch.float64)
f = torch.full((2, 2), 7.0)
e = torch.empty(2, 3) # uninitialized memory
r = torch.arange(0, 10, 2) # tensor([0, 2, 4, 6, 8])
l = torch.linspace(0, 1, steps=5) # includes both endpoints
i = torch.eye(3)
# Random tensors
u = torch.rand(2, 3) # uniform [0, 1)
n = torch.randn(2, 3) # standard normal
k = torch.randint(0, 10, (2, 3)) # integers in [0, 10)
p = torch.randperm(5) # random permutation
# Same shape/dtype/device as another tensor
zl = torch.zeros_like(n)
ol = torch.ones_like(a, dtype=torch.float32)
nw = n.new_zeros(4) # new_* keeps dtype/device of n
print(a.shape, a.dtype, a.device) # torch.Size([2, 3]) torch.int64 cpu
Source: https://docs.pytorch.org/tutorials/beginner/basics/tensorqs_tutorial.html and https://docs.pytorch.org/docs/stable/tensors.html
Guidance and pitfalls:
-
torch.tensor(data)always copies. Usetorch.as_tensor(data)to share memory with an existing array or tensor when possible, andtorch.from_numpyfor NumPy arrays (see the NumPy page). -
The legacy constructors
torch.Tensor(...),torch.FloatTensor(...)andtorch.LongTensor(...)are kept only for backward compatibility.torch.Tensor(2, 3)creates uninitialized float32 memory and does not takedtypeordevice; prefer the factory functions above. -
torch.emptyreturns whatever was in memory, so the values (possibly NaN) are meaningless until you fill them. -
torch.arange(0, 1, 0.1)has floating-point length surprises; prefertorch.linspacewhen you need an exact number of points. -
Pass
device=anddtype=to the factory instead of creating on the CPU and converting, which avoids a copy. -
Integer data gives
int64, float data givesfloat32, Python booleans givebool, Python complex numbers givecomplex64.
Attributes
x = torch.randn(2, 3, 4)
x.shape # torch.Size([2, 3, 4]); also x.size() and x.size(0)
x.ndim # 3 (also x.dim())
x.numel() # 24
x.dtype # torch.float32
x.device # device(type='cpu')
x.layout # torch.strided
x.stride() # (12, 4, 1)
x.is_contiguous() # True
x.requires_grad # False
x.is_leaf # True
x.element_size() # 4 bytes
x.nbytes # 96
torch.Size is a tuple subclass, so it unpacks and compares like one. The stride is the jump in elements needed to move one step along each dimension: for a contiguous tensor of shape (2, 3, 4) it is (12, 4, 1). Strides are the reason views (transposes, slices, expands) can share storage; see the next page. The layout is torch.strided for ordinary dense tensors; torch.sparse_coo is the beta sparse layout (see Sparse, Nested and Complex Tensors). Memory formats such as torch.channels_last change stride order for image tensors without changing shape.
Dtypes
The official dtype table in 2.15 contains these families:
| dtype | Aliases | Notes |
|---|---|---|
|
|
default floating dtype |
|
|
double precision |
|
|
sign 1, exponent 5, mantissa 10 bits |
|
none |
sign 1, exponent 8, mantissa 7 bits; the float32 range with less precision |
|
|
complex numbers; |
|
none |
8-bit integers |
|
|
signed integers; |
|
none |
boolean |
|
none |
low-precision "shell" dtypes: creation and layout operations work, other operations only case by case |
|
none |
limited eager-mode support; mainly there to assist |
Convert with x.to(torch.float16), x.to(other_tensor) (dtype and device), or the shortcuts x.float(), x.double(), x.half(), x.bfloat16(), x.long(), x.int(), x.bool(). x.to(...) returns x itself when nothing changes, so it does not always copy; use x.clone() for a guaranteed copy. Casting a float to an integer truncates toward zero; casting out-of-range values is undefined behaviour in C terms, so clamp first. Which dtype to choose for training (float32, bfloat16 or float16 with scaling) is discussed in Mixed Precision with torch.amp and Hardware, Memory and Mixed Precision.
Default dtype
Floating-point Python data and factory functions without dtype use torch.get_default_dtype(), which is torch.float32 initially. torch.set_default_dtype(torch.float64) changes it process-wide, which affects every later torch.tensor([1.0]), torch.zeros, torch.randn and newly created nn.Module parameters. Setting it inside a library is rude to callers; prefer explicit dtype= arguments. (The default-dtype functions are listed in the torch namespace documentation; the tensor attributes page itself only mentions get_default_dtype() in its type promotion rules.)
Type promotion
When an operation mixes dtypes, PyTorch promotes to a result dtype using categories ordered complex, floating, integral, boolean:
-
If a scalar operand is in a higher category than every tensor operand, the result uses a type large enough for that scalar’s category.
-
Else if a zero-dimensional tensor is in a higher category than the dimensioned tensors, the same applies to the zero-dim tensors.
-
Otherwise the result is the smallest type that is large enough and of the right category for all dimensioned operands.
A floating-point scalar counts as torch.get_default_dtype() and a non-bool integer scalar as torch.int64. Values are not inspected, unlike older NumPy behaviour.
i32 = torch.ones(3, dtype=torch.int32)
i64 = torch.ones(3, dtype=torch.int64)
f32 = torch.ones(3, dtype=torch.float32)
u8 = torch.ones(3, dtype=torch.uint8)
(i32 + 5).dtype # torch.int32 (scalar of same category)
(i32 + torch.tensor(5)).dtype # torch.int32 (zero-dim, same category)
(i32 + i64).dtype # torch.int64
(torch.ones(3, dtype=torch.bool) + u8).dtype # torch.uint8
(i64 + f32).dtype # torch.float32
(i32 / 2).dtype # torch.float32 (true division returns floats)
try:
i32 *= f32 # in-place cannot cast a float result into an integer
except RuntimeError as err:
print("RuntimeError:", err)
Two consequences: int64 + float32 is float32, which silently loses integer precision above \(2^{24}\); and in-place operations refuse to cast a result to a lower category (float into integer, non-bool into bool, complex into non-complex). Compare with the NumPy rules in NumPy type promotion.
Device, copies and conversions
x.to("cuda"), x.cuda(), x.cpu() and x.to(device, dtype) copy across devices; see Devices and Accelerators. x.item() converts a one-element tensor to a Python number and x.tolist() to nested lists; both synchronize with the GPU. x.detach() returns a tensor that shares data but is cut from the autograd graph, and x.clone() copies the data and stays connected to the graph.
x = torch.arange(6, dtype=torch.float32).reshape(2, 3)
y = x.to(torch.float64) # new tensor, new dtype
w = x.to(torch.float32) # same object: no change requested
print(w is x, y.dtype) # True torch.float64
s = torch.tensor(3.14)
print(s.item(), s.shape) # 3.140000104904175 torch.Size([]): float32 rounding
print(torch.tensor([[1, 2], [3, 4]]).tolist())
Common mistakes
-
Using
torch.tensor(existing_tensor): PyTorch warns and recommendsexisting_tensor.clone().detach(). -
Assuming
torch.tensor([1, 2, 3]) / 2is integer division: true division gives floats; use//ortorch.div(..., rounding_mode="floor")for floor division. -
Forgetting that integer tensors cannot require gradients; only floating-point and complex tensors can.
-
Building labels as
float32for cross-entropy with class indices: index targets must beint64(see Loss Functions). -
Comparing float tensors with
==; usetorch.allcloseortorch.isclose.