In this episode, we take attention out of our GPT and put Hyena in its place: long convolutions as long as the window, computed with the fast Fourier transform, between two gates. We write it from the paper and its authors' code, follow the numbers through one channel, and train it against our own attention models on two rented RTX 4090s.
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 ep029/end.
Transcript
Intro
0:00 Hello and welcome back to episode twenty-nine, where we're going to take attention out of our GPT and put Hyena in its place, long convolutions computed with the fast Fourier transform, between two gates. First, a quick look at what we'll have by the end.
0:15 By the end, we'll have trained GPTs without attention in them, and looked inside. An attention head picks out the name it's going to copy, while a Hyena channel weighs the tokens by distance and gates, and its model doesn't copy the name.
0:30 We're going to write Hyena from its paper and its authors' code, follow the numbers through it, and measure it against our own attention models on two rented GPUs, for speed, loss, long context and recall.
0:42 The series has a website with more information about the project. The code is open source on GitHub, tagged at each step of each episode, so you can follow along, and the docs get a page on Hyena today. Each episode has a page here too, with its chapters and its code.
1:00 A quick reminder of where we left off, first. Last time, we looked inside our agent while it copied a name from its task into a query, and found a head in the last layer that puts about ninety-two percent of its attention on the name. With the eight heads that look at the name the most turned off, the names it wrote right fell to about two percent. So in our model, copying goes through attention, which compares each token with all the tokens before it. Today, we take attention out altogether, and see what a model built without it can do, and what it costs.
1:35 Attention's cost grows with the square of the window, as each head scores each token against all the ones before it. Hyena, from a paper of twenty twenty-three, replaces it with filters as long as the window, and gates read off the tokens, and computes the long convolutions with the fast Fourier transform, in about n log n operations. We're going to write it from the paper and its authors' code, as an option in our model, along with a hybrid that keeps attention in one block. Then we're going to train it against our own attention models on two rented RTX 4090s, with everything else kept as it was. And we're going to measure the speed, the loss, how well each uses a long context, and how well each recalls what it has read.
The paper
2:17 The paper is Hyena Hierarchy, Towards Larger Convolutional Language Models, by Michael Poli, Stefano Massaroli and others at Stanford and Mila, from twenty twenty-three. Its abstract says Hyena reaches transformer quality on The Pile, a dataset of eight hundred gigabytes of text, with twenty percent less training compute at a window of two thousand tokens. It also says Hyena's operators are twice as fast as highly optimised attention at eight thousand tokens, and a hundred times faster at sixty-four thousand. Figure two point one puts the two side by side. Attention's matrix comes from a softmax of queries against keys, while Hyena's is a product of diagonal matrices and convolution matrices. And definition three point one is the operator of order N, which we're going to write out on the next card.
Attention, as a matrix
3:04 Before Hyena, let's write the attention we have in a way that makes the comparison easier, as the paper does. For one head, the output y is a matrix A times the values v, and the matrix is set by the input u. Row t of A holds how much token t takes from each token s. It's the exponential of the dot product of t's query with s's key, over eight, the square root of sixty-four, divided by the sum over the tokens up to t. That's the softmax from episode one, and past the diagonal the weights are zero, as a token doesn't look ahead. So the weight on a token comes from comparing contents, query against key, wherever that token sits in the window. The queries, keys and values are three projections of each token's channels, our q, k and v projections. The paper calls an operator like this data-controlled: it's linear in v, with a matrix that the input decides. The price is a table of T by T scores for each head. That's about a million for a window of a thousand and twenty-four tokens, and about seventeen million for four thousand and ninety-six, four times the window for sixteen times the scores.
Two blocks
4:14 Here's the attention part of our block, on the left. The norm before it, the MLP after it and the residual stream around them stay as they are today. Three projections make q, k and v, the scores make a table of T by T for each head, softmax turns each row into weights, and the weighted sum of the values goes through the output projection. On the right, Hyena, in attention's place, where a single projection makes three times the channels, cut into x one, x two and v. A short filter, three tokens long, mixes each channel with that channel of the two tokens before. Then the first gate: z is x one times v, channel by channel. The long filter comes from a small network of the position, without any tokens going in, and it's convolved with z over the whole window, with the fast Fourier transform, plus a skip, b times z. The second gate multiplies by x two, and the output projection has the shape of attention's. There's no table of T by T in it, and no token is compared with another.
The Hyena operator
5:15 The paper defines the operator of order N as a recurrence. It starts from z one, the values, and each step convolves with a filter, h n, then multiplies by a gate, x n, another projection of the input. Written out, a convolution is this sum: the output at t adds up z at each position s up to t, weighted by the filter at t minus s, how far back s is. So the weight a filter gives a token depends on its distance, and not on what the token is. We're going to use order two, as the paper does for its language models. In its authors' code, the first convolution is the short filter of three tokens, which runs as the projections are made, so one long filter is left, between two gates. The output at t is x two at t, times the sum over s of h at t minus s, times x one and v at s. And there's a skip, b times x one and v at t, with a b learned for each channel.
6:11 Like attention, this is a matrix times the values, for each channel, and the paper writes the matrix as a product. S h is the convolution as a matrix, here for four tokens: h zero on the diagonal, h one below it, h two below that. It's constant along each diagonal, which makes it a Toeplitz matrix. D x is a gate as a matrix, with x on its diagonal and zeros elsewhere, so multiplying by it scales each token's row. Multiplied out, the entry at row t and column s is x two at t, times the filter at the distance t minus s, plus b on the diagonal, times x one at s. So in attention, the weight token t puts on token s comes from comparing the two, query against key. In Hyena, it comes from how far apart they are, scaled by a gate at each end. The gates depend on the tokens, so the matrix still depends on the input, which is what the paper means by data-controlled. And each channel gets a matrix of its own, where the sixty-four channels of an attention head share their weights.
The FFT
7:17 Written out, a convolution over the window takes a sum for each output, T times T over two multiply-adds, as many as attention's scores. The convolution theorem is the way around that. The Fourier transform turns a convolution into a product, frequency by frequency, so we transform h and z with the fast Fourier transform, multiply them, and transform the product back. Each FFT takes about n log n operations. The FFT's convolution is circular, though: the filter's far end wraps round onto the tokens after t, which would let a token see ahead. Padded with zeros to twice their length, n is two T, and whatever wraps round lands past the T outputs we keep, so those are the causal sums. For a window of four thousand and ninety-six, the sums for one channel take about eight point four million multiply-adds, about sixteen point eight million operations. The three transforms take about eight hundred thousand, about twenty times fewer, and the gap grows with the window.
The convolution, in code
8:15 Hyena gets a file of its own, hyena dot py, and its docstring says what it's for. Hyena, from Poli and others in twenty twenty-three, puts long convolutions and gates in attention's place in the block. For each channel, the output at token t is a weighted sum of the tokens up to t, as with attention. The weight on token s comes from a filter, by how far back s is, and from two gates read off the tokens. Then the formula from the cards, and why it's fast. A sum over the tokens before, weighted by distance, is a convolution, and the fast Fourier transform computes it for each t at once in T log T operations, where attention's table of scores takes T squared. Torch is the one import, as its fft module has the transforms we need. Fft conv takes u, the values, with the channels before the tokens, and h, a filter for each channel, as long as the sequence. T is the number of tokens, and above it, we write the shapes and the sum it works out for each t at once. N is two T, and the comment over it says why. The FFT's convolution is circular: a filter running off the end wraps round to the start. With the inputs padded with zeros to two T, what wraps round lands past the T outputs we keep, so those are the causal sums. R F F T is the FFT of a real signal, which returns the frequencies up to the middle, as the ones after mirror them, and n equals n pads the input with zeros to that length. We take it of u and of h, in float thirty-two, and the comment says why: the FFT has no b float sixteen version, and its sums of thousands of terms need the precision. Then the product of the two transforms, frequency by frequency, and the inverse R F F T takes it back to two T values, of which we keep the first T, in the type u came in as. Over it, the idea in a line: convolving in time is multiplying in frequency, one product per frequency, instead of a sum per output. Direct conv works those sums out by hand, in T squared, for the tests and to read what fft conv computes. For each t, it multiplies the tokens up to t by the filter's first t plus one taps, reversed, and adds them up. As the comment says, token s is t minus s back, so its weight is h at t minus s, which is why the taps go in reverse. The test file imports pytest, torch and the two functions, and parametrize runs the test once for each length. The test checks that the two agree, for sequences of one, seven, thirty-two and a hundred tokens, with random values and filters, to within a ten thousandth.
10:52 We run the test with pytest, and all four lengths pass, so the transforms give the sums we'd write out by hand.
The filter
11:00 Now, let's see where the long filter comes from. A filter as long as the window, learned tap by tap, would need a weight for each position and each channel. So Hyena makes it with a small network instead, an implicit filter, the paper's equation seven. Each position t becomes thirty-three numbers: where it is in the window, from zero to one, and a cosine and a sine of it at sixteen frequencies, from zero to fifteen turns over the window. A network of four layers, sixty-four wide, turns those into a value for each channel. Its activations are sines, starting at a frequency of fourteen, so that a filter can have sharp features, where a network of smooth activations learns smooth shapes first. Then each channel's filter fades with distance, by an exponential whose rate goes from about three point one to about fifteen point four across the channels. The fastest falls to one percent by thirty percent of the window, and the slowest is still at about five percent at its end, so some channels look near and others far. All of it is thirty-five thousand, five hundred and twenty weights for our three hundred and eighty-four channels, for any window. A filter learned tap by tap would need about one point six million for four thousand and ninety-six tokens.
The filter and the operator, in code
12:11 Step two adds the filter and the operator to hyena dot py, and the docstring gains a sentence: this is the paper's operator of order two, as its authors' code computes it, one long filter between two gates. Math is for pi and the logarithms, and torch's nn module is for the layers. Sine is an activation, the sine of w times x, with a frequency w for each of the network's sixty-four hidden units. The frequencies are a parameter, so training can move them, starting at fourteen. The comment over it says why sines: a network of smooth activations learns smooth functions first, and with sines at a high frequency, a filter can have sharp features too. Hyena filter makes the long filter for each channel, and the comment over it gives the paper's equation seven: the window, times the network, of the position's encoding. Its weights don't grow with the window, which makes it an implicit filter. It takes the number of channels, the length of the window, sixteen bands of frequencies and a width of sixty-four. T counts the window's positions, from zero, as a tensor of whole numbers, which the encoding and the fade both use. Turns comes from linspace, sixteen numbers evenly spread from almost zero to fifteen. Over it, the comment says what the encoding is: each position as thirty-three numbers. One is where it is in the window, from zero to one, and the others are a cosine and a sine of it at sixteen frequencies, from zero to fifteen turns over the window. It's fixed, as in the paper's equation, while the authors' language models let training nudge it too. Angles holds each position's angle at each frequency: two pi, times the position over the length, times the turns. The encoding puts together where each position sits and the cosines and sines, and register buffer keeps it in the model, moved to the GPU along with it, without training it. Then the network: a linear layer from thirty-three to sixty-four, two more of sixty-four, and one from sixty-four to a value for each channel, without a bias, and the sines between them. We make the sine once and use it three times, so its frequencies are shared, as in the authors' code. The fade needs t again, from zero to one. The comment over it says how the filters fade: the fastest falls to one percent by thirty percent of the window, and the slowest is still at about five percent at its end. So each channel gets a rate, evenly spread from the log of a hundred over one point five, to the log of a hundred over point three. And b, the skip, a number for each channel, drawn from a normal distribution, as in the authors' code. Forward makes the first T taps of each channel's filter: the network on the first T positions, times the fade, transposed so the channels come first. Tap zero weighs a token's own value, and tap one the token before. Then Hyena, the operator, which goes where a block had attention, and the comment over it gives the matrices from the card. Y is D x two, times S h plus b times the identity, times D x one, times v. Like attention, it takes the config and the block's number. In proj makes three times the channels from each token, in one projection. The short filter is a convolution over the tokens, three long, with as many groups as channels, so each channel is filtered on its own, which is called a depthwise convolution. Its weights start as PyTorch draws them, as our model's init touches its linear layers and embeddings and nothing more, which the authors' models do too. The comment over it says how it mixes: a filter three tokens long on each of the three C channels, mixing a token's projections with that channel's from the two tokens before. It's padded by two at both ends, which gives T plus two outputs, and the first T of them end at each token, so they look back and not ahead. Then the long filter, for C channels and as many taps as the window, and the output projection, which attention has too. Forward gets B, T and C from the input's shape, and projects. Transpose puts the channels before the tokens, as convolutions take them. It runs the short filter, keeping the first T outputs, and split cuts the three C channels into x one, x two and v. The first gate: z is x one times v. Then the filter's first T taps, and the long convolution of z with fft conv, plus the skip, b times z. The second gate multiplies by x two, and the channels go back after the tokens for the output projection, with dropout, as attention has it. Streams returns x one, x two and v for whole sequences, to look inside the operator later. Matrices builds the T by T matrix each channel applies to its values, for one sequence. The operator doesn't build them, as the comment says: they're for looking at, as attention's weights are, and for the tests. Matrices takes the first sequence's x one and x two from streams, and the filter at its length. Lag is how far back column s is from row t, for each pair. Indexing the filter by the lag, clamped at zero, and zeroing past the diagonal makes S h, the Toeplitz matrix from the card, and the skip goes on its diagonal. Then x two scales the rows, and x one the columns. Then three new tests, and the first takes the gradient of output forty with respect to all the inputs. It's above zero for each token up to forty, and after forty, it's zero but for the FFT's rounding, under a millionth of the rest, so no output looks ahead. The second checks the matrix form: each channel's matrix times its values, through the output projection, gives the layer's output, with nothing above the diagonal. And the third checks that the filter has as many weights for a window of four thousand and ninety-six tokens as for two hundred and fifty-six.
17:58 We run them, and all seven pass, the four lengths from before and the three new tests, so the operator looks back and not ahead, and its matrices give its outputs.
Hyena in our GPT
18:08 Step three puts Hyena in our model, so model dot py imports Hyena from hyena dot py, and the config gets two fields. Mixer says what mixes the tokens in each block: attention, by default, or hyena. And attention layers lists the blocks that keep attention in a Hyena model, counting from zero, which makes a hybrid. The paper's appendix suggests those for windows of up to eight thousand tokens. Both fields have defaults, so the checkpoints we've trained so far load as they were. The KV cache, from episode four, gets a list for Hyena's blocks, as each keeps its own state there: each token's gated values, and the last two projections. The cache's length was the number of tokens in the first block's keys. Now the first block may be Hyena's, so it looks for the first block with keys, and then for one with Hyena's state. Sliding the window drops the oldest tokens from whichever blocks have keys, values or Hyena's z. KV cache bytes counts what grows with each token. A Hyena block keeps one number a channel, where an attention block keeps a key and a value, and the comment adds that the last two tokens' projections don't grow. It counts the Hyena blocks, all of them but the ones that keep attention, or none in an attention model. Per token, each attention block keeps a key and a value for each of its key and value heads, and each Hyena block one number a channel. Then the block, which has the norm, as before, and then Hyena, when the config says so and the block isn't one that keeps attention, or attention otherwise. In forward, a Hyena block doesn't take the rotary angles, and the comment says why: the convolutions know how far back each token is. And attend with, from episode thirteen, sets the attention function in the blocks that have attention. Back in hyena dot py, forward takes the cache, for writing one token at a time. Before is this block's state in the cache, if there is one. Writing with a cache, the projections of the last two tokens go in front of the new ones, for the short filter, and of its outputs, we keep the new tokens'. The new tokens' z joins the z of all the tokens so far. The filter doesn't depend on the tokens, so with a cache, it's made once for the whole window, and kept. For one new token, the output is a sum over all the tokens so far: their gated values, each weighted by the filter at its distance, the newest by h zero. The comment calls it a sum over the cache, as attention's is. Writing one token, there's no convolution for the FFT to speed up, just a dot product as long as the text. Otherwise, as for a prompt, it's the FFT, keeping the new tokens' outputs. At the end, the state goes in the cache: the last two projections, z, and the filter. As the comment says, that's one number a channel for each token, where attention keeps a key and a value. There are four new tests. Writing a sequence through the cache, eight tokens and then four one at a time, gives the logits of running it whole, for a Hyena model and for a hybrid. A hybrid's blocks are the kinds it names, the cache holds what KV cache bytes says, and generate writes past the window, where the cache slides.
21:23 This time we run all of the model's tests, the earlier episodes' too, as the block and the cache changed. They all pass, so the attention models work as before, and Hyena's cache gives what running the whole sequence gives.
21:37 Here's what each kind of block keeps and does as the model writes, one token at a time. Attention keeps a key and a value for each token so far, two C numbers, compares the new token's query with each key, and sums the values by the weights. Hyena keeps z, C numbers a token, and sums z weighted by the filter, gated by x two. After t tokens, that's about two t C multiply-adds for attention and t C for Hyena, so both grow with the text. The FFT pays off on whole sequences, a prompt or a training batch, while writing one token, Hyena takes a dot product as long as the text, as attention does. For a model of twelve blocks of seven hundred and sixty-eight channels, the cache takes seventy-three thousand, seven hundred and twenty-eight bytes a token with attention, and half that with Hyena. The paper's authors later distilled Hyena's filters into a recurrence with a state of a fixed size, in a paper called Laughing Hyena, which keeps a token's cost from growing, and which we're not going to do here.
Ready to train
22:38 Step four gets us ready to train, starting in pretrain dot py. Past windows of five hundred and twelve, the held-out batches hold fewer windows, so the logits fit in the GPU's memory next to what training holds: tonight's first run ran out of it in its first evaluation. N is how many batches, more as the batch gets smaller, so each estimate still averages as many tokens. Param groups moves the optimizer's two groups into a function, so both training scripts share it. Weight decay pulls the weight matrices towards zero, as before, but not the biases and the norms' gains, and now not the network that draws Hyena's filters either, which its authors leave out too. The weight decay stays at point one, and the rest get none. Main takes hyena, which names the run's folder with hyena at the end, and sets the config's mixer. At the bottom of the file, the arguments pass it along, and dash dash hyena turns it on. Pretrain DDP dot py, from episode twelve, gets the rest. The minutes become optional, as dash dash steps trains for a number of steps instead, with the learning rate's schedule following the steps, so that a run can see as many tokens as an earlier one did. Dash dash hyena puts Hyena in each block, and dash dash attention layers keeps attention in the blocks it lists, for a hybrid, as a list of numbers counted from zero. Giving both the minutes and the steps, or neither, is an error, which parser error prints along with the usage, before any GPU is touched. The config takes the mixer and the blocks, as a tuple, so it's saved in the checkpoint along with the rest. The run's folder ends in hyena, and the first line it prints says Hyena, with the attention that the blocks it lists keep. For a hybrid, it lists those blocks in brackets, after the kind of attention, and for Hyena alone, the line just says Hyena. The optimizer's groups come from param groups now, as in pretrain dot py, so the filters skip the weight decay here too. A run with steps has no time budget, so budget is none, and the clock still runs, for the minutes it prints at the end. In the loop, progress is the share of the steps done, or of the minutes, and both the schedule and the stopping follow it. Hyena bench dot py times one layer of each kind, as attention bench did in episode thirteen. It imports sync from episode four's bench dot py, our Hyena, and attention with its rotary angles from the model. Layer flops counts the operations of a layer's forward pass, with a multiply-add counting two. Both kinds project each token in and out, eight T C squared for a sequence, a cost both kinds share. Attention adds the scores and the weighted sums, two T squared C, once the half past the diagonal is skipped. Hyena adds, for each channel, a transform of the gated values and an inverse one, about five n log n with n at two T. And there's about thirty T C for the product, the gates, the skip and the short filter. Make layer builds one attention layer or one Hyena layer, from a config with the window as its block size, rotary embeddings on, and no dropout, and moves it to the device. Time layer seeds the random numbers, so both kinds get identical inputs, and works out how many windows make up the batch. The input asks for its gradient, so the backward pass goes all the way to it, and a random gradient stands in for the loss's. Attention gets its rotary angles, and on an NVIDIA GPU, it all runs in b float sixteen, as in training, while on the Mac it stays in float thirty-two. Run is a forward pass and a backward pass, with the gradient we made up, and then the gradients are cleared, the input's and the layer's, so the next run starts clean. The forward pass gives each kind what it takes: attention gets the rotary angles, and Hyena doesn't need them. A first run warms up, as the comment says. Then, on an NVIDIA GPU, reset peak memory stats starts the memory count afresh. Five runs are timed, with sync before each reading of the clock, as in episode four, and it returns the median, which a single slow run can't move, along with the most memory the GPU held. Both passes are timed, as training runs both, and the backward one does about twice the forward's work. Main's parser describes the script: one attention layer against one Hyena layer, forward and backward, with as many tokens at each length. The device is CUDA when there's an NVIDIA GPU, and the Mac's GPU otherwise. The lengths go from two hundred and fifty-six tokens up to sixty-five thousand, five hundred and thirty-six, by default. Tokens is how many tokens a batch holds, sixty-five thousand, five hundred and thirty-six: sixty-four windows of a thousand and twenty-four, or one of sixty-five thousand. With the tokens fixed, a layer whose cost per token grows with the window shows it as a rising time. Then the channels, three hundred and eighty-four by default, the heads, six, the runs, five, and a file for the results. Parse args reads them from the command line. The device's name comes from CUDA on an NVIDIA GPU, or it's mps on the Mac. It prints what it's measuring and on which device, and a header for the table, with a column for each kind. For each length, a row starts with the length and the windows, and it times both kinds. A kind that runs out of memory gets none, instead of stopping the run, and the GPU's cache is emptied for the next one. The comment says the operations are for a batch's forward pass, as the backward does about twice as much again. Then it works out how many times faster Hyena is, attention's time over Hyena's, so above one means Hyena is the faster. And it prints the line: the length, the windows, both times, that ratio, and the billions of operations each did. At the end, it writes it all to a JSON file, with the device, the tokens a batch and the channels, for the charts. Last in this step, a shell script trains the small models one after another, on one GPU. Set dash e u o pipefail stops the script at the first error, an unset variable or a failing pipe. The comment over it says what the script trains: the small models, half an hour each, with attention, with Hyena, and with Hyena but attention in block three. They train on windows of a thousand and twenty-four and of four thousand and ninety-six tokens, at sixty-five thousand, five hundred and thirty-six tokens a step. And it says how to start it on the second GPU, with CUDA visible devices set to one. Then mkdir makes a folder for the logs. For each window, a thousand and twenty-four and then four thousand and ninety-six, and for each kind, case picks the flags: none for attention, dash dash hyena, or dash dash hyena with attention in block three. Torchrun starts pretrain DDP on that GPU, for thirty minutes of web pages, compiled, with six blocks of six heads and three hundred and eighty-four channels. The batch is thirty-two thousand, seven hundred and sixty-eight tokens divided by the window, in two batches a step, so both windows see sixty-five thousand, five hundred and thirty-six tokens a step. Each run gets a name, and a log of its own.
Counting operations
29:41 Before we run anything, let's count the operations. Both kinds of block have the projections, eight T C squared, and the MLP, sixteen T C squared. Attention adds two T squared C, and Hyena about five n log n C for its transforms, plus thirty T C. And the model has the head, two T C V, where V is the vocabulary, thirty-two thousand, seven hundred and sixty-eight for the web. For our small model at a thousand and twenty-four tokens, a Hyena block does about three quarters of an attention block's work, but the head is half of the model's, so the whole model does about nine percent fewer operations. At four thousand and ninety-six tokens, attention is almost half of a block's work, and the model does about one point four times fewer with Hyena. Tonight's model, twelve blocks of seven hundred and sixty-eight channels at a thousand and twenty-four, does about eight percent fewer. Those are counts of operations, and the FFT runs on the GPU's ordinary cores in float thirty-two, where matrix multiplications in b float sixteen run on its tensor cores, so fewer operations needn't take less time.
A layer of each, timed
30:46 First, on the Mac's GPU, with sixteen thousand, three hundred and eighty-four tokens a batch, from sixty-four windows of two hundred and fifty-six tokens to two windows of eight thousand, one hundred and ninety-two. Each length times a layer of each kind, forward and backward, five times. At two hundred and fifty-six tokens, attention takes about thirty-seven milliseconds and Hyena about forty-seven, so on short windows, attention is the faster. By a thousand and twenty-four, Hyena is about one point four times faster, and at eight thousand, one hundred and ninety-two, attention takes about three hundred and seventy-seven milliseconds, about six point eight times Hyena's fifty-five.
31:24 Drawn as lines, attention's time grows in a straight line with the window, as each token is compared with all the tokens before it, so the work for each token grows with the window. Hyena's line stays nearly flat, as its transforms grow with the log of the window, which barely shows next to the projections, and those don't grow at all.
Two GPUs
31:44 For the runs, I've rented a machine with two RTX 4090s, in British Columbia, and called it gpu for ssh, as in episode fifteen. It costs about ninety-two cents an hour. Remote dot sh, from episode twelve, set it up: the code, the C++ tokenizer, and five of FineWeb-Edu's files, the web pages episode nineteen trained on. Its one hundred and twenty-eight cores tokenized them in about four minutes, about three point eight billion tokens. Nvidia smi, run on the machine over ssh, shows both GPUs busy, each with most of its memory in use. Its log of the commands that started them comes next. On the first GPU is tonight's run, a Hyena model in the shape of episode nineteen's: twelve blocks of seven hundred and sixty-eight channels, with its batch, its window of a thousand and twenty-four, and torch compile. It trains for thirty-six thousand seven hundred and forty-three steps, as many as episode nineteen's model took, so it sees the three point six billion tokens that model saw. On the second GPU, hyena runs dot sh trains the six small models, one after another. The first attempt at tonight's run ran out of memory in its first evaluation, with batches of forty-eight windows, so the held-out batches got smaller and more numerous, and it started again a quarter of an hour later.
Tools to compare them
33:06 While they train, step five adds the tools to compare them, and the first is hyena eval dot py. It measures models of any kind side by side, each in its own window, and here are the two measurements that matter most. Loss by position takes long held-out web pages, with episode twenty-two's long pages, and predicts each token from all the tokens before it in the window, in one pass. The losses are averaged over the pages and over sixteen groups of positions. That shows whether a model uses what it has read, as the loss should fall the further into the window a token is. Copying writes random tokens, then those tokens again. Nothing in the first half can be guessed, while each token of the second half can, by finding it in the first half and taking the token after it, which is what attention's induction heads do. The random tokens can be any but the padding and the end of text, from a generator with a fixed seed. The model takes one sequence at a time, as thirty-two windows of four thousand tokens make more logits than the Mac's GPU takes in one tensor. That gives the loss on each token, and whether the likeliest token was the right one, and it returns the loss on each half and the share of the second half it gets right. The file also runs episode twenty-two's pass key test, inside the window, as a Hyena filter is no longer than the window. And it times the milliseconds a token takes to write through the cache, after prompts of a quarter of the window up to most of it.
34:33 Flow dot py runs one text through an attention model and a Hyena model, so we can follow the numbers. It imports argparse for its arguments, json for its results, and os for their folder, then torch. From our own files, it takes the checkpoint loader, the results folder from hellaswag dot py, last episode's attention function, which keeps each head's weights, and pick device. The comment at the top says what it shows: for attention, a head's weights, from comparing each token's query with the keys before it. For Hyena, a channel's gates and filter, the matrix they make, and the last token's output worked through term by term. Hyena parts runs without gradients, as nothing here trains. The comment over it says what it gets: what one block's Hyena sees, from a hook on the norm before it, and what it makes of it, channel by channel. Seen starts empty, and a forward hook on that norm appends its output, which is what Hyena takes in, as the logit lens used hooks last time. The model runs once on the text, in a try, so the hook comes off whatever happens. Then streams gives x one, x two and v, channel by channel, for the one text. And it returns them, with the filter at the text's length, the skip b, the matrices, and the whole window's filters. Next tokens runs the model on the text, and returns its three likeliest next tokens, with their probabilities, from a softmax over the last position's logits, written as the token in quotes and a percentage. Far channel picks the channel whose last token draws most on the tokens more than two back, by the size of their weights, so the example we follow isn't one that looks at its neighbours alone. It takes each channel's last row of weights, and the share of its size that sits before the last three tokens, and keeps the channel with the largest share. Main's parser describes the script: one text through an attention model and a Hyena model, a head's weights, and a channel's gates, filter and matrix, with its last output worked out. It takes the attention model's checkpoint, the Hyena model's, and the text. By default, the block is two, the third, and the head is zero, and we're going to ask for block three and head two. The channel is the one that looks furthest back unless we give one, rows is how many terms of the last output to print, six, and the results go to flow dot json. Pick device chooses the GPU, as our other scripts do. It loads the attention model, and eval mode turns dropout off. It encodes the text, keeps each token as text for printing, and t is the last position. The head's weights come from the attention function, at our block and head, as last episode's viewer took them. It prints how many tokens, the block and the head, then the six tokens the head's last row puts the most on, each with its position, its text and its weight, to three decimals. Argsort, descending, puts the largest weights first. And the last line for attention is the model's likeliest next tokens. Then the Hyena model, which goes to eval mode too. Hyena parts gets its parts in that block, and far channel picks the channel, unless we gave one. It takes that channel's x one, x two, v, filter and skip. Z is x one times v, and it prints a header with the formula, and one for the columns. The terms are the filter's first t plus one taps, reversed so the newest token meets h zero, times z. Then it prints the last output's terms, newest token first: for each token s, x one, v, z, the filter at its distance, and h times z. Rest is the sum over the tokens before the ones printed, and total, the sum over all of them. Y is x two times the total plus the skip, b times z. It prints the rest and the total, then the skip, the gate and y, and the Hyena model's likeliest next tokens. The assert checks y against row t of the channel's matrix times its values, to within a thousandth, so the sum we work out is the operator's own number. And it writes the results to a JSON file, for our cards and charts: the tokens, the block, the head and the channel, the head's weights, the channel's matrix, its gates and values, its filter, its skip and y. Along with them go five channels' whole filters, from the slowest to fade to the fastest, and the one we followed, for the chart of the filters.
38:56 Recall dot py is a test from the Zoology paper, by Simran Arora and others at Stanford, from twenty twenty-three: multi-query associative recall. An example has pairs of a key and a value, then the keys again, here and there, each to be answered with its value. Attention can find a key by matching it against the tokens before, while a convolution weighs tokens by how far back they are, so it has to carry the pairs in its channels. Examples makes a batch from a vocabulary of eight thousand, one hundred and ninety-two tokens. Each example draws its own keys, from the lower half, and its own values, from the upper half, so there's nothing to memorise across examples. The pairs go at the start, two tokens each. Each key is asked once, in another order, at random places after the pairs, in a slot of two tokens: the key, then its value. The token after a query is the one to learn and to score, the value of the key just read, so the other targets are minus one, which cross entropy skips. Below it, the file trains models of two blocks, as in the paper: attention in both, Hyena in both, or Hyena and then attention. Each trains on fresh examples, four pairs at first, then up to eight, and so on up to sixty-four, with the next number allowed each fifth of the run. Drawn from all five numbers from the start, the hard batches drowned the easy ones, and on the Mac, no model learned the lookup. Then it scores the keys each model answers right, at each number of pairs.
Six small models
40:28 By six in the evening, the six small runs were done, half an hour each. Tail prints the last line of each log: the steps, the tokens, the minutes, the speed, with the evaluations along the way, and the memory. At a thousand and twenty-four tokens, attention got through about eight hundred and thirty-five million tokens. The hybrid got through about five hundred and sixty-two million, and Hyena about five hundred and thirty-one million, as on this GPU, its layers are the slower ones at that window. At four thousand and ninety-six tokens, attention gets through fewer, about six hundred and six million, and Hyena about four hundred and fifty-one million, still fewer. The evaluations take longer at four thousand tokens, for all three kinds.
41:12 Here's each half hour on a chart, from step a thousand on, as perplexity: e to the power of the loss, which spreads the lines apart. A perplexity of forty means the model is as unsure as if it picked among forty tokens. At a thousand and twenty-four tokens, on the left, attention ends at a loss of about three point six nine, a perplexity of about forty, and the hybrid at about forty-three. Hyena ends at a loss of about three point nine nine, a perplexity of about fifty-four. At four thousand and ninety-six tokens, on the right, they end in that order again, at perplexities of about forty-two, forty-four and fifty-eight. Compared at equal steps, so on as many tokens, the hybrid learns about as fast as attention, and Hyena more slowly. At step four thousand, at a thousand and twenty-four tokens, Hyena's loss is about four point one eight where attention's is about three point nine six. So on this GPU, at these windows, Hyena loses on both counts: the tokens it gets through, and what it learns from each.
A layer of each, on a 4090
42:14 To see why, as soon as the small runs were done, the second GPU timed a layer of each kind, with hyena bench dot py on sixty-five thousand, five hundred and thirty-six tokens a batch, and saved what it printed. At three hundred and eighty-four channels and two hundred and fifty-six tokens, attention's layer takes about nine point zero milliseconds, and Hyena's about twenty-two point six, more than twice as long. At four thousand and ninety-six tokens, attention takes about twelve point eight, and Hyena is still the slower, at about twenty-two point four. They meet at about sixteen thousand tokens, and at sixty-five thousand, attention takes about eighty milliseconds, about two point five times Hyena's thirty-two. At seven hundred and sixty-eight channels, each takes about twice as long, and they cross at about sixteen thousand tokens again.
43:05 Drawn as lines, attention's time grows with the window, as on the Mac. Hyena's stays nearly flat, but it starts far higher, so the lines cross at about sixteen thousand tokens, where on the Mac they crossed below a thousand. On the 4090, PyTorch's attention is FlashAttention, running in b float sixteen on the tensor cores, while our FFTs run in float thirty-two, on the ordinary cores, and read and write the whole sequence at each step. That's what the FlashFFTConv paper set out to fix, and the paper's authors had a fused kernel of their own for the convolution, which crossed FlashAttention between four and eight thousand tokens. At seven hundred and sixty-eight channels, on the right, the shapes are alike, so the crossing comes from the window and not the width.
Following the numbers
43:49 So, let's follow the numbers through the two small models trained at a thousand and twenty-four tokens, on a text whose next word has to be copied: Marie Curie was born in Warsaw, Marie Curie was born in. In the attention model, block three's head two is the one that looks back at the name from the last token. It puts about zero point four two of its weight on Warsaw, more than on any other token. And the model's likeliest next token is Warsaw, at about eighteen percent. In the Hyena model, block three's channel ten is the one whose last token draws most on the tokens more than two back. Its last output adds up a term for each token, and the newest, in, is weighed by h zero, about zero point three seven. Cur, the first half of Curie, four tokens back, is weighed by about minus zero point two eight, a negative tap. Then the sum, the skip and the gate give y, about zero point zero seven. And this model's likeliest next token is Paris, at about four percent: it doesn't copy the name.
44:54 On a card, here's channel ten's last output, newest token first: x one, v, their product z, the filter at each token's distance, and h times z. The two newest tokens get positive taps, and from two tokens back the filter is negative, which flips the sign of what each of those tokens adds. Cur has the largest z here, a negative one, so with its negative tap, its term is the largest, and positive. The nine tokens before them add the most, and with the skip, b times z, and the gate, x two, y comes to about zero point zero seven. Row fourteen of the channel's matrix, times its values, gives that y too, which flow dot py checks.
45:34 Here are the two matrices for the whole text. Each row is a token, and each square what it takes from a token up to it, so the rows grow by one square at a time, with nothing past the diagonal. On the left, attention's head, brighter where it takes more. Many rows lean on the first token, and the last row lights up on Warsaw, the name to copy, a single square picked out by matching. On the right, Hyena's channel ten, scaled by its largest entry, mint where it's positive and rose where it's negative. Its bright squares sit in a few columns, row after row: the first two tokens, and Warsaw. Those are tokens whose gate, x one, is large, and each row scales them by its own gate and by the filter at the distance. So a token here stands out for the rows after it by what its gate says, while in attention, a row picks the token that matches what it's looking for.
Side by side
46:28 Hyena eval dot py takes the three small models trained at a thousand and twenty-four tokens. For each, it prints the held-out loss on long web pages, the loss in the first and last sixty-four tokens of the window, the random tokens twice, the pass keys, and the writing speed. Attention's held-out loss is about three point five six, Hyena's about three point eight five, and the hybrid's about three point six two. Attention's loss falls from about three point eight nine in the first sixty-four tokens to about three point five three in the last, as the later tokens have more of the page to go on. Hyena's barely moves, from about three point nine four to about three point nine zero, so it makes little use of what it has read. Given random tokens twice, attention gets about seventeen percent of the second half right. Hyena gets none, and its loss on the second half is no lower than on the first, so the first copy doesn't help it at all. The hybrid, with attention in one block of six, gets about sixty-three percent, more than attention in all six. The pass keys are out of reach for models this small, a few percent at best. The writing times are noisy, as the Mac was rendering other videos at the time, so we're going to time writing on the 4090 instead.
47:44 Then the three trained at four thousand and ninety-six tokens, with the groups of positions two hundred and fifty-six tokens long. Attention's loss falls from about three point nine three in the first group to about three point seven zero in the last. Hyena's goes the other way, from about four point one one to about four point two zero, so for this model, a token deep in the window does worse than one near its start. Two thousand random tokens twice are too much for all three at this size: none of them copies more than a few percent. The pass keys are within reach, though: attention finds about forty percent of them in prompts of a thousand tokens, and fewer in longer ones. Hyena finds none, at any length. And the hybrid, with attention in one block of six, finds about twenty-six percent in a thousand tokens, and roughly what attention finds in the longer prompts.
48:35 Here's the perplexity by position at four thousand and ninety-six tokens. Attention's falls from about fifty-one in the first group of positions to about forty-one in the last, as each token has more of the page before it. Hyena's is higher all the way, and it ends higher than it starts, at about sixty-seven against sixty-one. Its filters weigh tokens by distance, fading over the window, and in a model this small, their far taps seem to add more noise than they help. The hybrid's line falls almost as attention's does, from about fifty-two to about forty-three: one block of attention is enough to use the whole window.
49:13 Side by side, the two tests of looking back. On the left, random tokens twice in windows of a thousand and twenty-four. Attention copies about seventeen percent of the second half, Hyena none, and the hybrid about sixty-three percent, the most of the three. On the right, the pass keys at four thousand and ninety-six tokens, over all four lengths. Attention finds about twenty-three percent of them, the hybrid about seventeen, and Hyena none.
49:40 Then the second GPU ran six minutes of episode nineteen's attention model, as this isn't the 4090 episode nineteen rented, and we want its speed on this machine. It trains at about one hundred and thirty-six thousand tokens a second, about what it did that night, one hundred and thirty-six thousand. Tonight's Hyena model runs at about eighty-two thousand, about zero point six one of attention's speed at this window, so its three point six billion tokens take the whole night, where episode nineteen's took under eight hours.
What the paper measured
50:10 Before our own numbers, here's what the paper measured. Table four point four trains on The Pile with GPT-2's tokenizer, for five, ten and fifteen billion tokens. At a hundred and twenty-five million parameters, GPT reaches a perplexity of thirteen point three, eleven point nine and eleven point two. A Hyena of a hundred and fifty-three million reaches thirteen point three, eleven point eight and eleven point one. At three hundred and fifty-five million, the two are within a tenth of each other, and Hyena takes about eighteen percent fewer operations. Figure four point three times a single layer with a batch of sixty-four. The authors' Hyena, which convolves with a fused CUDA kernel of their own, overtakes attention written in PyTorch at about two thousand tokens, and FlashAttention between four and eight thousand, and it's a hundred times faster at sixty-four thousand.
The night's models
51:01 By the morning, both of the night's runs had finished. Grep prints the last evaluation in Hyena's log, with its sample, and the totals. The sample says photosynthesis is the process of converting light energy into chemical energy, which is right. Its three point six billion tokens took about twelve point seven hours, and it ends at a held-out loss of about three point two four. Episode nineteen's attention model ended at about three point one one. The second GPU had a run of its own. At six in the evening, after the small models and the timings, it started a hybrid of this size, with attention in two blocks of twelve, the fourth and the tenth. That's the share of attention in the small hybrid, one block of six. It ran at about eighty-eight thousand tokens a second, a little faster than Hyena, so it took about eleven point nine hours. It ends at a held-out loss of about three point one zero eight, where attention ended at three point one one three.
51:58 Here are the three on one chart, by the tokens each had seen, as perplexity, from four hundred million tokens on. Episode nineteen's attention model ends at about twenty-two point five. Hyena's line is above it at all one hundred and thirty-two evaluations, by about seven at first and about three at the end, at about twenty-five point four. The hybrid's line is below attention's at one hundred and twenty-one of them, by about zero point eight for most of the night, and the two meet at the end, the hybrid at about twenty-two point four. The paper's Hyena matched GPT on The Pile with about a fifth more parameters, a hundred and fifty-three million against a hundred and twenty-five. Ours has about as many parameters as our attention model, and on our web pages, it doesn't catch up.
The 110M models, measured
52:45 Hyena eval dot py then measured episode nineteen's model and the night's Hyena on the first GPU, and the hybrid on the second, once it had finished. These are the small models' tests, at windows of a thousand and twenty-four. On long web pages, the hybrid's held-out loss is the lowest, at about two point nine seven, then attention's at about three point zero zero, and Hyena's at about three point one one. Attention's loss falls from about three point three two in the first sixty-four tokens to about two point nine six in the last. Hyena's starts a little lower, at about three point two eight, but falls to about three point one one, so it gains less from the rest of the window. Given random tokens twice, attention copies about twenty-seven percent of the second half. Hyena copies none, and its loss on the second half is barely lower than on the first. The hybrid copies about thirty-eight percent, the most of the three, as the small hybrid did. Attention finds about sixty-eight percent of the pass keys over the four lengths, fewer in the longest prompts. Hyena finds none. The hybrid finds about fifty-nine percent, a few fewer than attention at each length. The writing times were taken next to other runs on the machine, so once those had finished, the three were timed again, together, in one process. Writing a token after nine hundred and sixty takes attention about seven point four milliseconds, Hyena about six point two, about seventeen percent less, and the hybrid about six point four. Timed twice more, once in the other order, they moved by zero point six of a millisecond at most. Each takes about as long after two hundred and fifty-six tokens as after nine hundred and sixty, so at these lengths, the time goes mostly to starting each layer's work on the GPU, more than to the arithmetic.
54:29 By position, as perplexity, attention's falls from about twenty-seven point seven in the first sixty-four tokens to about nineteen point two in the last. Hyena's starts a little lower, at about twenty-six point five, and ends higher, at about twenty-two point five. The hybrid's starts lower still, at about twenty-five point four, and ends with attention's, at about nineteen point two. On the right, the copying: Hyena copies none of the second half, and the hybrid about thirty-eight percent, more than attention's twenty-seven.
55:02 The pass keys: attention finds about sixty-eight percent, the hybrid about fifty-nine, and Hyena none. And writing a token, timed together on the idle machine: Hyena takes about six point two milliseconds, against attention's seven point four.
HellaSwag and bits
55:17 HellaSwag, from episode nineteen: ten thousand and forty-two beginnings of a scene, each with four endings, where guessing gets twenty-five percent. Episode nineteen's model gets about twenty-nine point four five percent on this GPU, as it did on that night's. Hyena gets about twenty-eight point nine four, about half a percent fewer, which is about what chance alone moves a score on a test this size. The hybrid gets about twenty-nine point four one, level with attention. Bits dot py measures the bits each model needs for a character of held-out web text, where fewer is better. Attention needs about zero point nine five six, Hyena about zero point nine eight nine, and the hybrid about zero point nine four nine, the fewest of the three.
56:02 On HellaSwag, the three sit within about half a percent of each other, just under GPT-2 small's twenty-nine point five five percent. And on the right, what each cost: on the 4090, attention trains on about one hundred and thirty-six thousand tokens a second, Hyena on about eighty-two thousand, and the hybrid on about eighty-eight thousand.
Recall
56:21 After its evaluations, the first GPU ran recall dot py: two blocks of each kind, at three widths. Each trained for thirty thousand steps on windows of two hundred and fifty-six tokens, at a learning rate of one in a thousand. The hybrid answers nearly all the keys at all three widths, up to sixty-four pairs. Attention with sixty-four channels does too. With a hundred and twenty-eight or two hundred and fifty-six, it stalls at about half the keys with four pairs, and about five percent with sixty-four. Hyena stalls at all three widths. A wider model doing worse than a narrow one looked like a learning rate that suits one width and not another, so the grid ran twice more. The first GPU ran it at three in ten thousand, where even attention with sixty-four channels stalls. The second GPU ran it at three in a thousand. With a hundred and twenty-eight or two hundred and fifty-six channels, attention stalls at all three rates, and so does Hyena. A stalled model answers between about zero point seven and four point two keys an example, however many pairs there are, so it has learned something, but not the lookup.
57:27 Here's each model at its best of the three rates, by the number of pairs. With sixty-four channels, on the left, attention and the hybrid answer nearly all the keys, up to sixty-four pairs, while Hyena falls from about forty-two percent with four pairs to about one with sixty-four. With two hundred and fifty-six channels, on the right, attention falls as Hyena does. The hybrid answers all the keys there, at all five numbers of pairs. Its first block's short convolution hands each token the one before it, so a value already carries its key, and the attention block has the matching left to do. Attention alone has to learn that first half of the lookup too. In the Zoology paper, attention solved this with sixty-four channels and more, after a sweep of four learning rates up to one in a hundred, so our stall at the wider two is more likely our training than attention. The paper also found that gated convolutions like Hyena need at least as many channels as the window has tokens. Our widest Hyena has two hundred and fifty-six channels for windows of two hundred and fifty-six tokens, right at that line, and it stalls.
The scorecard
58:31 Here's everything on one card: the three models of a hundred and ten million parameters, side by side, a row a measurement, with the best of each row lit as we go. Attention trains the fastest on a 4090, in the least memory. After three point six billion tokens, attention and the hybrid end level, with Hyena behind. On long pages, the hybrid's loss is the lowest, and so are its bits a character. On HellaSwag, the three are level, within what chance moves a score. The hybrid copies the most of the random tokens, and attention finds the most pass keys. Hyena writes a token in the least time, about seventeen percent less than attention, and it keeps the smallest cache, half of attention's, while the hybrid's two blocks of attention add a little to it.
What came after
59:16 Hyena came out of a line of work at Stanford. H3, from twenty twenty-two, is the paper's operator of order two, with its filters from state space models. Hyena made the filters implicit, from a small network of the position. Later in twenty twenty-three, FlashFFTConv, by Dan Fu and others, computed the FFT with the GPU's matrix units, and found it up to about eight times faster than PyTorch's, which is the kind of kernel our plain PyTorch version lacks. StripedHyena, from Together AI, mixed Hyena blocks with attention blocks, and the Evo models, from the Arc Institute, use that design on DNA, with contexts of a hundred and thirty-one thousand tokens and more. Mamba, from Albert Gu and Tri Dao, made the filter depend on the tokens, as a recurrence with a state of a fixed size, so writing a token takes a fixed amount of work, however long the text. And the language models that use these layers today, such as Jamba, keep some attention layers among them, the hybrid we tried.
1:00:18 If there's another way of mixing tokens you'd like us to try against attention, let me know in the comments. And if you'd like to follow along, subscribe to the channel. I hope you find this useful, and thanks for watching.