Hyena is an operator that replaces attention by interleaving long convolutions as long as the input with element-wise gates determined by the input. It was proposed by Poli et al. in 2023 in the paper "Hyena Hierarchy: Towards Larger Convolutional Language Models."
The cost of attention in the Transformer grows with the square of the sequence length L. Methods that reduce it, such as linear attention, Performer, and sparse attention, lose performance, so they could not match the Transformer without mixing in standard attention layers.
The paper identifies three properties linked to the performance of attention and designs an operator that satisfies them.
Property
Meaning
Attention
Hyena
Data control
The linear operation applied to the input itself changes depending on the input
The attention matrix is determined by q,k
The gates are determined by the input
Sublinear parameter scaling
Making the sequence longer does not add parameters
Only the projection weights
Filters are built by a small FFN
Unrestricted context
Can represent the relationship between any two positions
Looks at every pair
Filters span the whole sequence
Hyena computes the long convolutions in O(LlogL) with the FFT, so it becomes faster the longer the sequence. In the paper, it was about 2 times faster than FlashAttention at length 8,000 and about 100 times faster at length 64,000. On language modeling with The Pile, it reached the same perplexity as GPT with 20% less training compute.
Theory: the Hyena operator
Like attention, the Hyena operator creates linear projections of the input, and then repeatedly applies long convolutions and gates to one of them (v). The computation of a Hyena operator of order N proceeds as follows (Algorithms 1 to 3 of the paper).
Create the projections: expand the input u (length L, width D) to (N+1)D with a linear projection, pass it through a short per-feature convolution, and split it into v,x1,โฆ,xN. These correspond to attention's q,k,v, but are not limited to three.
Build the long convolution filters: produce h1,โฆ,hN with a small FFN that takes the time t as input (Equation (7) below).
Alternate convolutions and gates: starting from z1=v, repeat the following equation (Equation (4) of the paper) for n=1,โฆ,N.
Use the final value as the output: pass y=zN+1 through the output linear projection.
ztn+1โ=xtnโโ (hnโzn)tโ(n=1,โฆ,N),y=zN+1
Written in one line, y=xNโ (hNโ(xNโ1โ (hNโ1โโฏ))). The convolution โ is computed with the FFT. The center of the figure at the top of the article shows the flow for order 2.
How the filters are built (Section 3.3 of the paper): learning the filter values one by one (explicit parameterization) makes the number of parameters proportional to the filter length. Hyena instead represents the filter as a function of time t with a small FFN (implicit parameterization).
htโ=Window(t)โ (FFNโPositionalEncoding)(t)
Positional encoding: the real and imaginary parts of the complex exponentials ei2ฯkt/L placed side by side (Appendix D.3).
FFN activation: sine is used so that filters with high-frequency components can also be learned.
Window: an exp(โฮฑt) decay is applied. ฮฑ varies by channel, providing filters of different lengths. In practice a bias is added to the window so that it never becomes exactly 0 beyond a certain length.
This decouples the filter length (memory length) from the number of parameters. S4 is also a form of implicit parameterization that builds the kernel from SSM parameters, and the paper notes that the FFN representation can approximate it as well.
Why it can replace attention
Viewed as matrices, Hyena is an operation that multiplies the input by "a matrix determined by the input" (Section 3.2 of the paper). With Dxโ=diag(x) a diagonal matrix and Shโ the Toeplitz matrix (convolution matrix) of filter h, it can be written as follows.
y=H(u)v=DxNโShNโโฏDx2โSh2โDx1โSh1โv
Attention is also an operation, y=A(q,k)v, that multiplies v by an input-dependent matrix A. Rather than building this matrix as L2 entries, Hyena keeps it factored into a product of diagonal matrices (gates) and Toeplitz matrices (convolutions). Both can be applied without materializing the matrix, so the computation takes O(NLlogL).
Long convolutions carry information far along the time axis, extending the memory length.
Gates select which positions and components to let through depending on the input. Element-wise multiplication in time corresponds to convolution in frequency, so alternating convolutions and gates is equivalent to convolving alternately in both time and frequency.
As an analogy, the long convolution is "a conveyor belt that carries past information, blurred by a fixed rule," and the gate is "a worker who looks at the current input and decides which of the carried items to pick up."
Hyena of order N=2 has the same form as H3, which sandwiches an SSM between two gates, and N=1 has the same form as GSS (Gated State Spaces) (Remark 3.2 of the paper). Hyena replaces these convolutions with filters built by an FFN instead of an SSM and generalizes the order.
Experimental results
Associative recall (vocabulary size 30, accuracy %. Table 4.2 of the paper. 2-layer models): a task in which a sequence of key-value pairs is followed by a key, and the model must answer with the corresponding value.
In an experiment comparing ways of building long convolutions (Figure 4.1 of the paper), filters built by an FFN (Hyena, CKConv) gave better results than standard convolutions, frequency-domain parameterization, and SSMs (H3), increasingly so as sequences got longer and vocabularies larger.
The Pile (trained on 15B tokens. Table 4.4 of the paper. FLOPs in units of 1019)
Model
Perplexity
Training FLOPs
GPT (125M)
11.2
1.88
Hyena-2 (153M)
11.1
1.87
GPT (355M)
9.1
4.77
Hyena-2 (355M)
9.2
3.93
Hyena reached perplexity comparable to the Transformer without mixing in attention, and at 355M parameters it cut training compute by about 20%.
Image classification (ImageNet-1k, top-1 accuracy %. Table 4.7 of the paper): replacing attention in ViT with Hyena gave 78.5% with 16ร16 patches, the same as ViT, and 79.8% with 8ร8 patches (sequence length 1,024), versus 80.0% for ViT.
Speed (Section 4.4 of the paper): Hyena overtakes attention at a length of about 2,000 and FlashAttention between lengths 4,096 and 8,192, and is about 100 times faster at length 64,000.
Caveats in practice
When using Hyena, keep the following points in mind.
It is not faster on short sequences: FFT-based convolution uses the GPU less efficiently than FlashAttention, so even with fewer operations, it does not win on speed until the length exceeds a few thousand.
Causality is preserved by the filters and padding: in language models, if each filter does not look at the future (is causal), the whole Hyena operator is causal as well (Proposition 3.1 of the paper). When computing with the FFT, evaluate the filter at t=0,โฆ,Lโ1, and pad the input and the filter to a length of at least 2Lโ1 before applying the FFT.
GPT's training settings are not necessarily optimal: the paper trains with the same hyperparameters as GPT, but recommends a slightly lower learning rate for Hyena than for GPT.
In its training form, Hyena's long convolution recomputes the convolution over the entire past each time a new token is generated. Unlike SSMs or linear RNNs, it does not update a fixed-size state one step at a time, so the cost of one generation step grows with the context length. If you need fast generation, check this point against Mamba and RWKV.
The language models that the paper shows matching the Transformer were experiments at scales of up to 1.3B parameters. Performance at larger scales and the availability of pretrained models do not match the Transformer, so verify on your own task before adopting it for large models. The paper also states that if only final performance on sequences up to about 8,000 matters, mixing in attention layers as in H3 gives better results.
Comparison with other models
Within the line of attention-free operators, Hyena is positioned as follows (Section 2.2 of the paper).
AFT (Attention-Free Transformer): builds the operation from gates and softmax, or from gates and a single explicit convolution.
GSS: builds the operation from gates and a long convolution produced by an SSM (corresponds to Hyena of order 1).
H3: adds one more gate and a short convolution (shift SSM) to GSS (corresponds to Hyena of order 2).
Hyena: generalizes this to repeated gates and long convolutions built by an FFN.
The Mamba paper points out that even gated architectures like Hyena mix along the sequence (the convolution kernel) independently of the input, so they struggle with the "selective copying" task, where the spacing between symbols changes every time. In the Mamba paper's experiments, a model with Hyena layers inside H3 blocks reached 30.1% accuracy.
Lining up sequence models that replace the Transformer from the same angles gives the following.
To handle long sequences of tens to hundreds of thousands of tokens with properties close to attention: Hyena is a good fit. The speed advantage grows with sequence length.
To generate at a constant speed: consider Mamba, RWKV, or RetNet, which can update their state one step at a time.
For sequences of a few thousand where performance comes first: compute the Transformer with FlashAttention, or mix in attention layers.
PyTorch example
โถShow code
python
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
A small implementation of the Hyena operator (Equations (4) and (7) and Algorithms 1-3 of the paper)
- Filter: h_t = Window(t) ยท FFN(PositionalEncoding(t)). The positional encoding is a complex exponential basis (Appendix D.3),
the FFN activation is sin, and the window is exp(-ฮฑ t) plus a bias (ฮฑ varies by channel)
- Operator: linear projection -> short convolution -> split into v, xยน, โฆ, x^N, then repeat z โ x^n โ (h^n โ z) N times
- Long convolutions are computed with the FFT, padded to length 2L to make them causal (not looking at the future)
For practical use, use the FFTConv kernel from the official implementation (safari)
"""
class Sin(nn.Module):
def __init__(self, dim, w=14.0): # sine freq. in Table A.4 of the appendix
super().__init__()
self.freq = nn.Parameter(w * torch.ones(1, dim))
def forward(self, x):
return torch.sin(self.freq * x)
class HyenaFilter(nn.Module):
"""Builds length-L filters for order ร d_model channels at once"""
def __init__(self, d_model, order, emb_dim=33, ffn_width=64, max_len=1024, fast_decay=0.3, slow_decay=1.5, bias=0.01):
super().__init__()
self.d_model, self.order = d_model, order
# Positional encoding: [t, Re ฯ_k(t), Im ฯ_k(t)], ฯ_k(t) = exp(i 2ฯ k t / L) (Appendix D.3, De = 2K + 1)
K = (emb_dim - 1) // 2
t = torch.linspace(0, 1, max_len)[:, None] # [L, 1]
tt = torch.arange(max_len)[:, None].float()
f = torch.arange(K)[None, :].float()
z = torch.exp(-1j * 2 * math.pi * f * tt / max_len)
self.register_buffer('pe', torch.cat([t, z.real, z.imag], dim=-1)) # [L, De]
self.register_buffer('t', t)
self.ffn = nn.Sequential(
nn.Linear(emb_dim, ffn_width), Sin(ffn_width),
nn.Linear(ffn_width, ffn_width), Sin(ffn_width),
nn.Linear(ffn_width, order * d_model, bias=False))
# Window exp(-ฮฑ t): vary ฮฑ by channel to spread out filter lengths (the range of ฮฑ is an example)
max_decay, min_decay = math.log(1e-2) / fast_decay, math.log(1e-2) / slow_decay
self.register_buffer('deltas', torch.linspace(min_decay, max_decay, order * d_model)[None, :])
self.bias = bias
def forward(self, L):
h = self.ffn(self.pe[:L]) # [L, order*D]
h = h * (torch.exp(-self.t[:L] * self.deltas.abs()) + self.bias) # apply the window (the bias keeps it from reaching 0)
return h.T.reshape(self.order, self.d_model, L) # [order, D, L]
def fft_conv(u, h):
"""u: [B, D, L], h: [D, L]. Pad to length 2L and do a causal convolution with the FFT"""
L = u.shape[-1]
y = torch.fft.irfft(torch.fft.rfft(u, n=2 * L) * torch.fft.rfft(h, n=2 * L), n=2 * L)[..., :L]
return y
class HyenaOperator(nn.Module):
def __init__(self, d_model, order=2, max_len=1024, short_filter=3):
super().__init__()
self.order = order
self.in_proj = nn.Linear(d_model, (order + 1) * d_model) # D -> (N+1)D
self.short_conv = nn.Conv1d((order + 1) * d_model, (order + 1) * d_model, short_filter,
groups=(order + 1) * d_model, padding=short_filter - 1)
self.filter = HyenaFilter(d_model, order, max_len=max_len)
self.out_proj = nn.Linear(d_model, d_model)
def forward(self, u): # u: [B, L, D]
L = u.shape[1]
z = self.in_proj(u).transpose(1, 2) # [B, (N+1)D, L]
z = self.short_conv(z)[..., :L] # short convolution that does not look at the future
*xs, v = z.chunk(self.order + 1, dim=1) # xยน, โฆ, x^N and v
h = self.filter(L) # [N, D, L]
for n in range(self.order): # z โ x^n โ (h^n โ z)
v = xs[n] * fft_conv(v, h[n])
return self.out_proj(v.transpose(1, 2))
class HyenaBlock(nn.Module):
"""A Transformer layer with attention replaced by the Hyena operator"""
def __init__(self, d_model, max_len=1024):
super().__init__()
self.norm1, self.norm2 = nn.LayerNorm(d_model), nn.LayerNorm(d_model)
self.mixer = HyenaOperator(d_model, order=2, max_len=max_len)
self.mlp = nn.Sequential(nn.Linear(d_model, 4 * d_model), nn.GELU(), nn.Linear(4 * d_model, d_model))
def forward(self, x):
x = x + self.mixer(self.norm1(x))
return x + self.mlp(self.norm2(x))
if __name__ == "__main__":
torch.manual_seed(0)
block = HyenaBlock(d_model=64, max_len=512)
x = torch.randn(2, 512, 64)
y = block(x)
print(y.shape) # torch.Size([2, 512, 64])
# Check causality: changing later inputs does not change earlier outputs
x2 = x.clone(); x2[:, 300:] = torch.randn_like(x2[:, 300:])
print('Difference in the first-half outputs:', (block(x2)[:, :300] - y[:, :300]).abs().max().item()) # almost 0
FAQ
Q. Is Hyena a CNN?
A.
It uses convolutions, but differs from an ordinary CNN in two ways: the filters are as long as the input, L, and see the whole sequence, and the filter values are not learned directly but built by a small FFN that takes the time t as input. In addition, it applies gates determined by the input, so the overall operation changes with the input.
Q. Why is it called "Hyena"?
A.
The paper does not explain the origin of the name. It is an operator in the lineage of H3 (Hungry Hungry Hippos), proposed before Hyena, and generalizes H3 to order N.
Q. How should the order $N$ be chosen?
A.
The paper's language models use order 3 on WikiText-103 and order 2 on The Pile. Raising the order increases the expressiveness of the input-dependent matrix, but it also increases the number of FFT convolutions, and the cost grows as O(NDL(log2โL+D)).