Tokenwerk · The LLM textbook

Chapter 9 · II · From numbers to language · 7 minutes

Vectors, matrices and tensor shapes

Lists and tables full of numbers: that is all a tensor is. Once you can read their shapes, the code of large models suddenly makes sense too.

Order for lots of numbers

You computed a small network by hand: two inputs, two neurons. In a real model exactly the same calculations happen, just thousands of times side by side. To keep that from ending in chaos, we pack numbers into lists and tables.

The names for them:

  • A single number, like 3, is a scalar.
  • A list like [2,1] is a vector.
  • A rectangular table is a matrix.
  • And tensor is the umbrella term for all of these, including stacks of tables and even more directions.

Sounds like science fiction, but it is just a neatly sorted field of numbers. You will find the word “tensor” on every corner of PyTorch code.

The shape reveals the structure

The list [2,1] holds two numbers; its shape is [2]. The table [[1,1],[-1,2]] has two rows and two columns, shape [2,2]. The shape doesn't say which numbers are inside, but how many lie in each direction. Such a direction is called an axis, for example the row direction or the column direction.

A stack of three tables with two rows and four columns each has shape [3,2,4]. Careful: the three numbers in the shape mean “three axes”, not “three numbers stored”. In total it holds 3×2×4=24 numbers. Picture a cabinet: 3 drawers, each with 2 rows of 4 slots.

Our small network as a table

The weights of the two neurons from chapter 5 fit into one shared table:

Neuron Weight for first input Weight for second input Bias
First 1 1 −2
Second −1 2 1

For the inputs [2,1] we compute the familiar neuron sum per row. First row: 2×1+1×1−2=1. Second row: 2×(−1)+1×2+1=1. Then comes ReLU. Nothing new, just neatly lined up.

A matrix multiplication is exactly that: many such weighted sums in one go. It brings no new idea; it is simply the efficient way to compute many neurons at once. And graphics cards can do exactly that blazingly fast.

First a single weighted sum

Take two lists of equal length: [1,2,3] and [4,0,−1]. Multiply the numbers at the same position and add everything up: 1×4+2×0+3×(−1)=1. This calculation is called the dot product, and a single number, a scalar, comes out at the end.

You know this already: a neuron does exactly that with its inputs and weights. By the way, a large dot product does not automatically mean “similar meaning”; more on that later with word vectors.

Dot product in shorthand

With short names for the two lists, you write:

a⋅b=1⋅4+2⋅0+3⋅(−1)=1.a\cdot b=1\cdot4+2\cdot0+3\cdot(-1)=1.

Here a and b are the whole lists. The dot between two list names means dot product; between two single numbers it means ordinary multiplication. You can tell which is meant by what stands on either side.

A matrix multiplication step by step

We want to turn the input [1,2] into two outputs. The first should be 1×3+2×5=13, the second 1×4+2×6=16. We arrange the weights like this:

python
import torch
x = torch.tensor([[1., 2.]])
w = torch.tensor([[3., 4.], [5., 6.]])
print(x @ w)  # tensor([[13., 16.]])

torch.tensor turns lists into a field of numbers. The dots in 1. and 2. mean: decimals allowed. And @ is the Python symbol for matrix multiplication.

For each output we take its column of weights, multiply by the input and add up. Written as shapes: [1,2] @ [2,2] → [1,2]. The two inner numbers (2 and 2) must match. Makes sense, because you need as many weights as there are inputs.

Don't mix them up: times is not always times

For two number fields of equal size, a * b simply multiplies each position by the same position in the other, without adding up. That is called elementwise. a @ b, on the other hand, forms weighted sums. Two completely different calculations, and a swapped symbol is one of the classic programming bugs.

One more term you will run into: transposing means swapping rows and columns. It is needed often, because the same weights are stored lying down or standing up depending on convention. In formulas it is marked with a small raised T, which is not a power.

Why PyTorch weights sometimes look rotated

nn.Linear(2,3) is a layer with two inputs and three outputs. Each of the three outputs needs two weights. PyTorch stores them as three rows of two numbers each, so shape [3,2], “the other way around” from what you might expect.

python
from torch import nn
layer = nn.Linear(2, 3)
x = torch.tensor([[2., 1.]])
y = layer(x)
print(layer.weight.shape)  # torch.Size([3, 2])
print(y.shape)             # torch.Size([1, 3])

The layer does the rotating internally. The weights here are still random, so don't expect a meaningful output.

The four letters you will see everywhere

A batch is a stack of examples processed at the same time. A sequence is a series; later, a series of pieces of text. Every piece of text becomes a list of numbers (exactly how comes in two chapters). These quantities have fixed letters:

Name Meaning Small example
B Number of examples in the batch 2 texts
T Number of processed positions per text 3 positions
D Number of numbers in each position's vector 4 numbers
V Number of possible text pieces in the model's vocabulary only as a later quantity for now

So the shape [B,T,D]=[2,3,4] means: two texts, three positions each, four numbers per position. 24 numbers in total. With these four letters in your head, you can already read the code of a language model surprisingly well.

Three handy moves

Reshape means grouping the same numbers differently, for example twelve numbers into three groups of four. The total stays the same. Transpose swaps axes. Broadcasting means a smaller number field is automatically reused to fit, for example the same bias for every row.

Handy, but use with care: you should always know what each axis stands for. Later, with attention, an axis for “heads” gets added. You don't need to remember that yet.

The most important habit

Before you compute, write down in words what a row and what a column means. Then check the shape. A program can run without errors with matching shapes and still compute nonsense. “Two texts with three positions” is something completely different from “three texts with two positions”, even though both are six positions.

Key points

  • Scalar, vector, matrix, tensor: number, list, table, stack. The shape says how many numbers lie in each direction.
  • Matrix multiplication (@) computes many neurons at once. Elementwise (*) is something else.
  • B, T, D, V: examples, positions, numbers per position, size of the vocabulary.