Index

Free, with Google

Keep going, free.

A free account opens lessons 2 and 3 of every track, 33 more lessons, and keeps your progress and review cards on every device.

Start free with Google

A chalk plan

Open everything on chalk.

Every lesson, board, video, lab and paper, and the full review decks. Yearly is $39/year.

See plansStart free instead

Module 01 · AI · Neurons to a language model · about 21 min to read

Watch: Neural networks end to end, and the PyTorch that runs them
▶ VideoPlay it as a journeyTutor comes with a plan

Vectors, Dot Products and Matrix Multiply

What a Neural Network Is
What a Neural Network Is · Open board

The What a Neural Network Is board, drawn for the next lesson. Every arrow on it is a multiply and every box is an add, and this lesson is the arithmetic under that drawing, done by hand, slowly enough to see it.

Before you start. You need school arithmetic and nothing more: multiply two numbers, add a short column, and remember that a minus times a minus is a plus. This is the maths floor under What a Neural Network Is, Tokens & Embeddings and Attention & the Transformer, and each of those will feel lighter once the one sum in this lesson is a habit.

2013: a chip built for one sum

In 2013, engineers at Google did a sum on the back of an envelope and did not like the answer. Their speech recognition ran on neural networks, and it worked. So they asked: what if people used voice search for three minutes a day? The answer, in their own words later, was that Google’s datacenters would have to double to keep up.

Until then, the company had run neural networks on ordinary processors, the general-purpose chips in every server. Those chips can do anything, and so they do any one thing only so fast. Spare capacity had made that free. A doubling was not free.

How many months did Google take to go from starting its chip project to running it in datacenters?

25.5 months

So Google started a rush project to build a chip that could do almost nothing. It could not run a web server or a database. It did one sum, over and over: multiply two numbers, add the result to a running total. At its heart was a grid of 256 by 256 little calculators, 65,536 of them, all doing that one sum at the same moment. They called it the Tensor Processing Unit, designed, built and running in datacenters within 15 months, in service from 2015. The paper describing it came out in 2017.

A whole chip for “multiply, then add”. This lesson is what that sum is, what question it answers, and how a few of them make one step of a neural network.

A vector: a film described as a short list of numbers

Start with something a computer cannot eat: a film. It eats numbers only. So describe the film with numbers.

Pick three things you care about, always in the same order: how much action, how much romance, how much comedy, each out of 5. These numbers are made up for this lesson. A heist film might score 4 for action, 1 for romance and 3 for comedy. Write that as one list in square brackets:

heist  = [4, 1, 3]      action, romance, comedy
caper  = [5, 0, 4]
weepie = [0, 5, 1]

The order is the whole trick: the second slot always means romance.

A list of numbers like this, where each position has a fixed meaning, is a vector. That is all the word means.

There is a second way to see one, and both matter. Drop romance for a moment and keep two numbers, action and comedy. Now the heist film is a point on graph paper: 4 along, 3 up. Draw an arrow from the corner to that point. The caper, at 5 along and 4 up, is an arrow pointing almost the same way. The weepie, at 0 along and 1 up, points straight up the page, off in its own direction.

123451234action →comedy → heist (4, 3)caper (5, 4)weepie (0, 1)

Films of the same kind point the same way. Keep that picture. A vector is a description when you read it, and an arrow when you draw it, and the next sum works on both.

The dot product: multiply the pairs, add them up

Now you. Say one point of action is worth 2 to you, one point of romance costs you 1 (you get bored), and one point of comedy is worth 1. Your taste is also a vector, in the same order:

you = [2, -1, 1]

How much will you enjoy the heist film? Line the two lists up, multiply each pair, add:

action:   4 × 2    =  8
romance:  1 × (-1) = -1
comedy:   3 × 1    =  3
                    ----
                     10

That number is a dot product: two vectors of the same length, multiplied slot by slot, then added. It is the sum from the Google chip, done three times and totalled.

The weepie gives 0 × 2 + 5 × (-1) + 1 × 1 = -4. The caper gives 5 × 2 + 0 + 4 × 1 = 14. You would pick the caper.

Read what the number means. Every slot where the film has a lot of something you like adds a lot. A slot where one of you has a zero adds nothing. A slot where they pull opposite ways, the film full of romance and you against it, subtracts. So the dot product is how much two lists agree. Big and positive: they point the same way. Near zero: they have nothing to do with each other. Negative: they point apart.

Dot the heist [4, 1, 3] with the caper [5, 0, 4]. What total do you get?

55

It works between two films as well. Heist against caper is 4×5 + 1×0 + 3×4 = 32. Heist against weepie is 0 + 5 + 3 = 8. The heist agrees with the caper four times as much.

A matrix: many dot products at once

One viewer is not a cinema. Add two more, each a taste vector, and stack all three as rows of one table:

            action  romance  comedy
you       [   2      -1        1  ]
romantic  [  -1       3        0  ]
comic     [   0       0        2  ]

A table of numbers in rows and columns is a matrix. This one holds three tastes.

Multiplying the matrix by the heist vector means: take each row, dot it with the film, write the answer down.

flowchart LR
  F["heist [4, 1, 3]"] -->|"row 1: 8 - 1 + 3"| A["you: 10"]
  F -->|"row 2: -4 + 3 + 0"| B["romantic: -1"]
  F -->|"row 3: 0 + 0 + 6"| C["comic: 6"]

In: one vector of three numbers, a film. Out: another vector of three numbers, [10, -1, 6]. That is matrix multiply. Nothing new, only the dot product done once per row.

Look at what just happened to the film. It went in described by what is in it (action, romance, comedy) and came out described by who likes it (you, the romantic, the comic). Same film, new description. A matrix is a machine for re-describing a thing.

Put three films side by side and you get nine dot products, three viewers by three films, one grid out. Google’s chip does 65,536 multiply-and-adds in a single tick: this grid, far larger.

One layer: y = Wx + b, then the zero rule

Two small additions turn this into one step of a neural network.

First, some viewers are harder to please before the film even starts. Give each one a fixed amount added to their score: you start at -4 (a long day), the romantic at 0, the comic at +1. That fixed extra per row is the bias.

scores  [10, -1, 6]
bias  + [-4,  0, 1]
        -----------
        [ 6, -1, 7]

Second, a rule: any score below zero becomes zero. A viewer who would hate the film does not report hating it. They just do not show up. The romantic’s -1 becomes 0. The rule is an activation, and this one, “negative becomes zero”, is the one What a Neural Network Is calls ReLU, short for rectified linear unit: “rectified” because the negative half is cut off, “linear” because the positive half passes through unchanged.

after the zero rule: [6, 0, 7]

Written the short way, one layer is:

y = activation(W x + b)

Read it as: take the input list x, dot it with every row of the table W, add each row’s fixed extra b, then zero anything negative. The numbers in W are the network’s weights, the dials What a Neural Network Is shows being turned. The film became a new vector, and that new vector can be the input to the next layer, which re-describes it again.

That is all a neural network computes, layer after layer. A large language model does it with tables thousands of numbers wide, for every word, which is why Google built a chip that does nothing else.

You now know

  • A vector is a list of numbers where each position has a fixed meaning, and it can be read as a description or drawn as an arrow.
  • A dot product multiplies two same-length lists slot by slot and adds the results. The total says how much the two agree.
  • A positive dot product means two vectors point the same way, near zero means unrelated, negative means they point apart.
  • Multiplying a matrix by a vector is one dot product per row, and it turns one description of a thing into another.
  • One neural-network layer is y = activation(W x + b): a matrix multiply, a fixed extra per row, then a rule such as “negative becomes zero”.
  • Chips like Google’s TPU exist because nearly all of that work is multiply-then-add, done in huge grids at once.

Stop here if you want. What follows keeps the same films and goes one level deeper: why a bigger film is not a more similar one, what a neuron is, why the chip is a grid, and where all this turns up again in embeddings and attention.

Second read: the same cinema, one level deeper

The films and viewers are still made up, so the sums fit in your head. Real models learn their numbers instead of having them typed in, and their slots have no names. The chip numbers are real, from Google’s 2017 paper (linked below).

The sequel problem

The heist film does well, so the studio makes Heist 2. Same kind of film, everything turned up: twice the action, twice the romance, twice the comedy.

heist  = [4, 1, 3]
heist2 = [8, 2, 6]

Dot Heist 2 [8, 2, 6] with the caper [5, 0, 4]. What total do you get?

66

Heist 2 against the caper is 40 + 0 + 24 = 64, double the original’s 32. So did the sequel become twice as much like the caper? No. It is the same kind of film, only louder. The dot product cannot tell “more alike” from “bigger”.

On graph paper the problem is plain to see. Keep action and comedy again. Heist 2’s arrow points exactly where the heist’s arrow points. It is just twice as long.

12345678123456action →comedy → 435 Heist 2 (8, 6)heist (4, 3)caper (5, 4)

So to ask “are these the same kind of film?”, look at where the arrows point and ignore how long they are.

Measure the arrow, then divide it out

The heist’s arrow goes 4 along and 3 up. That is a right-angled triangle with sides 4 and 3, and the long side, the arrow itself, is 5: the 3, 4, 5 triangle from school. Look at how you get the 5: 4×4 + 3×3 = 25, and the square root of 25 is 5. That 4×4 + 3×3 is the heist dotted with itself. So an arrow’s length is the square root of its dot product with itself, and that works for three slots, or 768, the same as for two.

With all three slots back, the heist is √(16 + 1 + 9) = √26 ≈ 5.099 long and the caper is √(25 + 0 + 16) = √41 ≈ 6.403.

Now divide the agreement by both lengths:

heist with caper:    32 / (5.099 × 6.403) = 32 / 32.65 = 0.98
heist with weepie:    8 / (5.099 × 5.099) =  8 / 26    = 0.308

Size is gone and only direction is left. The answer always lands between 1 (same direction) and -1 (opposite), with 0 for unrelated. Heist 2 against the caper also gives 0.98, the same as the original, which is the whole point. This number is the cosine similarity. Written the short way, once you know what it says:

cos(a, b) = (a · b) / (|a| × |b|)        |a| is the length of a

A neuron is one viewer

The next lesson draws a neuron: inputs on the left, a weight on each line, a Σ in a circle, one output on the right. It looks like new machinery. It is the viewer you already met.

Follow “you” watching the heist:

action 4romance 1comedy 3 × 2 = 8× −1 = −1× 1 = 3 add: 10mood: −4= 6 6 > 0,out goes 6 the film = x1, x2, x3your taste = the weights wadd = Σ, mood = bzero rule

The film’s three numbers come in on three lines. Each line multiplies by how much you care about that thing: 2 for action, -1 for romance, 1 for comedy. The circle adds what arrives, 8 - 1 + 3 = 10, then adds your mood, -4 after a long day, to get 6. Then the zero rule: 6 is not negative, so 6 goes out. Had it come to -1, a zero would go out, and you stay home.

That is a whole neuron. In the board’s labels, x1, x2, x3 are the film’s numbers, the w on each line is your taste, the Σ is “add them up”, b is your mood and the activation is the zero rule. A neuron does not think. It holds one taste and asks one question: how much does what is coming in agree with it?

A layer is a row of these viewers watching the same film at once. Each row of the matrix is one viewer’s taste, so each row is one neuron. The romantic and the comic are two more, and the three together gave the [6, 0, 7] you worked out.

How big a real cinema is

A layer’s table has one row per viewer and one column per slot in the film. The film must have exactly as many slots as the table has columns, or some taste has nothing to multiply. One number comes out per row. And the work is one multiply-and-add per seat in the table: our 3 by 3 table is 9.

GPT-2 small, the model What a Neural Network Is measures, has layers that take 768 numbers in and give 3,072 out: 3,072 viewers, each with a taste of 768 numbers. That is 768 × 3,072 = 2,359,296 multiply-and-adds, for one layer, for one word. A model reads a page as hundreds of words, through dozens of layers like that.

You will also see a layer written the other way round, with each viewer as a column instead of a row (x @ W instead of W @ x). It is the same table turned on its side, and every sum inside is the same. When the next lesson writes it that way, nothing new is happening.

Why Google’s chip is a grid

Now the chip from the start of this lesson has a shape that makes sense. Its heart is a 256 by 256 grid of little multiply-and-add cells, 65,536 of them: a cinema of 256 viewers with 256 tastes each, every one of them doing its multiply in the same tick. The tastes sit still in the cells, the film’s numbers flow across, and a row of 256 totals comes out the far side.

It ticks 700 million times a second. Count a multiply and an add as two operations: 65,536 × 2 × 700,000,000 = 91.75 trillion a second, the paper’s quoted peak of 92 trillion (for whole numbers 8 bits wide, not decimals).

Where the cinema shows up next

  • Words are films. Tokens & Embeddings describes every word as a vector, like the films here, except the numbers are learned and there are hundreds of slots with no names. “Which words are alike” is the cosine you just did. Its toy vectors give king · queen = 0.81 − 0.09 + 0.64 = 1.36 and king · banana = 0: banana has nothing in any slot where king has something. Searching documents for an answer, the heart of RAG (Retrieval-Augmented Generation), is that cosine run against a whole library.
  • In attention, every word is a viewer and a film at once. In Attention & the Transformer, each word carries a taste, called its query (what it is looking for), and a description, called its key (what it offers). How much one word cares about another is the first word’s query dotted with the second word’s key. Stack the queries as rows and the keys as columns and the whole sheet of scores is one matrix multiply, written Q @ K.T. On that lesson’s hand-picked numbers, the word sat scores the four words of “the cat sat down” 1, 4, 3, 0: it cares most about cat. That lesson turns those scores into shares of 7%, 62% and 31%, and turning scores into shares is the next lesson, The Maths Floor, Part 2: Probability, Softmax and Temperature.

All of it in code

Every sum above, in numpy. @ is the dot product, or a matrix multiply when one side is a table. Change a number and run it again.

Show the working as code
import numpy as np
# films as [action, romance, comedy], scores 0-5 (made up)
heist  = np.array([4, 1, 3])
caper  = np.array([5, 0, 4])
weepie = np.array([0, 5, 1])
heist2 = heist * 2                       # the sequel: everything doubled

# the sequel problem: the dot product grows with size
print("heist  . caper:", heist @ caper)
print("heist2 . caper:", heist2 @ caper)

# length, then the cosine: direction alone
length = lambda v: float(np.sqrt(v @ v))
cosine = lambda a, b: float(a @ b) / (length(a) * length(b))
print("lengths heist, caper:", round(length(heist), 3), round(length(caper), 3))
print("cosine heist, caper :", round(cosine(heist, caper), 3))
print("cosine heist2, caper:", round(cosine(heist2, caper), 3))
print("cosine heist, weepie:", round(cosine(heist, weepie), 3))

# a layer: three viewers (rows) are three neurons
W = np.array([[ 2, -1, 1],               # you
              [-1,  3, 0],               # the romantic
              [ 0,  0, 2]])              # the comic
b = np.array([-4, 0, 1])                 # each viewer's mood
print("W @ heist + b      :", W @ heist + b)
print("after the zero rule:", np.maximum(0, W @ heist + b))
print("turned on its side :", heist @ W.T + b)
heist  . caper: 32
heist2 . caper: 64
lengths heist, caper: 5.099 6.403
cosine heist, caper : 0.98
cosine heist2, caper: 0.98
cosine heist, weepie: 0.308
W @ heist + b      : [ 6 -1  7]
after the zero rule: [6 0 7]
turned on its side : [ 6 -1  7]

Try it

Change your own taste and see which film wins, then give the cinema a fourth viewer:

Show the working as code
import numpy as np
films = np.column_stack([[4,1,3], [5,0,4], [0,5,1]])   # heist, caper, weepie
W = np.array([[ 2, -1, 1],
              [-1,  3, 0],
              [ 0,  0, 2],
              [ 1,  1, 1]])      # a fourth viewer who likes everything equally
print(W @ films)
[[10 14 -4]
 [-1 -5 15]
 [ 6  8  2]
 [ 8  9  6]]

A fourth row in the table is a fourth number out: the output got longer because the table got taller, and the input did not change. Now set that viewer to [0, 0, 0] and predict the row before you run it.

Go deeper

Retrieval practice

8 questions. Answer each one before you open it.

What makes a list of numbers a vector rather than just a list, and what are the two ways to see one?

Each position has a fixed meaning, always in the same order: slot two of a film vector is always romance. Read it and it is a description of a thing. Draw it and it is an arrow from the corner to a point. Films of the same kind point the same way.

Work out the dot product of [4, 1, 3] and [2, -1, 1] by hand. What does the answer mean?

4×2 + 1×(-1) + 3×1 = 8 − 1 + 3 = 10. It is how much the two lists agree: big and positive means they point the same way, near zero means unrelated, negative means they point apart. Here a heist film against a taste that likes action and comedy scores 10.

Why does the heist film score 32 against the caper but only 8 against the weepie, and why is the raw dot product not the whole story?

Heist [4,1,3] and caper [5,0,4] are both high in action and comedy, so the big slots multiply together: 20 + 0 + 12 = 32. The weepie’s big slot is romance, where the heist has 1, so only 0 + 5 + 3 = 8. But a dot product also grows with size, so a film with doubled scores would “agree” more with everything. Dividing by both lengths gives the cosine, direction alone: 0.98 against 0.308.

What does multiplying a matrix by a vector actually do, step by step?

One dot product per row: take row 1, dot it with the vector, write the answer. Then row 2. And so on. Three viewer rows times one film vector gives three numbers, [10, -1, 6]. The film goes in described by what is in it and comes out described by who likes it.

A table has 3,072 rows and 768 columns. What length of vector can it take, what comes out, and how many multiply-and-adds does it cost?

It takes a vector of length 768 (the width must match), returns one number per row, so 3,072, and costs 768 × 3,072 = 2,359,296 multiply-and-adds. That is one GPT-2-small-sized layer, for one token.

Write one layer as a formula and say each part in plain words.

y = activation(W x + b). Dot the input x with every row of the weight table W. Add each row’s fixed extra, the bias b. Then apply the rule, for ReLU “negative becomes zero”. With the viewers: [10, -1, 6] + [-4, 0, 1] = [6, -1, 7], then [6, 0, 7].

Why did Google build a chip that can only multiply and add, and how big was its grid?

A 2013 projection said that if people used voice search for three minutes a day on neural networks, Google’s datacenters would have to double on ordinary processors. Nearly all of that work is multiply-then-add. So they built the TPU around a 256 × 256 grid, 65,536 multiply-and-add cells working at once. They had it in datacenters within 15 months, from 2015.

Where does the dot product appear in embeddings and in attention?

In embeddings, similarity between two token vectors is a dot product divided by their lengths, the cosine: king · queen = 1.36, king · banana = 0 on the toy vectors. In attention, one word’s score for another is its query dotted with the other’s key, and all the scores at once are the matrix multiply Q @ K.T; sat’s row comes out 1, 4, 3, 0, highest on cat.

Neural networks end to end, and the PyTorch that runs them · also Non-linearity: why a hundred layers can equal one

Review AI

Saved in this browser, and to your account when you sign in.