{mvGPT}
  • Episode 28
  • 23 min

Attention heads in our GPT, seen and tested

We look inside our agent while it copies a name into a query, with each head's attention written out, the logit lens, and a page of our own, then turn the heads that look at the name off to see what they do.

Watch on YouTube

Open in Colab

In this episode, we look inside our GPT while its graph role copies a name from its task into a Cypher query. We write attention out by hand to keep each head's weights, put the logit lens on the residual stream to see each layer's guess at the next token, and build a page of our own to look at all 144 heads on a prompt. A head in the last layer puts 92 percent of its attention on the name in the task, and the name shows up in the last layer alone. For the okapi, that head looks at the right token, and the model can't write it inside the quotes. Then we turn the heads that look at the name off, against random ones, and find that they do more than copy.

Topics: Architecture

The code

Each step on screen is a tag in the code's repository. The code at the end of the episode is ep028/end.

  1. 2:30ep028/step-1Attention, written outBrowseChanges
  2. 8:28ep028/step-2A page to look withBrowseChanges
  3. 13:26ep028/step-3Heads turned offBrowseChanges
  4. 20:41ep028/step-4Heads turned offBrowseChanges

Transcript

Intro

0:00 Hello and welcome back to episode twenty-eight, where we look inside our model while it copies a name from its task into a query, at what each of its attention heads looks at, and what each layer would write. Let's begin with a quick look at where we're going to be by the end of the episode.

0:17 By the end of today, we look at our agent's graph role as it starts the king penguin's name in its query. A head in its last layer puts almost all of its attention on the name in the task, and the logit lens shows King in the last layer, and no layer before it.

0:32 On the website of the series, you can find more information about the project. The code is open source on GitHub, tagged at each step of each episode, so that you can follow along, and the docs get a page on looking inside the model today. And each episode has a page here as well, with its chapters and its code.

0:50 Now, before we get to today's work, let's quickly go over the last two episodes. In episode twenty-six, the agent's graph role copied the okapi's name wrong into its query, and a mask on the logits kept the name to the task's words. Last time, a draft guessed the next few tokens, and the agent checked them in one pass, about one point five times faster on its tasks. Both came back to copying: the name, from the task into the query. Today, we look inside the model while it copies, at which tokens each attention head looks at, and what each layer would write, and then we test what we see.

1:26 Today, we write attention out by hand, so that we can keep each head's weights. We put the logit lens on the model, which shows what each layer would write next. We build a page of our own to look at all one hundred and forty-four heads on a prompt, and look at the king penguin and the okapi. And we turn the heads that look at the name off, to test what they do. All right, let's get started with the attention weights.

Attention, written out

1:53 A head's attention, from episode one, is a softmax of q, k transposed, over the square root of sixty-four, with a mask that hides the tokens after each one. The result is a table of weights, with a row for each token. A row's weights are each zero or more and add up to one, so each row says how a token shares its attention out over the tokens before it, and its own place. And the head's output for a token is the values of those tokens, weighted by that row. Since episode one, PyTorch's scaled dot product attention has done this for us, without handing the weights back, so to see them, we write it out.

2:30 First, the attention in model dot py, where each attention layer gets three more fields. As the comment says, they're for looking inside the model, with interpret dot py: keep, which makes it keep its weights, the weights it kept, and off, a list of heads to turn off. They start off, with no weights kept and no heads off, so the model runs as before. When keep is on, attention is written out by hand. The scores are q times k transposed, over the square root of the head's size, sixty-four. The comment over them says how: as episode thirteen's attention by hand does it, so that we keep the weights, for each token, how much it takes from each token before it. Seen is the mask, a lower triangle, as a token sees its own place and the tokens before it, and the tokens after it get minus infinity, so softmax gives them nothing. When the model isn't causal, as for episode fifteen's text diffusion, there's no mask, and each token sees them all. The weights are the softmax of each row, and the output is the weights times the values, the sum PyTorch's function works out too, with the weights kept on the way. Then, for the heads turned off, it works on a copy, so we don't write into a tensor that PyTorch might still need. As the comment says, a head turned off adds nothing to the residual stream, so their outputs are zeroed. Interpret dot py is new, and its comment says what it's for: each layer's attention weights on a text, the logit lens on its residual stream, and heads turned off, to see what they were doing. Attention returns the weights of each layer's heads on some tokens, and its docstring says how they're laid out: layers, heads, the tokens, and the tokens each looks back at. It finds the model's device from its first parameter, as before. It turns keep on in each block, runs the model once, and turns keep off again in finally, so that it's off even if something goes wrong. Then it stacks each layer's weights into one tensor, twelve layers of twelve heads, so we can pick out a layer and a head like any other index. Lens is the logit lens, from a post by nostalgebraist in twenty twenty. Its docstring says what it does: the final norm and the head, on the residual stream after the embeddings and after each block, so that each layer's guess at the next token shows. The residual stream is the sum each block adds to, and the final norm and the head are what turn the last of it into logits, so we use them on the earlier sums too. It finds the device, and starts streams as an empty list. Register forward hook has PyTorch call our function after each block runs, and we keep what it hands us in streams. As the comment says, a hook gets each block's output, the residual stream so far, as the model runs. The input goes in as a tensor, and through the model once, in a try, so the hooks come off whatever happens. After the run, the hooks come off in finally, the embeddings go first, and each stream goes through the norm, the head and a softmax, for each layer's probabilities at each position. That's thirteen rows for twelve layers, as the embeddings come first. Heads off turns heads off while it's open, and its docstring says how: each head is a layer and a head, counting from zero, used with a with statement. On entering, it appends each head to the list of its layer. On leaving, it goes through the blocks and empties each one's off list, whether the code inside ended normally or with an error. Main prints the lens at the end of an answer so far, and its parser's description says so. It imports prompt from agent dot py, the checkpoint loader and pick device inside main, as the other scripts do. It takes the checkpoint, a task, the answer's first tokens, and the role, graph by default. It loads the model and its tokenizer from the checkpoint, on the device pick device finds, and puts the model in eval mode. It encodes the role's prompt with the answer after it, and takes the lens at the last position. Then it prints, for the embeddings and each layer, the three likeliest next tokens, with their probabilities. Each line is the layer's name, embeddings for the first, then each guess as the token's text, in quotes, and its probability as a percentage. The tests use a tiny model of two layers. The first checks the weights: each row adds up to one, a token gives nothing to the tokens after it, and with the weights written out by hand, the logits are PyTorch's own. The second checks that the lens's last layer is the model's output, and the third that heads turned off change the logits, and come back on.

7:01 We run the tests with pytest, and all three pass, so the weights written out by hand give the logits PyTorch's attention does.

The logit lens

7:09 We ask the graph role for the king penguin's weight, with its query written up to the opening quote of the name, and print the next token, layer by layer. At the embeddings, the lens reads back the quote, as the head shares its weights with the embeddings, from episode one. From layer one to layer four, the guesses are odd pieces of words, and from layer five, mostly single capital letters, at two percent or less, as the residual stream doesn't say much yet that the head can read. Layers ten and eleven lean to a T, with K and P next, at a few percent each. Then in layer twelve, the last, King comes in at about ninety-six percent. King shows up in the last layer, and nowhere before it.

7:52 Now the okapi, at its opening quote, then after the O it writes. At the quote, layers ten and eleven lean to K, at about twenty-one percent in layer ten. The last layer's best guess is O, at about eight percent, where the king penguin's King was at about ninety-six, so the model is unsure of the okapi from the start. After the O, from layer nine on, the guess is A K, and it ends at about twenty-five percent, with O K, in lower case, second at about fourteen. The K that okapi needs next does show up, glued to an A or an O.

A page to look with

8:28 Then a page to look with, viewer dot HTML, which is pasted in, as it's a page more than code to read line by line. Its style is in the series' colours, and its script does the work. It decodes the weights, and puts each token on the page as a chip you can click. It draws each of the hundred and forty-four heads as a small picture, a row per token and a column per token it looks at, brighter where it looks. Picking a token shades the tokens before it by the weight the picked head gives each, and writes the weights of a tenth or more under them. The lens is a bar for each layer, with its guess, and a button averages the whole layer's heads. Viewer dot py writes the page for a text. It imports argparse, base64 and json, for the numbers that go in the page, os, for the template's path, and attention and lens from interpret dot py. Page is the path of viewer dot HTML, next to the script. The comment over it says what the page shows. There are the text's tokens, shaded by how much the token picked takes from each, for a head or a whole layer, each head's pattern, small, in a grid, and the logit lens at the token picked. As the comment says, the numbers go in the page, in place of its marker, so a browser opens it with nothing else running. Main imports prompt, the checkpoint loader and pick device, and its parser says what it's for: a page to look at the model's attention on a role's prompt. It takes the checkpoint, a task, and the answer's text, which goes in after the prompt, as its help says. Then the role, graph by default, and the file to write, attention dot HTML by default. It loads the model in eval mode, and encodes the role's prompt with the answer after it, as one text. It runs the prompt and the answer through the model for the weights, and again for the lens, and takes the lens's top guess at each position and layer. The data names the role and the task, and each token is decoded on its own, so the page shows where each one starts and ends. It holds the number of layers and heads, and the weights. As the comment says, each weight goes in as a byte, from zero to two hundred and fifty-five. So the page holds a hundred and forty-four heads of a prompt in under a megabyte, instead of several megabytes of floats. The lens goes in as those guesses, each one's text with its probability rounded to three places. And the page starts with the last token picked, and the first layer's first head. It reads the template, writes the page with the data in place of the marker, and prints how many tokens, layers and heads it holds. And at the bottom, the script runs main when it's run on its own, as the others do.

11:10 The page, for the graph role's query for the king penguin's weight, as the model wrote it. On the left are the prompt's and the query's tokens, and on the right, the hundred and forty-four heads, a small picture each. We pick Penguin, the second word of the name in the query. Layer ten's first head puts about ninety-five percent of its attention on the token before it, King. It's a previous-token head, and its picture is a bright line just under the diagonal. Layer nine's fifth head puts most of its attention on the first token, R, as many heads do when they've nothing in particular to look at. Now the name's opening quote, which writes King next. Layer twelve's first head puts about ninety-two percent of its attention on King, in the task, and the lens says King, at layer twelve and no layer before. Layer twelve's fourth head puts even more on it here, about ninety-six percent, though over the questions we score later, it gives the name less of its attention than the first head does. Averaged over layer twelve's twelve heads, half of the attention rests on the first token, and about a third on the line break after the role's line. The name gets about sixteen percent, nearly all of it from those two heads. From King, in the query, the first head moves on, and puts about ninety-seven percent of its attention on Penguin, the next word of the name in the task, which is what the query writes next.

12:30 The okapi's query, as the model wrote it, with Oakapi, from the opening quote, and layer twelve's first head. It puts about ninety-four percent of its attention on O K, in the task, so the head looks at the right place, and the fourth head does too. As with King, O K in the task has its word's space at the front, and inside the quotes, the model needs O K without it. King without its space came at about ninety-six percent, but O K without its space gets about a hundredth of a percent, so the model writes an O, at about eight percent. From the O, the head moves on, and puts about seventy-two percent of its attention on A P, the next piece of the name, as if the K were written. But the model hasn't written the K yet, and the lens says A K: the K, glued to an A. So from the opening quote, the head looks at the right place, and it's the tokens that go wrong, with the head following them.

Heads turned off

13:27 Looking at a head says where it looks, and turning it off says what the role loses without it, so interpret dot py gets that test. It imports json and os, for the results, random, for the random heads, and re, for the names in the queries. Span finds the tokens that hold some text, the first time it's written after a given character, as its docstring says. It decodes each token, works out where each one ends in the text, and returns the positions of the tokens that overlap the text. Copy scores measures each head, and its docstring says how: the share of its attention that goes to the name in the task, from the tokens that write the name into the query. Those are its opening quote and each of its tokens but the last, as each writes the next token of the name. It's averaged over the examples, a number for each layer and head. For each example, it encodes the prompt and the query, finds the name in the query with a pattern we write next, and the tokens of the name in the task and in the query. As the comment says, a token can end inside a letter, as an e with an accent is two bytes, and then the name isn't in the tokens' text, so that example is left out. It gets the weights, takes the rows of the query's name tokens, sums each row over the task's name tokens, and averages. Name is that pattern, and the comment says what it finds: a name in a query, in single quotes or in double ones, with the quote it opened with. So a name in double quotes ends at a double quote, and an apostrophe inside it doesn't end it. Names right is, as its docstring says, the share of the answers that put the right name in their query, out of those that put any name in. It pairs each example's name with the first name in the answer's trace, keeps the pairs where the trace names something, and counts the matches, or gives none when no trace names anything. Share writes a share as a percentage, or a dash for none, so the table can say when there's no name to count. Heads runs the test, and its docstring says it finds which heads look at the name in the task as the query copies it, and asks the graph role's questions with them turned off. It imports what it needs inside: graph data for the questions, the agent and attempt to ask them, and as role, so the lens doesn't need them. The examples are the graph data's seen questions, up to the limit, each under the graph role's line. As the comment says, they're episode twenty-four's held-out ones, in the training's wordings, as episode twenty-five asked them. With names is the questions whose query has a name in it, which is nearly all of them, as a list's query names its group. It scores the heads on those, and sorts them by their score. It prints how many heads it scored, over how many questions, then the six with the highest, each head's layer and number counted from one, as the page shows them. Right asks the questions with some heads turned off, inside heads off, so they come back on after each run, and returns the share right, with each answer. The results keep the scores, and the top eight heads, counted from one. It asks the questions with no heads off first. It prints the table's title and its header: the heads turned off, then the share right and the names, for the top ones, and again for the random ones. Then it prints the row for none off, with its share right and its share of names right, and the results keep the names' share. Then, for one, two, four and eight heads, it asks the questions with the top ones off. It draws as many random heads from all hundred and forty-four, three times, with seeds zero, one and two. As the comment says, that's what turning off any heads that many does. It averages the share right over the three draws, and the names right too, unless a draw has none to count. The results keep the row's numbers: the share right and the names for the top heads, then each draw's share right, and the names for the random ones. And the row is printed, with a dash where no query named anything. And as the last comment says, it prints a question the role got right, and got wrong with the top eight off, from the last row's answers. At the end, it adds the share right with no heads off to the results, and returns them. Main imports sg serve's address, from graph dot py, and the results folder, from hellaswag dot py, as the evaluations do. The parser's description now names both: the logit lens, and heads turned off. There are two commands now, made with argparse's sub parsers, which keep each command's arguments apart. Lens, the logit lens at the end of a role's answer so far, takes the task, the answer and the role, as before. Heads, for the test, takes dash dash limit, the questions to ask, two hundred by default, and dash dash server, for where sg serve is listening, which lens doesn't need. The checkpoint comes before the command, as both use it, and main loads the model in eval mode, as before. With heads, main runs the test, and takes the model's name from its folder. It makes the results folder if it isn't there, and saves the results in it, as heads, then the name, dot JSON, for the charts and the page to read, and returns. Otherwise, it prints the lens, as before, with each line's guesses now built from the pairs of probabilities and tokens. The page gets two buttons over the grid, patterns and copying the name, and the grid can show each head as one colour, the share of its attention on the name in the task. And viewer dot py takes dash dash heads, the results of interpret dot py heads, and puts the scores in the page.

18:56 We run it on the agent from episode twenty-five, with sg serve for the graph's queries. It asks the graph role two hundred questions seventeen ways, which takes about half an hour. The two heads that look at the name the most are in the last two layers: layer twelve's first, at about ninety-two percent, then layer eleven's fifth, at about eighty-six. With no heads off, the graph role gets about eighty-eight percent of the questions right, and copies about ninety-one percent of its names right. With the top four heads off, it gets about seventy-two percent right, where four random heads leave it at about eighty-eight. Yet it still copies about eighty-five percent of the names it writes right, so most of what it lost isn't the names. With the top eight off, it gets none right. It still names something in about two thirds of its answers, but just two percent of those names are right. The question at the bottom is one where it writes no query at all, and calls the calculator with words in it, a tool it hasn't got.

19:55 As a line, turning off the heads that look at the name the most costs a few points for the first one or two, about sixteen with four, and all of it with eight. As many random heads, drawn from the whole model and mostly from earlier layers, cost little up to four, and about nine points with eight. So the heads at the top of the list are ones the role needs, though this test can't tell them from other heads in the last layers. With four off, the names the role writes lose about six points, so other heads carry the name as well, and these heads have other work. With eight off, almost none of its names are right, so between them, the eight do carry the name. A head's pattern is a guess at what it does, and turning it off tests the guess.

20:42 And the docs get a page on looking inside the model: attention written out, the logit lens, the page and the heads we found on it, and the heads turned off. It goes at the end of the navigation, after last episode's page on speculative decoding, the docs' home page lists it, and the README gets the commands.

Wrap-up

20:59 Now, let's go over what's real here, and what's scaled down. Looking at attention patterns, the logit lens and turning heads off are how a lot of interpretability work on transformers starts. And the kinds of heads we found, ones that look at the previous token and ones that look back at what's being copied, are kinds that research has found in much larger models. What's scaled down is how far we go: one task, with heads looked at and turned off one group at a time. We don't trace the path from one layer to the next. Work such as Anthropic's on circuits and on features follows a behaviour through the whole model, and finds the directions in the residual stream that stand for things, which is the deeper version of today.

21:41 So, today, we wrote attention out by hand, to keep each head's weights. We put the logit lens on the residual stream, and the king penguin's name showed up in the last layer and no layer before it. We built a page to look at the hundred and forty-four heads, and found a previous-token head, and heads resting on the first token. And two heads in the last layer look at the name the model is about to copy. For the okapi, the first of them looked at the right token, and the token was the problem. And turning off the heads that look at the name cost the role about sixteen points with four of them, while the names it wrote stayed mostly right. With eight, it cost all of it, and the names went wrong as well.

22:22 If there's a head or a prompt you'd like to see on the page, let me know in the comments, and I'll have a look. And if you'd like to follow along, subscribe to the channel. I hope you find this useful, and thanks for watching.