Lesson 1.1 — Tensor Fundamentals
Watch the robot tensor animation (18 seconds)
Why does a neural network need tensors?
Traditional control
Symbols: x(t) current state vector · u(t) control input at step t · A state-transition matrix · B input matrix · x(t+1) next state vector.
Learned dynamics
Symbols: f_θ learned neural network · θ parameter tensors · x(t), u(t) current state and control input · x̂(t+1) predicted next state.
Key idea: in the PyTorch computing context, a tensor is a multidimensional array carrying a shape, a data type and a device. This is not the strict differential-geometry definition of a tensor.
One model computation, three tensors
Scalar ()
Speed magnitude: a single number
Vector (3,)
End-effector position: three coordinates
Matrix (2, 3)
Two samples, each with three features
3D Tensor (3, 2, 3)
A collection of three 2-D matrices
The four terms you must own
| Term | Meaning | Example: (2, 3, 4) |
|---|---|---|
| Shape | Length of each axis | (2, 3, 4) |
| Rank / ndim | Number of axes — not matrix rank | 3 |
| Axis / dimension | A specific axis, indexed from 0 | axis 0: 2; axis 1: 3; axis 2: 4 |
| numel | Total number of elements | 24 |
Scalar → Vector → Matrix → Tensor
Dimension Explorer
X = torch.arange(12).reshape((3, 4))
# X.shape = (3, 4); X.ndim = 2; X.numel() = 12
Scalar ≠ length-one vector. A scalar has shape () and
zero axes; a vector with one element has shape (1,) and one axis.
Likewise, tensor rank means ndim, not the linear-algebra rank of a matrix.
A 2 × 2 matrix of all ones has ndim 2 and matrix rank 1.
Axis Navigator — which index moves where?
Axis Navigator · axes and indices
A = torch.arange(12).reshape(3, 4)
# axis 0 = row index, axis 1 = column index
Axis meaning is a convention. In a matrix, axis 0 is the row index and axis 1 the column index. In a robot trajectory, axis 0 can be the batch. PyTorch knows the axis lengths; it does not know what you meant an axis to represent.
Robot trajectory — a four-dimensional tensor
Let each axis have its own index set. For this data layout, a coordinate selects one trajectory, one time step, one joint and one state variable. A length-one axis still contributes to the rank. The number of entries is the product of the axis lengths.
Symbols: X 4-D trajectory tensor · B (b) batch size / number of trajectories · T (t) time steps per trajectory · J (j) joints / actuators · S (s) state variables per joint (position, velocity, torque) · numel(X) total scalar elements.
Play through the leading slice, then change just one index in Inspect an element. Changing time moves along the same signal. Changing the joint or state chooses a different signal.
Robot trajectory · (B, T, J, S)
X = torch.zeros((32, 100, 7, 3), dtype=torch.float32)
# X.ndim = 4; X.numel() = 67,200
Batch ≠ Time. Batch indexes independent samples; Time indexes the sequence inside one sample. The same shape does not imply the same semantics. Merging J and S only changes the data layout; it does not learn a new feature.
An image is also a tensor
Symbols: I 4-D image batch tensor in NCHW layout · 8 (N) batch of images · 3 (C) RGB color channels · 480 (H) image height in pixels · 640 (W) image width in pixels.
RGB Channel Explorer
Robot (B, T, J, S) and image (B, C, H, W) are both rank-4
tensors, but their axes have nothing in common semantically. Always name the axes
before manipulating them.
dtype and device
dtype — what is stored?
| dtype | Bytes | Typical use |
|---|---|---|
| float32 | 4 | Default for continuous inputs and weights |
| float64 | 8 | Higher-precision verification |
| float16 / bfloat16 | 2 | Low-precision compute on supported hardware |
| int64 | 8 | Indices and many classification targets |
| bool | 1 | Validity masks |
Memory Payload Explorer
Floating-point Precision Lens
| dtype | Stored value | Δ vs binary64 |
|---|---|---|
float16 | 0.09997558593750 | -2.4414e-5 |
float32 | 0.1000000014901 | 1.4901e-9 |
float64 | 0.1000000000000 | 0.0000e+0 |
device — where does it live?
device is the compute device a tensor is allocated on — CPU, a CUDA GPU, or a supported MPS device on Apple Silicon. It is a different attribute from shape and dtype.
For 67,200 float32 values: 67,200 × 4 = 268,800 bytes = 262.5 KiB of logical element data. Metadata, allocator overhead and gradients are not included.
Device Transfer Simulator
X = torch.ones((2, 4), dtype=torch.float32, device='cpu')
Y = X.to('cuda') # discrete VRAM copy (Y is not X)
cpu → cuda copies across PCIe into discrete VRAM, cpu → mps wraps Unified Memory as an mps:0 tensor, and cpu → cpu is a zero-copy no-op (Y is X).Tensors used in ordinary element-wise operations generally need compatible devices. This course starts on CPU so that device configuration problems are not mixed with mathematical ones.
Learn by coding — PyTorch
Setup · local environment
python3 -m venv .venv
source .venv/bin/activate
python -m pip install torch
python -c "import torch; print(torch.__version__)"
macOS / Linux example. Skip it if you already have a working environment.
PyTorch syntax guide — read this before predicting
Before answering the code-prediction questions below, make sure these four Python/PyTorch conventions are clear:
| Syntax | What it means | Example & why it matters |
|---|---|---|
1. vs 1 | Trailing dot makes a Python float (1.0); no dot is an int | torch.tensor([1., 2., 3.]) → float32; torch.tensor([1, 2, 3]) → int64 |
.item() | Unwraps a 1-element (0-D) tensor into a plain Python int or float | X[1, 2, 3] is tensor(23) (ndim=0); X[1, 2, 3].item() is 23 |
torch.arange(N) | Creates 1-D integers 0, 1, ..., N-1 | torch.arange(24) has shape (24,) and dtype=int64 |
x.shape / x.ndim / x.numel() | Axis lengths / number of axes / total element count | For (2, 3, 4): shape=torch.Size([2, 3, 4]), ndim=3, numel()=24 |
x.element_size() / x.is_contiguous() | Bytes per element / whether memory order matches row-major shape | float32 → 4 bytes; element_size() * numel() gives logical bytes |
01 — Create tensors and inspect properties
ndim, shape and numel are independent properties. Writing 1. (with a trailing dot) makes a float literal, so [1., 2., 3.] defaults to float32, whereas integer inputs like [1, 2, 3] or torch.arange(24) default to int64.
import torch
x = torch.tensor([1., 2., 3.])
X = torch.arange(24).reshape(2, 3, 4)
print(x.shape, x.ndim, x.dtype)
print(X.shape, X.ndim, X.numel())
02 — Integer indexing vs slicing (and .item())
Integer indexing (like X[0]) removes the indexed axis; slicing (like X[0:1]) keeps it. Indexing every axis (X[1, 2, 3]) leaves a 0-D scalar tensor tensor(23), and .item() extracts the plain Python number 23.
X = torch.arange(24).reshape(2, 3, 4)
print(X[0].shape)
print(X[0:1].shape)
print(X[:, 1, :].shape)
print(X[1, 2, 3].item())
03 — Reshape vs transpose
Check the arrangement with identifiable elements; never validate with shape alone.
X = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(X.reshape(3, 2))
print(X.transpose(0, 1))
04 — Robot trajectory
Organize data as (B, T, J, S); reshape merges the adjacent J and S axes.
B, T, J, S = 2, 3, 2, 3
X = torch.arange(B*T*J*S).reshape(B,T,J,S)
Y = X.reshape(B,T,J*S)
print(X.shape, Y.shape)
print(X[0, 1, 1, 2].item())
print(Y[0, 1, 1*S+2].item())
assert X.numel() == Y.numel()
05 — dtype, bytes and device
Every element shares one dtype. Element size × numel gives the logical payload, not the whole memory footprint.
X = torch.zeros(32, 100, 7, 3, dtype=torch.float32)
print(X.numel(), X.element_size(), X.numel() * X.element_size())
print(X.device, X.is_contiguous())
Y = X.to('cpu')
print(Y is X)
to('cpu') on a CPU float32 tensor may return the same object; it is not guaranteed to copy.
Mini project — robot data shape audit
Goal: without looking at the answer, create a (32, 100, 7, 3) tensor, print the first trajectory, the first time step and the merged features, and assert every shape. Write one sentence per axis explaining its meaning.
import torch
B, T, J, S = 32, 100, 7, 3
X = torch.arange(B * T * J * S).reshape(B, T, J, S)
# TODO: extract the first trajectory, removing the batch axis
# TODO: extract the first time step for all trajectories
# TODO: merge J and S into a single feature axis
# TODO: add shape and element-count assertions
Advanced: prove that the same (b, t, j, s) maps to the same value before and after merging. Do not hide an axis-order bug behind random numbers.