An explorable explanation

From noise to unbeatable: how a neural network learns

A network teaching itself tic-tac-toe in your browser.

The picture above is a complete neural network. Hover over any part of the picture for details.

At the top are 18 inputs representing the board position, each a 0 or a 1. Below them are two layers of neurons, 64 drawn as small tiles and 32 as circles. At the bottom comes a single number, the rating: how good the network thinks the position it is reviewing is. The lines are connections between layers. Each connection carries a number called a weight, and adjusting the weights is how the network learns.

The largest AI models work on the same principles. Each neuron multiplies its inputs by their weights, adds up the results and squashes the total into a fixed range, or bends it some other way. Layers feed each other until the final number comes out. Training means nudging the weights, a little at a time, whenever that number turns out to be wrong.

Real networks have billions of weights, far too many to look at. This one has 3,329, few enough to see every one. Our example is tic-tac-toe, a game small enough that we can always know the best move to grade the network as it learns.

Right now its weights are random and it has never seen a game. Play it on the board on the rightat the bottom of the screen by clicking a square. That board drives the whole page: the network picture above and every step below show the game as it stands, so each move you make changes them all. The numbers in the empty squares show how it rates each of your possible moves, and the ring marks the one it would play in your place. A ✓ marks the moves a perfect player would make.

You'll probably win. Currently it only knows one thing: when a move wins on the spot, it almost always takes it, because a finished game scores itself: a win counts +1, whatever the network thinks. That score is all it will ever learn from. On an untrained network everything else is guesswork, though it doesn't play randomly: its starting weights give it favorite squares, and it plays them every time. Reload the page and you will get a different network with different favorites. Keep playing as you read.

How it works

Step 1: What the network sees

The network doesn't see × and ○, only numbers. Nine of them say which squares hold pieces of the player who just moved, and nine say which hold the opponent's: 1 for a piece, 0 for none. Play a move and watch them change.

Because it always sees the board from the side of whoever just moved, one network can play both × and ○. This isn't the most compact way to describe a board. But it is the easiest for us to read, and the game is simple enough that we don't have to optimize.

Step 2: How it picks a move

What the network returns is a single number, the rating: how good a position is for the player who has just moved into it, meant to run from −1 (a sure loss) to +1 (a sure win). So the network doesn't rate the board in front of it, but the boards its moves would lead to. To choose a move, it imagines each possible move, rates the position that move would create, and picks the highest. Those ratings are the numbers on the board, green for good and orange for bad. The ringed square is its choice, the move it would make in your place.

Untrained, the ratings are noise, except for moves that end the game. Those are scored definitively: three in a row is +1, whatever the network thinks. That's why it rarely misses a win. It still can, because nothing stops its own ratings from going above +1. Everything else, even blocking your three in a row, it has to discover.

Step 3: One neuron

Between the inputs and the output sit the two layers of neurons. Let's follow one move through them, the one the network would make in your place right now. Point at another empty square on the board, or click one on the small board in the card below, to follow that move instead, or try a position where something is at stake:

A first-layer neuron has one weight for each of the 18 inputs. Below, its weights are drawn as two small boards, one for the mover's pieces and one for the opponent's. A green weight is positive: a piece on that square pushes the neuron's output up. An orange weight pushes it down. A square without a piece counts as 0, so only the weights under a piece matter.

The neuron adds up the weights under the pieces, plus a fixed offset of its own called the bias (no relation to the bias people worry about in AI answers), which makes the neuron easier or harder to set off. Biases start at 0, so in an untrained network they add nothing yet. Training adjusts them along with the weights.

Last, the neuron squashes the total into the range −1 to +1, following the curve in the card above. A total near 0 passes through almost unchanged. A large total, positive or negative, is flattened toward +1 or −1, so piling on more evidence makes less and less difference.

Why squash? Without it, each piece could only push the rating up or down by a fixed amount, wherever the other pieces are. But in tic-tac-toe a piece means different things depending on its neighbors. One of your opponent's pieces in a corner is harmless. Add a second one in the same line, with the third square empty, and together they are a threat that must be blocked. The pair matters far more than its two pieces added up, and a plain sum can't express that. Nor do more layers help on their own: a sum of sums is still one big sum, however many layers deep.

Squashing makes each neuron work more like a switch. Below a certain total it stays near −1, above it near +1, and only in between does it respond gradually. The bias decides where that switch point is, and that is what it is for. Take a neuron with positive weights on two squares. Without a bias, one piece on either would already switch it on. A negative bias can hold it off until both are there, and then the neuron answers a question about a combination: are both there? The next layer adds up switches like these, so it can react to combinations of patterns, not just single squares. That is what makes stacking layers worthwhile.

The small tile next to the neuron's number is this neuron as it appears in the network picture, at the top of the page and in Step 7: the same two boards of weights in miniature, framed in green when its output is positive and orange when it's negative. With random weights the tiles are noise. Training is what gives them meaning.

Step 4: Neurons of neurons

The 32 second-layer neurons work the same way, but their inputs are the 64 outputs of the first layer, not the board. So they combine patterns rather than squares. A first-layer neuron can learn to spot something simple, such as a threat on one particular line: two of the opponent's pieces with the third square empty. A second-layer neuron can then combine several of those into "a threat on any line", or "two threats at once", a fork that can't be stopped. I couldn't get a single layer to learn ideas like these (see Too shallow in the appendix). In practice a trained network is rarely this tidy. An idea tends to be spread across many neurons, and most neurons mix several ideas. In the network picture the second-layer neurons are the small circles.

Step 5: Down to one number

The rating is a weighted sum of the 32 second-layer outputs, plus a bias, without squashing. Think of it as a vote. Each neuron's output times its weight is its vote, positive for "good for the mover" and negative for "bad". The total is the rating.

Step 6: One number per move

Here are all current options side by side, each rated by one full run through the network. Click any of them to follow it through the steps above.

Untrained, the pick is arbitrary. It often lands on a good move anyway, because many positions have several equally good moves. When only one move will do, like a block, finding it is luck.

Step 7: The whole network

Here is everything at once: the inputs at the top, the 64 first-layer tiles, the 32 second-layer circles and the rating. The lines are the weights between layers, green for positive and orange for negative, thicker for stronger. Hover over any part for its numbers.

How it learns

So far the weights have stood still: a position goes in, a rating comes out, and with random weights that rating is noise. Training is how the weights change, and the rest of this page is about that.

Step 8: Learning by playing itself

The network is never shown which moves are good. It trains by playing against itself, and the only feedback is how each game ends. The result is scored for the player who made the last move, and in tic-tac-toe that move can only win or draw: +1 or 0, as we saw in Step 2. A loss is the same win seen from the other side, so the loser's last position is worth −1. The trick is to turn that one result into a lesson for every move along the way.

The key idea: a position is worth what your opponent's best reply leaves you. Say I move into a position the network rates +0.6 for me. Now it's my opponent's turn, and the network's best move for them is rated +0.9, for them. So my position was really worth −0.9 to me, and the network was too optimistic. This will nudge every weight slightly in the direction that would have rated my position closer to −0.9. Working out which way to nudge each weight is called backpropagation: the error is passed backward through the layers, and each weight gets its share of the blame.

Only the final moves are checked against how the game actually ended. Every earlier move is checked against the network's own opinion one move later. Over thousands of games, the truth works its way back from the end of the game to the opening. This is called temporal-difference learning. In the early 1990s Gerald Tesauro used it to teach a program called TD-Gammon to play backgammon close to world-champion level.

One more ingredient is curiosity, or exploration in the jargon. A network that always played its favorite move would only learn about the games it already likes. So in training it plays the first few moves of each game at random, and after that makes random moves half the time at first, tapering off to one in ten. The small board beside the counter below shows the latest game it played against itself, with its random moves faded.

Training happens out of view, hundreds of games a second. The board shows what it has learned so far. Every few hundred games a referee tests it: how many games it would lose against every possible opponent, and how often its move is wrong. Step 9 explains how. Train it with the button below, 500 games to start with:

The chart counts how many games it would lose against every possible opponent. Now play it again, or .

Taking a win came free from the start. What it learns first is blocking, and by 2,000 games it nearly always blocks. Train on to 2,000, 5,000 and 20,000 games, and test it between steps. Try it in a tight spot: . A ✓ marks perfect moves. The lab has a timeline of how its rating of each move changed during training.

Step 9: The referee

To grade the network we need the right answers, and tic-tac-toe has them. The game is so small that an ordinary program, with no learning involved, can play out every possible continuation and find the best move in any position. A game where that has been done is called solved. Tic-tac-toe has 255,168 possible games, and a laptop can check them all in a fraction of a second.

Every few hundred games, training pauses for a two-part exam. The first part plays the network against every possible opponent, as × and as ○: some 550 to 950 different games, depending on how it plays. When it loses none of them, nothing can beat it. In my runs it first got there somewhere between 5,000 and 15,000 games, and then still slipped now and then by a game or two as it kept adjusting. By around 20,000 games the slips become rare.

The second part is stricter. It goes through all 4,520 positions that can come up in a game and counts those where the network's move isn't a perfect one. Even an untrained network gets about four in five right. Half of all positions offer an immediate win, which the game scores for it, and in many of the rest several moves are equally good. Where no win is on offer, it does no better than picking at random. The ones it misses are the ones that matter: the block, the trap, the win. Missing a forced win counts as a mistake even if the game still ends in a draw.

So how can an unbeatable network still make wrong moves? Because the second part also tests it on positions it would never get into. From the first move, whatever its opponent does, the network steers every game into only about 500 of the 4,520 positions, and in those it never loses. Drop it into the middle of a game someone else started, though, and it can still go wrong. The puzzle buttons do exactly that, so they can catch it out. Most of these mistakes are the harmless kind: settling for a draw where a win was there for the taking.

The last chart shows how much the weights are still changing. They swing wildly at first and settle, both because there is less to correct and because training gradually turns down the size of each nudge.

Putting it together

That is the whole recipe. Eighteen numbers describe the board. Neurons weigh them, add them up and squash the result, and a second layer combines what the first one found. One number comes out, and the move with the best number gets played. Then the network plays itself, game after game, and after every move nudges its weights toward its own rating one move later, with the result of the game as the only fixed truth. Nothing in it knows the rules of good play. After 10,000 to 20,000 games, nothing can beat it, give or take the odd slip.

The AI models in the news are built from the same parts, scaled up a hundred million times and trained mostly on text instead of games. The appendix below goes further: a lab to try things in, how this network fails, what decides a network's shape, and how the ideas carry over to language models.

I wrote this to understand neural networks better myself, from first principles. If it helps you do the same, all the better.

Appendix: going further

The lab

Everything in one place, plus the settings. Change a setting and a fresh network starts training, with the previous run kept on the charts as a dashed line. Watch slows training down so you can follow the games.

Three ways to fail

The setup you just trained wasn't the first one tried. Each of these went wrong while this page was being built, and each is a lesson about neural networks in general. You can repeat all three in the lab above.

1. Too timid

With few random moves, the network only studies the games it already likes. It never learns that moves it rates badly might be good, and about half of all positions never come up. It gets stuck well short of perfect.

2. Too shallow

With one layer of neurons instead of two, it stalls with about 3% of its moves wrong and keeps losing a few games. To check that the problem is the shape of the network and not the training, I skipped self-play and taught it the best move for every position directly. One layer still couldn't learn them all, at any size I tried. Two layers learned them in minutes. And it isn't just size: a single layer of 170 neurons, as many weights as the two-layer network, still lost 23 games after 20,000 games of training. What one layer can't do well is combine. "A threat on any line" or "two threats at once" are combinations of simpler patterns, and combining is what the second layer is for.

3. Forgetful

As random moves become rare, the network mostly sees sensible games and slowly forgets the odd positions it met early on. The fix is a memory: it keeps the last 50,000 positions it has seen and, after every move, revisits four of them at random. DeepMind used the same trick in 2015 to teach one network design to play dozens of Atari games. Without it, this network learns more slowly, and long after first becoming unbeatable it keeps slipping back, by many more games than with memory.

How deep, how wide?

Each layer of neurons (the rating at the bottom doesn't count as one) combines what the layer before it found. So depth is about how many levels of combination a task needs, and width is about how many patterns each level has to keep track of. Tic-tac-toe has about three levels: single squares, then lines and threats, then combinations of threats, such as a fork. I couldn't get one layer to reach the third level. Two can, and I'd expect a third to add little here.

One way to think about it: harder problems have taller stacks of ideas. In chess, pieces make attacks, attacks make tactics like pins and forks, and tactics make plans. In language, words make phrases, phrases make sentences, and sentences make arguments. That is why networks for such tasks have dozens of layers.

In theory a single layer can imitate anything if it is wide enough, but it may need absurdly many neurons to do what a few layers do with few. In practice, as far as I can tell, nobody calculates the right shape. It is found by experiment, much like the three failures above: try a shape, measure, adjust. Bigger isn't free, either. Every extra weight has to be learned from examples, so an oversized network can need far more of them.

What the neurons learn

Hover over the tiles in the network picture of a trained network and some may show patterns you can read. In one of my runs, 15 of the 64 first-layer neurons were mostly about the center, often called the strongest square in the game, and more than half were organized largely by whole rows and columns. Others mix several patterns into something hard to name, and even the clear ones only hint at what a neuron does in combination with the other 95. That's a small taste of why large networks are so hard to understand from the inside.

moveropponent

Who holds the center?Neuron 6. Pulled down when the mover holds the center, pushed up when the opponent does.

moveropponent

RowsNeuron 25. The mover's top and bottom rows push it up and the middle row down. For the opponent's pieces it's the other way round.

moveropponent

Hard to nameNeuron 35. Up when the mover holds the center and the opponent the edges, down for most else. A pattern, but what does it detect?

Three first-layer neurons from one training run (20,000 games, unbeatable). Green weights push a neuron up, orange push it down, stronger colors more. Every run finds its own.

An old idea

In 1961 Donald Michie built MENACE, a tic-tac-toe player made of 304 matchboxes. There was one box for each position it might face, filled with colored beads, one color per possible move. To move, he drew a random bead from the box. After a win he added beads of the colors played, and after a loss he removed them. It learned to play well, with no computer at all.

MENACE memorized: every position had its own box. This network has no slot per position. Every weight is shared across many positions, so what it learns from one changes how it rates others. It has to find general rules, and that is what lets the approach scale. No table could hold every position in chess, which has around 1044 of them, let alone Go, which has far more. Yet in 2017 AlphaZero taught itself both with a close relative of the same recipe: self-play, a network that rates positions, and the result of each game as the only teacher. It used a vastly bigger network, plus a search through possible moves.

From tic-tac-toe to language models

The core parts carry over to the AI models you use every day. What changes is the scale, and where the lessons come from.

  • Inputs. Here, 18 zeros and ones. A language model turns each piece of a word into a list of a few thousand numbers, so a prompt of a few sentences becomes hundreds of thousands of numbers.
  • Neurons and layers. The same multiply and add, with a bend like the squash, stacked dozens of layers deep. One addition, called attention, lets each word take the other words into account.
  • Output. This network rates each empty square and picks the best. A language model scores every possible next piece of a word and picks among the best.
  • Learning. The same backpropagation. The lessons come first from predicting the next word in huge amounts of text, then, much like here, from feedback on whole answers.
  • Weights. 3,329 here, hundreds of billions there. That's one reason nobody can read their tiles.

Further reading