TExcelTAD
Home › Math for Deep Learning & LLMs › Tensors and Shapes

Tensors and Shapes

Deep learning generalizes vectors and matrices to tensors: arrays with any number of axes. A batch of colour images is a 4-axis tensor, a batch of token embeddings a 3-axis tensor, attention scores a 4-axis tensor. Most of the linear algebra you know carries over by treating some axes as "batch" axes and doing ordinary matrix algebra on the last two.

Scalars, vectors, matrices, tensors

Object Axes Example Typical shape
scalar 0 a loss ()
vector 1 a bias (d,)
matrix 2 a weight matrix (d_out, d_in)
3-tensor 3 token embeddings of a batch (B, T, d)
4-tensor 4 a batch of RGB images (PyTorch layout) (B, C, H, W)
4-tensor 4 attention scores (B, heads, T, T)

The number of entries is the product of the shape, and reshaping reinterprets the same numbers with a different shape, without copying them, as long as the product is unchanged.

Batched matrix multiplication

A @ B on tensors with more than two axes multiplies the last two axes as matrices and treats all leading axes as a batch:

(A@B)b,i,j=∑kAb,i,k Bb,k,j(A @ B)_{b,i,j} = \sum_k A_{b,i,k}\,B_{b,k,j}

This is how a transformer applies the same weight matrix to every token of every sequence, and how attention computes one T×TT \times T score matrix per head.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
B, T, d, d_out = 2, 4, 8, 3
X = rng.normal(size=(B, T, d))                 # 2 sequences of 4 tokens, 8 features each
W = rng.normal(size=(d_out, d))
Y = X @ W.T                                    # same W for every token of every sequence
print("tokens -> features:", X.shape, "->", Y.shape)
print("token (1, 2) equals W @ x:", np.allclose(Y[1, 2], W @ X[1, 2]))
S = X @ X.transpose(0, 2, 1)                   # per-sequence token-token similarity
print("scores per sequence:", S.shape)
flat = X.reshape(B * T, d)                     # merge batch and time for a plain matrix product
print("reshape keeps values:", np.allclose((flat @ W.T).reshape(B, T, d_out), Y))
tokens -> features: (2, 4, 8) -> (2, 4, 3)
token (1, 2) equals W @ x: True
scores per sequence: (2, 4, 4)
reshape keeps values: True

Image tensors

A colour image has height, width and 3 channels. Frameworks disagree on the order: PyTorch uses (B, C, H, W) ("channels first"), TensorFlow and most image files use (B, H, W, C). Converting is a transpose of axes, not a reshape: reshaping would scramble pixels.

python · try it yourself
import numpy as np

img_hwc = np.arange(2 * 3 * 3).reshape(2, 3, 3)       # height 2, width 3, 3 channels
chw = img_hwc.transpose(2, 0, 1)                      # move channels to the front
wrong = img_hwc.reshape(3, 2, 3)                      # same shape, wrong layout
print("pixel (0,1) in HWC:", img_hwc[0, 1], " CHW:", chw[:, 0, 1], " wrong reshape:", wrong[:, 0, 1])
print("contiguous after transpose:", chw.flags["C_CONTIGUOUS"])
pixel (0,1) in HWC: [3 4 5]  CHW: [3 4 5]  wrong reshape: [ 1  7 13]
contiguous after transpose: False

The transposed view is no longer contiguous in memory; frameworks sometimes copy (.contiguous() in PyTorch) before fast kernels can use it.

In software

  • torch.Tensor.view requires compatible memory layout; reshape copies if needed.
  • x.permute(0, 3, 1, 2) in PyTorch converts NHWC to NCHW; einops.rearrange(x, "b h w c -> b c h w") writes the same thing readably (Broadcasting and Einsum).
  • Shape errors are the most common bug in model code: printing x.shape at each layer is a legitimate debugging technique.

Exercises

Exercise 1: Count entries

How many numbers are in a tensor of shape (16, 3, 224, 224), and how many megabytes in float32?

Answer

2 408 4482\,408\,448 numbers, about 9.69.6 MB.

Solution

16⋅3⋅224⋅224=2 408 44816 \cdot 3 \cdot 224 \cdot 224 = 2\,408\,448; times 4 bytes is 9 633 7929\,633\,792 bytes.

Exercise 2: Batched product shapes

A has shape (5, 7, 3, 4) and B has shape (5, 7, 4, 2). What is the shape of A @ B?

Answer

(5, 7, 3, 2).

Solution

The leading (5, 7) axes are batch axes; the last two multiply as (3×4)(4×2)=3×2(3 \times 4)(4 \times 2) = 3 \times 2.

Exercise 3: Flatten for a dense layer (code)

A batch of 10 images of shape (1, 28, 28) must enter a dense layer with 784 inputs. Reshape it and print the shape.

Answer

(10, 784).

Solution

Keep the batch axis and merge the rest: -1 lets NumPy compute 1⋅28⋅28=7841 \cdot 28 \cdot 28 = 784.

python · try it yourself
import numpy as np
imgs = np.zeros((10, 1, 28, 28))
print(imgs.reshape(10, -1).shape)
(10, 784)

Test yourself

For tensors of shape (B, T, d) and a matrix W of shape (d_out, d), X @ W.T has shape…

  1. (B, T, d)
  2. (B, T, d_out)
  3. (d_out, d)
  4. (B, d_out)

Converting an image batch from (B, H, W, C) to (B, C, H, W) requires…

  1. a reshape
  2. a transpose (permutation) of axes
  3. a matrix inverse
  4. nothing

Attention scores in a multi-head transformer typically have shape…

  1. (B, T)
  2. (B, heads, T, T)
  3. (T, d)
  4. (heads,)