◆ AI All-in-One

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
↗ Plan a path here

Read first

Matrices and Matrix Multiplication

This leads to

QuantizationPyTorchAudio as DataImages as Data
The full path from zero — 2 concepts before this one
  1. Vectors
  2. Matrices and Matrix Multiplication
  3. 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 2×3×4×4=962 \times 3 \times 4 \times 4 = 96 numbers.

scalar 0 axes () a loss vector 1 axis (4,) one example's features matrix 2 axes (3, 4) a table of data 3-D tensor 3 axes (3, 4, 4) one colour image 4-D tensor 4 axes (2, 3, 4, 4) a batch of 2 colour images Shape = the size along each axis. Colour image layout in PyTorch: (channels, height, width); a batch adds a leading axis.
Fig. 1 Tensors with 0 to 4 axes. A scalar has shape (). A vector of 4 numbers has shape (4,). A 3 × 4 matrix has two axes. One colour image is a stack of red, green and blue grids, shape (3, 4, 4). A batch of two colour images adds a leading axis, shape (2, 3, 4, 4).

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

BB is the batch size, TT the sequence length, DD the model width and VV the vocabulary size. For GPT-2 small, D=768D = 768 and V=50,257V = 50{,}257, 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 3×32×32=30723 \times 32 \times 32 = 3072. 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:

  1. Line the two shapes up from the right.
  2. 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 X\mathbf{X} of shape (3, 2) minus its column means [2,20][2, 20], shape (2,).

X:      (3, 2)
means:     (2,)   -> treated as (1, 2) -> stretched to (3, 2)
result: (3, 2)
[110220330]−[220]=[−1−1000110]\begin{bmatrix} 1 & 10 \\ 2 & 20 \\ 3 & 30 \end{bmatrix} - \begin{bmatrix} 2 & 20 \end{bmatrix} = \begin{bmatrix} -1 & -10 \\ 0 & 0 \\ 1 & 10 \end{bmatrix}

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.

Example 1: subtract the column means (3, 2) − (2,): the row of means is copied down to every row 1 10 2 20 3 30 2 20 2 20 2 20 −1 −10 0 0 1 10 − = (3, 2) (2,) → (3, 2) (3, 2) The broadcasting rule Line the shapes up from the right. Each pair of sizes must be equal, or one of them must be 1. A size-1 or missing axis is stretched to match (without copying memory). Example 2: a column plus a row makes a table (3, 1) + (1, 4) → (3, 4): both are stretched 0 0 0 0 10 10 10 10 20 20 20 20 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 11 12 13 14 21 22 23 24 + = (3, 1) (1, 4) (3, 4)
Fig. 2 Broadcasting. Example 1: a (3, 2) table minus a row of 2 column means; the row is stretched down to every row. Example 2: a (3, 1) column plus a (1, 4) row; both are stretched, producing a (3, 4) table of sums.

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) needs permute/transpose. Using reshape produces the right shape with scrambled data.
  • Reducing over the wrong axis. x.mean(0) and x.mean(1) give completely different things. Name the axis you mean in a comment, or use the einops library's named operations, such as reduce(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. Use unsqueeze(0).
  • Mixed devices or dtypes. Expected all tensors to be on the same device means 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.shape right before computing it.

Where it leads

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

  1. Without running code, write down the shapes of: x[0], x[:, -1], x.sum(axis=1) and x.reshape(-1, 4) for x of shape (6, 5, 4). Then check in NumPy.
  2. Which of these pairs broadcast, and to what shape? (5, 3) and (3,); (5, 3) and (5,); (4, 1, 6) and (3, 1).
  3. Take a (2, 3, 4) tensor of the numbers 0–23. Compare x.reshape(2, 4, 3) with x.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).

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A batch of images has shape (8, 3, 32, 32). What is the shape of images.mean(axis=(2, 3))?

  2. Predictions have shape (4, 1) and labels shape (4,). You compute ((pred - y) ** 2).mean(). What goes wrong?

  3. You need to convert images from (B, C, H, W) to (B, H, W, C). Which operation is correct?

  4. Which pair of shapes broadcasts together?

  5. A model trained on batches of shape (B, 3, H, W) is given a single image of shape (3, H, W). What should you do?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Tutorial

Tensors (Learn the Basics)

PyTorch · Beginner · Free

The official hands-on introduction to creating, indexing, reshaping and moving PyTorch tensors.

Docs

Broadcasting

NumPy · Beginner · Free

The official explanation of NumPy's broadcasting rules, with diagrams of how arrays of different shapes line up.

Docs

Broadcasting semantics

PyTorch · Intermediate · Free

PyTorch's short note on how tensors of different shapes are combined, including the in-place gotchas.

Tool

einops

Alex Rogozhnikov · Intermediate · Free

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'.

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

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