Tensor shapes dtypes and devices
Quick answer
A tensor is an array of values with a shape, data type and device. PyTorch combines tensor arithmetic with automatic differentiation. Start on CPU with explicitly typed floating-point features; use integer class indices for multiclass cross-entropy. Static examples tested locally with PyTorch 2.10.0+cpu; ByteMind execution is unverified.
Batch and bias
import torchx=torch.tensor([[1,2],[3,4]],dtype=torch.float32)b=torch.tensor([10,20],dtype=x.dtype)print((x+b).tolist(), tuple(x.shape), str(x.device))Expected output: [[11.0, 22.0], [13.0, 24.0]] (2, 2) cpu. The bias is broadcast over the two rows.
How it works
An input batch with N rows and D features has shape (N,D). For nn.Linear(D,H), weights have shape (H,D) and the layer computes X @ W.T + b. Broadcasting aligns trailing dimensions: each pair must be equal or one. Reduction dim=0 combines rows; keepdim=True preserves a size-one axis. Tensor.to(device=..., dtype=...) returns a tensor; assign the result. Integer tensors cannot require gradients. reshape may copy when strides prevent a view; clone makes a separate allocation. A device mismatch is not solved by changing the dtype. CPU examples use explicit float32 or float64; GPU behavior is not tested.
Axis reduction and cast
import torchx=torch.tensor([[1,2],[3,4]])y=x.to(dtype=torch.float64).mean(dim=0,keepdim=True)print(y.tolist(), tuple(y.shape), str(y.dtype))Expected output: [[2.0, 3.0]] (1, 2) torch.float64. The cast permits a floating mean; keeping the reduced axis makes later broadcasting explicit.
Common mistakes
Never assume reshape changes axis order: use transpose or permute. Avoid accidental (N,1) versus (N,) subtraction, which broadcasts to (N,N). Check both features and model parameters are on the same device and use compatible dtypes.
Practice and next steps
Predict the shape after broadcasting a (3,1) tensor with a (1,4) tensor. Then move to differentiating scalar objectives.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Tensor shapes dtypes and devices — knowledge check
Apply tensor shapes dtypes and devices to small examples and debugging scenarios.
What shape results from (3,1)+(1,4)?
Which dtype supports gradients for real-valued parameters?
What does mean(dim=0) on (5,3) return without keepdim?
How should a converted tensor be retained?
Which operation swaps two axes?