Level 3 In-Depth AI · Math Foundations
Tensors and Shapes
A tensor is a grid of numbers with any number of axes, such as a batch of colour images or a batch of sentences. Deep-learning code is mostly about tensors and their shapes, and most bugs are shape bugs.
- Level
- ●●●●● Easy
- Reading
- 12 min
- To learn it well
- 45 minutes to read, an afternoon to practise
- Builds on
- 2 concepts →
- Quiz
- 5 questions ↓
Read first
Matrices and Matrix MultiplicationThe full path from zero — 2 concepts before this one
- Vectors
- Matrices and Matrix Multiplication
- Tensors and Shapes
Read them roughly in this order. See it on the concept map →
Why it matters
Open any deep-learning code and you will see comments like # (batch, seq_len, d_model) or # B, C, H, W. Those are shapes, and they are the single most useful thing to keep track of when you read or write a model.
A vector has one axis and a matrix has two. Real AI data needs more:
- A colour photo is three grids of pixels (red, green, blue): 3 axes.
- A training batch of 32 such photos adds one more: 4 axes, shape
(32, 3, 224, 224). - A batch of 8 sentences, each 512 tokens long, each token an embedding of 768 numbers: shape
(8, 512, 768). - A batch of short videos adds a time axis: 5 axes.
The general name for "a grid of numbers with any number of axes" is a tensor, which is why the most popular deep-learning libraries are called PyTorch and TensorFlow. Every input, weight, activation and gradient in a neural network is a tensor. Once you can read and manipulate shapes, you can read model code. When a model crashes, the error is a shape mismatch more often than anything else. When a model silently trains badly, a shape bug is a prime suspect.
The intuition
Think of how you store numbers in everyday life:
- A single number on a sticky note is a scalar.
- A shopping list is a vector: one row of numbers.
- A spreadsheet is a matrix: rows and columns.
- A workbook with several sheets of the same size is a 3-D tensor: sheet, row, column.
- A filing cabinet of identical workbooks is a 4-D tensor: workbook, sheet, row, column.
The number of directions you can move in is the number of axes (NumPy calls it ndim; people also say "dimensions" or, confusingly, "rank"). The shape lists how many entries there are along each axis. A tensor of shape (2, 3, 4, 4) holds numbers.
The physical meaning of each axis is a convention that you and the library agree on. PyTorch stores images as (batch, channels, height, width). TensorFlow and most image files use (batch, height, width, channels). The numbers are the same and only the order of the axes differs, but feed one layout to code expecting the other and you get nonsense.
Key idea A tensor is an n-dimensional grid of numbers. Its shape says how long each axis is, and the meaning of each axis (batch, channel, time, feature…) is a convention you must track yourself. Write shapes in comments.
How it works
Common shapes in AI
| Data | Typical shape | Axes mean |
|---|---|---|
| Tabular batch | (B, F) |
examples, features |
| Greyscale image batch | (B, 1, H, W) |
examples, channel, height, width |
| Colour image batch (PyTorch) | (B, 3, H, W) |
examples, RGB channels, height, width |
| Token ids for a batch of text | (B, T) |
sentences, positions |
| Token embeddings | (B, T, D) |
sentences, positions, features |
| Attention scores | (B, heads, T, T) |
sentences, heads, query position, key position |
| Model output logits | (B, T, V) |
sentences, positions, one score per vocabulary word |
is the batch size, the sequence length, the model width and the vocabulary size. For GPT-2 small, and , so the logits for one batch of 8 sequences of 1,024 tokens hold over 400 million numbers. That is why memory runs out so quickly.
Indexing, slicing and reducing
You pick out parts of a tensor by giving an index per axis. With images of shape (8, 3, 32, 32):
images[0]is the first image: shape(3, 32, 32). Indexing with a single number removes that axis.images[:, 0]is the red channel of every image: shape(8, 32, 32). The colon:means "everything along this axis".images[:4]is the first four images: shape(4, 3, 32, 32). A slice keeps the axis.
A reduction such as sum, mean or max collapses one or more axes. images.mean(axis=(2, 3)) averages over height and width and leaves shape (8, 3): the average colour of each image. The rule to remember: the axis you reduce over is the axis that disappears.
Reshaping
Reshaping changes the shape without changing the numbers or their order in memory. The total count must stay the same. To feed images to a plain fully connected layer you flatten each one: (8, 3, 32, 32) becomes (8, 3072), because . Writing -1 for one size tells the library to work it out.
Reshape reads and writes entries in row-major order: the last axis changes fastest. So reshaping [1, 2, 3, 4, 5, 6] to (2, 3) gives rows [1, 2, 3] and [4, 5, 6], never [1, 3, 5] and [2, 4, 6].
Transposing or permuting reorders axes, which does move numbers around: (8, 3, 32, 32) permuted to (8, 32, 32, 3) changes from channels-first to channels-last. Reshaping cannot do this. Confusing the two is a classic bug: reshaping (B, C, H, W) straight to (B, H, W, C) gives the right shape and scrambled pixels.
Two small helpers you will see everywhere:
- unsqueeze adds an axis of size 1:
(3, 32, 32)→(1, 3, 32, 32), to make a single image look like a batch of one. - squeeze removes axes of size 1:
(8, 1)→(8,).
Broadcasting
Often you want to combine tensors of different shapes, for example subtract the mean of each column from every row of a data table. You could copy the row of means three times to make the shapes equal. Broadcasting does this for you automatically, without actually copying memory.
The rule fits in two lines:
- Line the two shapes up from the right.
- Each pair of sizes must be equal, or one of them must be 1 (a missing axis counts as 1). The size-1 axis is stretched to match.
Worked by hand: a table of shape (3, 2) minus its column means , shape (2,).
X: (3, 2)
means: (2,) -> treated as (1, 2) -> stretched to (3, 2)
result: (3, 2)
Broadcasting can stretch both sides at once. A column of shape (3, 1) plus a row of shape (1, 4) gives a full table of shape (3, 4), the "addition table" of the two.
Broadcasting is used constantly: adding a bias vector of shape (D,) to activations of shape (B, T, D), scaling each channel of an image batch, applying an attention mask of shape (1, 1, T, T) to scores of shape (B, heads, T, T).
Matrix multiplication on tensors
The @ operator works on tensors with more than two axes by treating all but the last two as batch axes. With x of shape (B, T, D) and a weight matrix W of shape (D, D_out), x @ W has shape (B, T, D_out). The same matrix is applied to every token of every sentence. This is how a Transformer layer processes a whole batch with one call.
Multi-head Self-Attention and Multi-Head Attention uses reshaping and permuting to split the feature axis into heads: (B, T, D) → (B, T, heads, D/heads) → (B, heads, T, D/heads). Then a batched matrix multiplication computes every head's scores at once.
Data type and device
Besides its shape, every tensor has a data type (float32, float16, bfloat16, int64…) and, in PyTorch, a device (cpu, cuda for an NVIDIA GPU, mps for Apple silicon). Two tensors must agree on both before you can combine them. Lower-precision types halve memory and speed up computation, which is what Mixed Precision Training training and Quantization exploit.
In code
import numpy as np
# A batch of 8 RGB images, 32 x 32 pixels, PyTorch layout: (batch, channels, height, width)
images = np.random.default_rng(0).random((8, 3, 32, 32))
print(images.ndim, images.shape, images.size) # 4 (8, 3, 32, 32) 24576
print(images[0].shape) # (3, 32, 32) one image
print(images[:, 0].shape) # (8, 32, 32) red channel of every image
print(images.mean(axis=(2, 3)).shape) # (8, 3) average colour per image
print(images.reshape(8, -1).shape) # (8, 3072) flatten each image
print(images.transpose(0, 2, 3, 1).shape) # (8, 32, 32, 3) channels-last
# Broadcasting: subtract each column's mean from every row
X = np.array([[1.0, 10], [2, 20], [3, 30]])
print(X - X.mean(axis=0)) # [[-1. -10.] [0. 0.] [1. 10.]]
# The classic silent bug: (4, 1) minus (4,) broadcasts to (4, 4)
y_pred = np.array([[1.0], [2.0], [3.0], [4.0]]) # model output, shape (4, 1)
y_true = np.array([1.0, 2.0, 3.0, 4.0]) # labels, shape (4,)
print((y_pred - y_true).shape) # (4, 4) oops
print(np.mean((y_pred - y_true) ** 2)) # 2.5 wrong, predictions are perfect!
print(np.mean((y_pred.squeeze(1) - y_true) ** 2)) # 0.0 correct
The same ideas in PyTorch, following a batch of text through the first steps of a language model:
import torch
tokens = torch.randint(0, 50_000, (4, 10)) # 4 sentences, 10 token ids each
emb = torch.nn.Embedding(50_000, 64) # each id -> a vector of 64 numbers
x = emb(tokens)
print(x.shape) # torch.Size([4, 10, 64]) (B, T, D)
W = torch.randn(64, 128)
print((x @ W).shape) # torch.Size([4, 10, 128]) acts on the last axis
heads = x.view(4, 10, 8, 8).transpose(1, 2) # split 64 features into 8 heads of 8
print(heads.shape) # torch.Size([4, 8, 10, 8]) (B, heads, T, D/heads)
view is PyTorch's cheap reshape. It needs the tensor's memory to be laid out in order, and after a transpose it may refuse. Then use .reshape(...) or call .contiguous() first.
Common pitfalls
- Silent broadcasting. The example above is real and common: a
(N, 1)prediction minus a(N,)label gives an(N, N)table. The loss is still a single number, training still runs, and the model learns badly. Check that both sides of a loss have identical shapes. - Reshape instead of permute. Changing
(B, C, H, W)to(B, H, W, C)needspermute/transpose. Usingreshapeproduces the right shape with scrambled data. - Reducing over the wrong axis.
x.mean(0)andx.mean(1)give completely different things. Name the axis you mean in a comment, or use the einops library's named operations, such asreduce(x, 'b t d -> b d', 'mean'). - Forgetting the batch axis. A model trained on batches expects
(B, C, H, W). Passing one image of shape(C, H, W)raises an error or, worse, treats the channels as a batch. Useunsqueeze(0). - Mixed devices or dtypes.
Expected all tensors to be on the same devicemeans one tensor is on the GPU and one on the CPU. Move both with.to(device). - Integer division and types. Token ids must be integers (
int64) for an embedding lookup, while everything that gets gradients must be floating point.
Watch out Broadcasting turns many shape bugs from crashes into silent errors. When a model trains but performs strangely, print the shape of every tensor going into the loss. A good habit is
assert pred.shape == target.shaperight before computing it.
Where it leads
- Convolutional networks slide small filters over
(B, C, H, W)image tensors. - Self-Attention and Multi-Head Attention and the The Transformer are sequences of reshapes, permutes and batched matrix multiplications on
(B, T, D)tensors. Build a GPT from Scratch tracks every shape. - Backpropagation produces a gradient tensor with exactly the same shape as each parameter tensor.
- Mixed Precision Training, Quantization and Distributed Training are about how tensors are stored and where they live.
- Eigenvectors and SVD returns to two-axis matrices and asks what they do geometrically.
A bit of history
In physics, "tensor" has a stricter meaning: a quantity that transforms in a specific way when you change coordinates, used by Gregorio Ricci-Curbastro and Tullio Levi-Civita around 1900 and made famous by Einstein's general relativity in 1915. Machine learning borrowed the word loosely to mean "multi-dimensional array". The array-programming style itself goes back to Kenneth Iverson's APL language in the 1960s. Python's array library grew from Numeric (1995) and numarray into NumPy, created by Travis Oliphant in 2005–2006, which defined the broadcasting rules most libraries now copy. Google released TensorFlow in 2015 and Meta (then Facebook) released PyTorch in early 2017, both built around GPU tensors with automatic gradients.
Try it
- Without running code, write down the shapes of:
x[0],x[:, -1],x.sum(axis=1)andx.reshape(-1, 4)forxof shape(6, 5, 4). Then check in NumPy.- Which of these pairs broadcast, and to what shape?
(5, 3)and(3,);(5, 3)and(5,);(4, 1, 6)and(3, 1).- Take a
(2, 3, 4)tensor of the numbers 0–23. Comparex.reshape(2, 4, 3)withx.transpose(0, 2, 1). Same shape, different contents. Why?Hint for 2: line the shapes up from the right.
(5, 3)and(5,)fails: 3 versus 5. Use(5, 1)instead. The last pair gives(4, 3, 6).
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Tensors (Learn the Basics)
The official hands-on introduction to creating, indexing, reshaping and moving PyTorch tensors.
NumPy: the absolute basics for beginners
The official, friendly introduction to arrays, shapes, indexing and broadcasting.
Broadcasting
The official explanation of NumPy's broadcasting rules, with diagrams of how arrays of different shapes line up.
Broadcasting semantics
PyTorch's short note on how tensors of different shapes are combined, including the in-place gotchas.
einops
A small library that makes reshaping and rearranging tensors readable: you write the shape change in words, such as 'b c h w -> b (h w) c'.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/math/tensors.md