✖

How ChatGPT and artificial intelligence work: the maths inside

How does ChatGPT work? The language model that this artificial intelligence runs on has no encyclopaedia of ready-made answers inside it. It does essentially one thing: it looks at the text it has so far and estimates how likely each possible continuation is. It picks one piece of text, sticks it on the end and repeats the whole process, again and again, until the answer is finished. This repeated guessing of the next word is how a poem, a recipe for shepherd’s pie and the steps for solving a quadratic equation come about: the last one appears in texts so many times that the model can imitate it.

It sounds simple, and there really is no magic in it, just secondary-school maths: vectors, the scalar product (dot product) and probability. This part starts a series that takes it apart piece by piece.

How artificial intelligence works step by step

A computer cannot calculate with words, only with numbers. So before the model can even start on the sentence “The cat sat on the”, it has to turn it into numbers. The whole journey looks like this:

A diagram in five steps from left to right: the text “The cat sat on the”; five tokens one below another, The, cat, sat, on, the, each with its number; from each token a row of cells; a neural network; and columns of probabilities for the next word, the highest being “mat” (in red). A red dashed arrow leads from the result back to the text, labelled “+ mat” A diagram in five steps from left to right: the text “The cat sat on the”; five tokens one below another, The, cat, sat, on, the, each with its number; from each token a row of cells; a neural network; and columns of probabilities for the next word, the highest being “mat” (in red). A red dashed arrow leads from the result back to the text, labelled “+ mat”

  1. A program called a tokenizer chops the text into tokens, pieces of words. Each token has its own number in the tokenizer’s list.
  2. Each token is replaced by a vector, a long list of numbers that somehow captures its meaning.
  3. The vectors pass through a neural network: an enormous amount of multiplying and adding.
  4. At the end comes a probability for every token the model knows: how well it would fit as the next one.
  5. One token is chosen and added to the text, and the whole round starts again.

The tokens and numbers in the picture are real: this is exactly how the tokenizer of GPT-4o splits the sentence. The shades of the cells and the lengths of the columns are only for illustration.

Word by word

It is worth watching the last step a few times in a row. For simplicity we will now talk about whole words, even though the model really chooses tokens.

Three rows below each other. “The cat sat on the” and to the right three candidates with columns: mat (the longest, in red), sofa, floor. “The cat sat on the mat” with candidates and, for, all. “The cat sat on the mat and” with candidates looked, purred, waited. The chosen word is always in red and in the next row it is already part of the text Three rows below each other. “The cat sat on the” and to the right three candidates with columns: mat (the longest, in red), sofa, floor. “The cat sat on the mat” with candidates and, for, all. “The cat sat on the mat and” with candidates looked, purred, waited. The chosen word is always in red and in the next row it is already part of the text

The numbers in the picture were not measured on a real model; they only show the principle. Notice that the model never writes a whole sentence in advance and has no plan of where it is heading. An answer of a thousand words is simply a thousand guesses of one next word, one after another.

How come ChatGPT does not answer the same question the same way every time? It does not have to choose the most probable word. Most of the time it draws among the candidates, in such a way that a word with a higher column comes up more often than a word with a lower one. How the output of the network turns into probabilities, and how the drawing can be sharpened or blurred, is the subject of the part on the softmax function.

Tokens: pieces of words

Why does the model not work with whole words straight away? There are simply too many of them: Czech, for instance, has each word in many forms, and on top of that there are names, typos, numbers, programming code and emoji. With a separate entry for every word, the model would never be finished. So it splits text into tokens, pieces from which anything can be assembled. Common words are a single token each, others are put together from several pieces (the GPT-4o tokenizer, for instance, builds “Tokenization” from “Token” and “ization”), and in the worst case the text falls apart into individual bytes.

The list of all tokens is called the vocabulary. The tokenizer that OpenAI used for GPT-4 (2023) has over 100,000 of them, and the one for GPT-4o (2024) and newer models has about 200,000. Nobody picked these pieces by hand: they came about automatically, when the most frequent pairs of characters in a huge amount of text were gradually glued together into larger units.

That text, however, was most likely mostly English, so English comes out of this considerably better. Look at how the GPT-4 tokenizer splits one question in English and in Czech (the Czech “Jak funguje umělá inteligence?” means “How does artificial intelligence work?”):

Two rows of coloured rectangles. The English sentence How does artificial intelligence work? split into 6 tokens: each word is one token and the question mark is the sixth. The Czech sentence Jak funguje umělá inteligence? (the same question) split into 10 tokens: Jak, fung, uje, um, ě, l, á, intelig, ence, question mark Two rows of coloured rectangles. The English sentence How does artificial intelligence work? split into 6 tokens: each word is one token and the question mark is the sixth. The Czech sentence Jak funguje umělá inteligence? (the same question) split into 10 tokens: Jak, fung, uje, um, ě, l, á, intelig, ence, question mark

The space between words is not a separate token, by the way: it belongs to the piece that follows it, so the second token of the Czech sentence is in fact a space followed by “fung”. In the picture it is replaced by a larger gap. The English words “artificial” and “intelligence” are whole entries in the vocabulary, whereas the Czech “umělá” (“artificial”) falls apart into four pieces. A longer sentence turns out much the same: “The cat is sitting on the window and looking out.” has 11 tokens, while the Czech “Kočka sedí na okně a dívá se ven.” (the same sentence) has 17. The newer GPT-4o tokenizer is a little kinder to Czech and splits the Czech sentences into 9 and 14 tokens; the English counts do not change.

This is not just a curiosity. When models are used through another program, they are paid for by the token, and the model can also see only a limited number of tokens at once, the so-called context. What does not fit in it, the model cannot see at all when it estimates the next word. GPT-3 from 2020, for example, had a context of 2,048 tokens, roughly 1,500 words in English, so a few pages of text; today’s models can handle much more. So Czech fits less text into the same context, and the same answer costs more in it.

Word vectors

The number of a token, say 9059 for “cat”, is only its position in the list and says nothing about meaning: tokens 9059 and 9060 need not have anything in common. So the model replaces each token with a vector, a list of many numbers, right at the start. In GPT-3, each such vector had 12,288 numbers.

You can imagine a vector as an arrow or a point, only not in a plane with two coordinates but in a space with thousands of dimensions. Nobody can picture such a space, but you calculate in it exactly the same way as with vectors at school: you add component by component, and the length comes from Pythagoras’ theorem.

Nobody invented the numbers in the vectors either. The model sets them itself during learning, when it tries to guess the next word as well as possible on a huge amount of text. It turns out that words with a similar meaning end up close to each other: “cat” next to “dog”, “Monday” next to “Tuesday”, “London” next to “Manchester”. No wonder: words that appear in similar sentences have to be predicted similarly, and so they get similar numbers.

King − man + woman ≈ queen

The most famous example comes from 2013, from the Czech computer scientist Tomáš Mikolov, and became well known together with the word2vec method, which he developed with his colleagues at Google. Their word vectors had 300 numbers. If we take the vector of the word “king”, subtract the vector “man” and add the vector “woman”, we get a vector to which the nearest of all words is “queen” (the nearest would otherwise be “king” itself, so the words we plugged in are not counted):

king − man + woman ≈ queen

This can be drawn in a plane. The coordinates in the picture are made up, real vectors have hundreds of dimensions, but the principle is the same:

Four points in a plane: man (2, 1), woman (1, 3), king (6, 2), queen (5, 4), with grey arrows to them from the origin. The red arrows from man to woman and from king to queen are equally long and parallel, and so are the blue dashed arrows from man to king and from woman to queen. Together they form a parallelogram Four points in a plane: man (2, 1), woman (1, 3), king (6, 2), queen (5, 4), with grey arrows to them from the origin. The red arrows from man to woman and from king to queen are equally long and parallel, and so are the blue dashed arrows from man to king and from woman to queen. Together they form a parallelogram

The red arrow from man to woman is the difference of the vectors woman − man, a kind of “direction of femaleness”. If we attach the same arrow to the king, we arrive at the queen. In the picture, man is m→=(2,1), woman is w→=(1,3), king is k→=(6,2), and so

k→−m→+w→=(6−2+1,2−1+3)=(5,4),

which is exactly the coordinates of the queen. With real vectors it comes out only approximately, hence the wavy sign ≈ instead of the equals sign. Pairs such as Paris and France, or Rome and Italy, behave the same way: the difference “capital city minus country” points in roughly the same direction.

Cosine similarity

But how do you tell that two vectors are “close”? What decides is the angle between them. Its cosine is 1 for arrows in the same direction, 0 for perpendicular ones and −1 for opposite ones. It is calculated from the scalar product:

cos⁡φ=u→⋅v→|u→|⋅|v→|

In artificial intelligence this number is called the cosine similarity, and many search engines and chatbots use it to find texts that fit your question, only with thousands of components instead of three. If you would rather not calculate, you can skip the rest of this section and carry on with the section about the network.

Let’s try it on small vectors with three components. Say the first number tells how much the word is “animal”, the second how much it is “at home” and the third how much it “drives”. In real models the individual numbers cannot be named so neatly; this is just an illustration. Our three words get the vectors: cat c→=(4,3,0), dog d→=(4,2,1) and car a→=(0,1,4).

We start with the cat and the dog. With three components you calculate just as in a plane, with one more term. Scalar product: we multiply the corresponding components and add the results:

c→⋅d→=4⋅4+3⋅2+0⋅1=22

The magnitude of a vector is the square root of the sum of the squares of its components:

|c→|=42+32+02=25=5

|d→|=42+22+12=21≈4.583

We substitute into the formula:

cos⁡φ=225⋅4.583≈0.96

The cosine similarity of the cat and the dog came out at about 0.96, almost one. This corresponds to an angle of roughly 16° (found with the inverse cosine), so the arrows point almost the same way.

And now the cat and the car:

c→⋅a→=4⋅0+3⋅1+0⋅4=3

|a→|=02+12+42=17≈4.123

cos⁡φ=35⋅4.123≈0.15

This time it came out at about 0.15, an angle of around 82°. The arrows are almost perpendicular: a cat and a car do not have much in common. That fits.

Why the angle and not the plain distance between points? The length of a vector also carries information unrelated to meaning, whereas the angle ignores it and follows only the direction.

What happens inside the network?

The token vectors then travel into a neural network. There is nothing mysterious in it, just an enormous amount of multiplying and adding of numbers called parameters, or weights: they determine how much weight each number carries in the resulting sum. GPT-3 had 175 billion of them. How many parameters GPT-4 and the newer models that ChatGPT runs on have, OpenAI does not disclose.

At the start of learning, all the parameters are random and the model babbles nonsense. Then it is given a piece of real text, has to guess the next token, and according to how badly it got it wrong, every parameter is nudged a little in the right direction; that direction is calculated using a derivative (the part on gradient descent is about that). GPT-3 learned like this on roughly 300 billion tokens of text. Nobody tells the model what a cat is or what a verb is; everything it “knows” is written in those numbers.

In doing so, the model learns to estimate what is probable, not what is true. Most of the time it comes to the same thing, because there are more true sentences in texts than false ones. But when the model does not know something, it writes something that only looks like the truth; this is called a hallucination. Its output therefore needs to be checked; in maths, a program called Lean can do that for a human.

The rest of the series

Each step from the first picture gets a part of its own, with formulas and worked examples:

  • neural network: how one neuron adds up and why there have to be more layers of them,
  • gradient descent: how the network learns and what this has to do with derivatives,
  • softmax: how numbers turn into probabilities and why the model answers differently every time,
  • transformer and attention: how the model knows what “it” refers to in a sentence,
  • AI hallucinations: why probable is not the same as true.

Chapters: How ChatGPT and artificial intelligence work: the maths inside, Neural network: what it is and how it computes, Gradient descent: how a neural network learns, Softmax: how numbers become probabilities and what temperature is, Transformer and attention: how a model knows what a word refers to, AI hallucination: why artificial intelligence confidently writes falsehoods