In this episode, we look inside the GPT we pretrained on web pages in episode nineteen, with a sparse autoencoder. It writes each token's 768 channels in the middle of the model as a sum of 32 directions out of more than twelve thousand, the features, trained on the fly on this Mac. We find the first token of each window behaving very differently, measure what the autoencoder costs the model's loss, read the contexts where features fire, and push the model's writing around with a single feature.
The code
Each step on screen is a tag in the code's repository. The code at the end of the episode is ep033/end.
Transcript
Intro
0:00 Hello again, and welcome to episode thirty-three, where we take the GPT we pretrained on web pages in episode nineteen and try to read what's inside it, with a sparse autoencoder. A single number inside a language model rarely means anything you can name. So it got me curious when, in twenty twenty-four, Anthropic and OpenAI pulled millions of features out of their own models this way, many of them readable. Our model is much smaller than theirs, and I half expect mush from it. Still, I'd like to know whether it has features you can name, and whether a Mac is enough to find them. Before we build anything, let's see what one of those features does to the model's writing.
0:39 This is our web model finishing my favourite thing to do at night is, twice from one seed. The second time, we've added one feature from a sparse autoencoder to its stream, a feature for the moon, and by its second sentence, the model is writing about a huge moon.
0:56 As usual, the series has a website, with a page for each episode. The code is on GitHub with a tag for each step, if you'd like to run any of it yourself, and the docs get a page on sparse autoencoders today. The episodes are listed further down, each with its chapters.
1:13 In episode thirty-two, we moved our GPT into MLX, Apple's array library, and raced it against PyTorch on this Mac. It wrote about two and a half times as fast, a token at a time, and its compiled training step ran about forty percent faster. Today, we stop making the model faster and look inside one instead.
1:33 We're going to start by looking at the residual stream in the middle of the model, before we encode anything, and then write a sparse autoencoder and train it on this Mac. We'll measure what it costs the model to run on the autoencoder's version of its stream, read what some features fire on, and push the model's writing around with one of them. Right, let's start with the idea behind it.
The idea
1:55 As it flows through our web model, each token is seven hundred and sixty-eight numbers, the residual stream. The model has to keep far more ideas apart than that, such as names, places, dates and grammar. The leading guess comes from Anthropic's work on superposition: the model packs them in as directions that overlap a little. A sparse autoencoder tries to pull them apart again, and its encoder gives each token a score for each of twelve thousand two hundred and eighty-eight features, sixteen times the channels. Then we keep the thirty-two highest and set the rest to zero, which is what makes it sparse. The decoder has a direction for each feature, and it adds up the thirty-two kept ones, each times its score, to rebuild the token's stream. Training asks the rebuilt stream to match the real one, and if it works, each feature ends up meaning something on its own, which we can then go and read. Keeping the top thirty-two is OpenAI's TopK version, from twenty twenty-four. I prefer it to the older penalty on the activations, as k is a number I choose directly, where a penalty's weight has to be tuned until the sparsity comes out right.
A look at the stream
3:02 Everything goes in a new file called SAE, for sparse autoencoder. It imports argparse and os, NumPy and PyTorch, our checkpoint loader and the data folder, and from our model, pick device and rotary, which makes the rotary angles our web model uses. We're going to train a sparse autoencoder on the residual stream after one block. Each token's channels are written as a weighted sum of a few directions, picked out of many thousands, the features, which we can then read one at a time. Before any autoencoder, I want to look at what it's going to encode, so the first function is stream. It gives back the residual stream after the first so many blocks, without running the rest, which saves half the work when we stop at block six of twelve. It's the start of our model's forward pass, copied out. The token embeddings come first, and the rotary angles if the config asks for them, as ours does. A config without them gets learned position embeddings in their place, and then the blocks run, up to the one we want. Get windows picks random windows from a file of tokens with NumPy, and stacks them into a batch on the device. Norms is the first look, with torch no grad, as nothing here needs gradients. It picks the device, and what it's after is how long the stream's vectors are at each position, averaged over held-out text. We load the checkpoint and put the model in evaluation mode, and the validation tokens of episode nineteen's web pages come in through a memory map. NumPy gets a seed, so that each run picks identical windows, and sixteen windows of a thousand and twenty-four tokens go through the first blocks. Each token's vector is measured by its length, the norm, and each position's lengths are averaged over the windows. It prints the first six positions, a line each, and the median of the rest. From what I've read, the first position tends to be odd in these models, and I want to see whether ours is too. Main sets up argparse, with a description of what the file is for, and subcommands under it, since each step of the work adds one. Norms is the first, and takes the checkpoint and the layer, six by default, the middle of our twelve blocks. Main then parses the arguments and calls the function the command names, and the last two lines run main when the file is run as a script. And a test, in a new file called test SAE, which imports our GPT and stream. Tiny model builds a small GPT from a fixed seed, with rotary embeddings and four blocks, in evaluation mode, so that two runs on one batch agree. The test checks that the stream is the output of the blocks before it. It builds a tiny model and a random batch, and an empty list for the output. A forward hook lets us see a module's output as the model runs, and the one we put on the second block keeps the stream after two blocks. After one run of the model, the hook comes off. Stream, with a layer of two, has to give that, to a rounding error. If our copy of the forward pass ever drifts from the model's, this test fails before we train anything on the wrong stream.
6:11 The test passes, so stream gives what the model's blocks give. Then norms, on the web model, which runs sixteen windows through its first six blocks. The first position's vectors are about five hundred and sixty long on average, the second's about eighty-three, and the third's about sixty-one. Past the first six positions, the median is about thirty-eight, so the first token of a window is about fifteen times longer than a typical one. It looks like a sign of the attention sink that Xiao and others described in twenty twenty-three, where attention piles onto the first token. It lands on whatever token happens to start the window, so what that token means doesn't come into it. As far as I know, the usual explanation is that attention's weights have to add up to one, so a head with nothing useful to look at puts its weight on the first position. For us, it means those tokens would dominate an autoencoder's loss, so from here on we leave each window's first token out. The next two are long too, though a lot less, and I've kept them in.
The autoencoder
7:09 Now the autoencoder, which needs a few more imports: time, n n and its functional side, the TensorBoard writer, and the folders for checkpoints and runs. Sparse autoencoder is a module whose init takes the size of the stream, the number of features, and k, the features each token keeps. The encoder is a linear layer from the stream to a score per feature, and the decoder goes back, without a bias of its own. Bias is a vector the size of the stream, the point the features are measured from: the encoder sees the stream minus it, and the decoder adds it back. Scale is a buffer, saved with the autoencoder but not trained, for how much the stream is scaled by on the way in, so that its tokens are about the length of the square root of d model. That keeps the learning rate meaningful whichever model we point it at. The initialisation is from OpenAI's paper, and I think it's the cleverest idea there, so remember this part, as we're going to come back to it. Each feature's direction starts random, with a length of one, and the encoder starts as the decoder's transpose. That way, a feature first fires on the stream along its own direction. Encode takes the bias away first, so the encoder scores how a token differs from the bias, and top k finds each token's k largest. Each token keeps those, through a ReLU, and the others are set to zero with scatter, which writes values into a tensor of zeros at the indices top k found. Decode is the decoder, plus the bias that encode took away. Forward encodes the stream and returns the rebuilt stream with the features, as training uses the features to find dead ones. Normalize decoder, after each step, puts each feature's direction back to a length of one, so that how strongly a feature is there is its activation alone. Train first seeds PyTorch and NumPy, so that running it again gives identical starting directions and windows. It picks the device and loads the checkpoint, putting the model in evaluation mode. It memory-maps the training tokens of the web pages, and takes d model, the width of the stream, from the model's config. The autoencoder gets that width times the expansion, sixteen, so twelve thousand two hundred and eighty-eight features, and k. Windows is the batch size over the window length, the number of windows in a step. Batch takes the stream of that many random windows, without gradients, as the model isn't what we're training. Each window's first token is left out, as norms showed that its stream is many times longer than the others', and it would dominate both the scaling and the loss. What batch returns is the rest, one row per token. The scale is set once, from the first batch: the square root of d model over its average length. Adam updates the autoencoder's parameters, at the learning rate we ask for. The run folder goes under checkpoints, and the TensorBoard writer logs to a new folder in runs, named by the time. Since holds a zero for each feature, and counts the tokens since that feature last fired. One that hasn't fired in two million counts as dead, as a dead feature is a direction that's being paid for and not used. Before the loop, it prints the sizes and the block, as a header for the log. Next, it notes the start time, and the loop runs for a number of minutes. Each step takes a batch of the stream, scaled, and rebuilds it. The loss, called unexplained, measures the rebuild against the real stream: its error as a share of the stream's variance. I find it far easier to read than a raw squared error, since zero is perfect and one is no better than predicting the average token. The update is the usual three lines, zero grad, backward and the optimizer's step, and after it the decoder's directions go back to unit length. Since grows by the batch's tokens, and resets for each feature that fired. Each hundred steps, it works out the dead share from those counts. It logs the unexplained share and that dead share to TensorBoard, and prints them both to the terminal, with the tokens a second. At the end, it makes the run folder and saves the weights there, with the checkpoint, the layer, k and the number of features, so that the file records everything needed to load it again. Its last line prints the steps, the tokens and the minutes the run took. Main gets the train command, which takes the checkpoint. The layer is six by default, the stream after six blocks. The expansion is sixteen features for each channel of the stream, and k is thirty-two features per token. It runs for fifteen minutes unless we say otherwise, on batches of four thousand and ninety-six tokens, in windows of a thousand and twenty-four, at a learning rate of two times ten to the minus four. The tests get two more, both on a small autoencoder with k of eight. The first encodes ten random vectors, and each token has to keep eight features at most, and none of them negative, which is what the ReLU is there for. The second checks the initialisation, from a fixed seed, on a fresh autoencoder. The decoder's directions have to come out as unit vectors, to a small tolerance. This is the paper's initialisation, with the decoder starting each direction at a length of one, and the encoder as its transpose. Then a stream that's the bias plus three times feature seventeen's direction has to make feature seventeen fire the most.
Training it
12:34 All three tests pass with the autoencoder in. Then fifteen minutes of training, on the stream after block six, with twelve thousand two hundred and eighty-eight features and thirty-two per token. Each line is a hundred steps, and the unexplained share falls fast at first, from about three quarters, and then slowly, to about zero point one eight by the end. So the autoencoder rebuilds about eighty-two percent of the stream's variance. And the dead share stays at zero the whole way. That surprised me, as dead features are a problem these papers spend a lot of pages on, and I'd put this one down to the initialisation, with each feature starting on its own direction. It's thirty-seven hundred steps in fifteen minutes, about fifteen million tokens, which is tiny next to the billions the big labs train on, so I'd expect the features to be rougher than theirs.
13:23 On a chart, most of the drop happens in the first thousand steps, and after that it wobbles around a fifth from one batch to the next, still going down slowly. A longer run would take a few more points off, and if I were using these features for more than a first look, I'd give it an hour.
What it costs the model
13:39 A low reconstruction error doesn't tell us whether the model can still use what comes back, so the next measurement runs the model on it. Load SAE reads a saved file, which names the checkpoint it came from, and loads that model in eval mode. It rebuilds the autoencoder at the sizes in the file, loads its weights, and returns both with the tokenizer and the layer. Splice is a small class to use with Python's with statement. While it's open, the stream at a given point goes through a function we pass, before the rest of the model sees it. Init keeps the function, and the block at layer minus one, as Python counts from zero. On enter, it registers a forward hook on that block, and a forward hook that returns a value replaces the block's output with it. On exit, it removes the hook, so the model is back to normal however the block inside ends. Evaluate loads everything with load SAE, and memory-maps the validation tokens of the web pages. It seeds NumPy, and takes sixty-four windows of a thousand and twenty-five tokens: the inputs, and the next tokens one along. Loss runs the model on them four at a time, since all sixty-four at once would need over eight gigabytes for the logits, and averages the cross entropy over the targets. The first of three runs, clean, is the model as it is. Then a splice runs the stream through the autoencoder, so that the rest of the model gets its reconstruction instead. The stream is converted into the autoencoder's units on the way in, and back on the way out, past each window's first token, which the autoencoder didn't see in training. Mean is the stream's average token, from eight of the inputs, past their first tokens. It keeps nothing of what each token carries, so it's the floor to compare with, and the third run splices it in for each token past the first. It prints the loss over all the held-out tokens for each of the three, first the model as it is, then through the sparse autoencoder, and with the average token instead. The last line is how much of the gap between that floor and the clean model the reconstruction recovers. This is the number I'd report for an autoencoder, because it's measured on the model's predictions, not on the stream. The evaluate command takes the SAE's file and the number of windows, sixty-four by default, and main's table of commands maps evaluate to its function. The test imports Splice, and checks that a splice changes what the rest of the model sees, and then goes away. It runs a tiny model on a random batch. With a function that changes nothing, the model's output is unchanged, and with one that zeroes the stream, it isn't. Once the with block ends, the model is as it was.
16:20 We run it on the autoencoder we just trained, with about sixty-five thousand held-out tokens of web pages. The model as it is has a next-token loss of about three point zero eight. Running on the autoencoder's version of its stream after block six, it goes up to about three point two nine. With the average token in its place, it's about eight point four, which shows how much the model needs that stream. The autoencoder gets back about ninety-six percent of the way from the floor to the model. For fifteen minutes on a Mac, I'll take that. Still, the loss goes up by about a fifth of a point, so our features miss part of what the later blocks use.
Reading the features
16:59 Next comes the code for reading what each feature fires on. Context gives back an example for us to print. It decodes the twelve tokens before a given token. That token goes in bold yellow, so it's decoded on its own, before the three tokens after it. They're joined with the terminal's escape codes for the colour, and new lines are turned into spaces, so that each example fits on one line. Fire rates memory-maps the first fifty thousand validation tokens of the web pages. It measures the share of them each feature fires on, at all positions but the first, as in training. We cut the tokens into windows of a thousand and twenty-four, and start a count at zero for each feature. Eight windows at a time, it adds up the tokens each feature fired on, and then divides by the number of tokens it looked at. I added it after my first look, where a handful of the twelve thousand lit up on over half the tokens and crowded the top of each ranking, while telling us next to nothing about any single token. Features, the first way in, shows each token of a text with the features that fire most strongly on it. It loads the autoencoder, and its fire rates mark the dense features. A feature firing on most tokens tells us little about any one of them, so those are left out. It prints their numbers first, so we know which ones are missing. After that, the text goes through the tokenizer, the model and the autoencoder, and the dense features are set to zero. The first token is left out, as in training, and each one after it gets its top three features, with their activations, on a line of its own. It's the way I find features to look at, by typing a sentence about something and seeing what lights up. Show is the second way in, from the other side. For each feature id we ask for, it finds how often it fires on held-out text, the contexts where it fires most strongly, and the tokens its direction pushes the model towards. Show also loads the autoencoder, and memory-maps half a million validation tokens, ten times what fire rates reads, as the rarer features need that much text to turn up a few good examples. The wanted features go in a tensor, and each one gets a list for its best examples, and a count of the tokens it fired on. The loop steps through the data eight windows at a time, stacking them and running them through the model and the autoencoder, and keeps the wanted features' activations. It counts the tokens each one fired on, and for each feature, top k picks the strongest activations across these eight windows. As the windows leave out their first token, each index into them is mapped back to a position in the held-out text, and kept as a candidate. Once the data's done, each feature's direction comes from the decoder, in the stream's units, and is read straight through the model's head. That shows which tokens it raises the most. Reading it that way skips the six blocks after it, so it's rough, but it's often enough to guess what a feature is for. Last, it prints the share of tokens each feature fires on, and the tokens it raises. The candidates are sorted, strongest first, and it prints a context for each of the best, with its activation. In main, each way in gets a command of its own. Features takes the SAE's file, a text, and how many top features to show for each token, three by default. Show wants the SAE's file and one or more feature ids, with the number of tokens to read and the examples to print, six by default. Main's last line adds both to the table of commands.
20:26 Let's try features on a sentence about Paris. It measures the fire rates first, which takes a moment. Seven features fire on over half of all tokens, so they're left out, and I've not worked out what they carry, whether it's the position, the general direction of the stream, or something else. Our tokenizer cuts Eiffel into three pieces, and each piece gets features of its own, which I suspect are about spelling out a rare word. On Paris, the strongest is feature sixteen twenty-one. Capital gets a different feature, ten six five two, and sixteen twenty-one shows up there too. And eighty-two eighty-seven fires on both Paris and France, which makes me think it's about France. The full stop gets activations around fifty, far above the rest, and I think it's what we saw with the first token, a few tokens the model makes much louder than the others.
21:16 Then show, on six features I'd picked out from sentences like that one, over half a million held-out tokens. Sixteen twenty-one fires on about one token in three hundred, and its strongest contexts are Paris, Atlanta and Paris again, so it looks like a feature for a city's name. The tokens it raises through the head partly agree, with city at the top, and metro and metropolitan among them. Ten six five two is the word capital, and mostly the one meaning a city, in Kyiv, the capital. Seventeen sixty-seven is carbon, and the token it raises most is dioxide, followed further down by monoxide, so it's partly a feature for what comes next. Carbon is my favourite of the six, because it's the clearest case I found of a feature doing a job for the prediction. Fifty-three eighty-six fires on the moon, Jupiter's moons among them, seventy-five sixteen on years, nineteen thirty-two, nineteen twelve, eighteen ninety-six, and sixty-one ninety-eight on full stops, with activations near seventy, the loud tokens from before. Not all features are this clean, and I picked these six. A lot of the ones I looked at were harder to name, and the raised tokens are often noise, as with the moon's, since going straight to the head skips the six blocks after this one.
Steering with a feature
22:28 And last, steering, which needs textwrap and our sample script's write function. Steer loads the autoencoder, and push takes the feature's column of the decoder and divides it by the scale. That puts the feature's direction in the stream's own units, times the strength we ask for. The loop writes twice, once as it is and once with the feature, and both times it seeds PyTorch with the seed we give, so that the feature is the one difference between the two. The push goes into the stream after the block, at each position, through a splice, times strength greater than zero, which leaves the first text as it is. I was quite pleased that the splice we used to measure the autoencoder is all we need here, because a feature is a direction, and we can add it. It prints both texts, wrapped to ninety characters. On the command line, steer takes the SAE's file, a feature and a prompt. The strength is ten by default, with sixty tokens, and the seed is zero unless we pass one. The table of commands in main's last line gets steer as well.
23:31 Now steering, with the moon feature, fifty-three eighty-six, on a prompt I picked, my favourite thing to do at night is. As it is, the model writes about sleeping in a bed, with our eyes glued to our bed, which is about what I'd expect from a model this size. With the moon's direction added at a strength of twelve, from that seed, the text turns: there's a huge moon, the second of our moons, as full as a half moon. The sentences are no better than before, but they're about something else, and I didn't expect one direction at one block to move the text that far. At thirty, it's moon after moon, and the grammar falls apart, as the feature takes over the stream instead of nudging it. I tried the city and the carbon features too, and at strengths that kept the text readable, they barely pulled it towards cities or carbon. I'd want to measure steering properly, over a lot of prompts, before claiming more than that it works some of the time.
24:28 Last, the docs get a page on sparse autoencoders, with the stream and its sink, the autoencoder and its training, what it costs the model, the features we read and the steering. It goes in the docs' list and their navigation. The README gets the commands, from norms to steer.
Wrap-up
24:46 Today's autoencoder sits on the stream after block six of our web model, with twelve thousand features and thirty-two per token, and it trained in fifteen minutes on this Mac. Before that, the stream showed us the attention sink, a first token about fifteen times longer than the rest, which we left out. The autoencoder rebuilt about eighty-two percent of the stream's variance without a dead feature, and the model running on it kept about ninety-six percent of the way back from the average token. Some features were easy to name, cities, the word capital, carbon with dioxide to follow, the moon and years, while seven fired on over half of all tokens and plenty I couldn't name at all. And one of them, the moon, could steer the model's writing, at a strength between nudging the text and breaking it. I can't say yet whether the moon is the usual case or a lucky one, as the city and carbon features barely pulled the text their way.
25:37 Let me know in the comments what you think those seven features that fire on over half of all tokens are for, as I'd like a better guess than mine. And if you'd like to follow along, subscribe to the channel. I hope you find this useful, and thanks for watching.