AI Logic

Architectures

Hyena

Updated๏ผš

Architecture of Hyena. The left shows the overall flow as a language model (attention in each Transformer layer is replaced by the Hyena operator, while the MLP and residual connections stay the same). The center shows the order-2 Hyena operator (a linear projection and short convolution produce v, xยน, and xยฒ; v is multiplied in turn by the long convolution hยน, gate xยน, long convolution hยฒ, and gate xยฒ, then passed to the output projection). The right shows how the long convolution filters are built (a positional encoding of time t is passed through a small FFN with sine activations and multiplied by an exponential window)

Background and overview

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 LL. 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.

PropertyMeaningAttentionHyena
Data controlThe linear operation applied to the input itself changes depending on the inputThe attention matrix is determined by q,kq, kThe gates are determined by the input
Sublinear parameter scalingMaking the sequence longer does not add parametersOnly the projection weightsFilters are built by a small FFN
Unrestricted contextCan represent the relationship between any two positionsLooks at every pairFilters span the whole sequence

Hyena computes the long convolutions in O(LlogโกL)O(L \log L) 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 (vv). The computation of a Hyena operator of order NN proceeds as follows (Algorithms 1 to 3 of the paper).

  1. Create the projections: expand the input uu (length LL, width DD) to (N+1)D(N+1)D with a linear projection, pass it through a short per-feature convolution, and split it into v,x1,โ€ฆ,xNv, x^1, \dots, x^N. These correspond to attention's q,k,vq, k, v, but are not limited to three.
  2. Build the long convolution filters: produce h1,โ€ฆ,hNh^1, \dots, h^N with a small FFN that takes the time tt as input (Equation (7) below).
  3. Alternate convolutions and gates: starting from z1=vz^1 = v, repeat the following equation (Equation (4) of the paper) for n=1,โ€ฆ,Nn = 1, \dots, N.
  4. Use the final value as the output: pass y=zN+1y = z^{N+1} through the output linear projection.
ztn+1=xtnโ‹…(hnโˆ—zn)t(n=1,โ€ฆ,N),y=zN+1z^{n+1}_t = x^n_t \cdot (h^n * z^n)_t \quad (n = 1, \dots, N), \qquad y = z^{N+1}

Written in one line, y=xNโ‹…(hNโˆ—(xNโˆ’1โ‹…(hNโˆ’1โˆ—โ‹ฏโ€‰)))y = x^N \cdot (h^N * (x^{N-1} \cdot (h^{N-1} * \cdots))). 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 tt with a small FFN (implicit parameterization).

ht=Window(t)โ‹…(FFNโˆ˜PositionalEncoding)(t)h_t = \mathrm{Window}(t) \cdot (\mathrm{FFN} \circ \mathrm{PositionalEncoding})(t)
  • Positional encoding: the real and imaginary parts of the complex exponentials ei2ฯ€kt/Le^{i 2\pi k t / 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)\exp(-\alpha t) decay is applied. ฮฑ\alpha 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)D_x = \mathrm{diag}(x) a diagonal matrix and ShS_h the Toeplitz matrix (convolution matrix) of filter hh, it can be written as follows.

y=H(u)โ€‰v=DxNShNโ‹ฏDx2Sh2โ€‰Dx1Sh1โ€‰vy = H(u)\, v = D_x^N S_h^N \cdots D_x^2 S_h^2\, D_x^1 S_h^1\, v

Attention is also an operation, y=A(q,k)โ€‰vy = A(q, k)\, v, that multiplies vv by an input-dependent matrix AA. Rather than building this matrix as L2L^2 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(NLlogโกL)O(NL \log L).

  • 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=2N = 2 has the same form as H3, which sandwiches an SSM between two gates, and N=1N = 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.

Sequence lengthHyenaTransformer (FlashAttention)GSSH3AFTRWKV
30,000100.032.45.38.42.312.4
64,000100.026.72.14.31.26.5
131,00097.2Out of memory0.10.60.82.3

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.

Language modeling (perplexity, lower is better)

WikiText-103 (125M parameters. Table 4.3 of the paper)

ModelPerplexity
Transformer18.6
Hybrid H3 (with attention mixed in)18.5
Performer26.8
Reformer25.6
Linear attention25.6
Hyena-3 (order 3)18.6
Hyena-3-slim (deeper and narrower)18.5

The Pile (trained on 15B tokens. Table 4.4 of the paper. FLOPs in units of 101910^{19})

ModelPerplexityTraining FLOPs
GPT (125M)11.21.88
Hyena-2 (153M)11.11.87
GPT (355M)9.14.77
Hyena-2 (355M)9.23.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โˆ’1t = 0, \dots, L-1, and pad the input and the filter to a length of at least 2Lโˆ’12L - 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.

ModelHow the sequence is mixedDoes forgetting of the state depend on the input?Training costOne generation step
TransformerSoftmax attentionNo state (keeps the entire past)Quadratic in lengthProportional to length so far
Linear attentionAdds feature-map inner products into a stateDoes not forget (only adds)Linear in lengthConstant
S4Linear SSM (initialized with HiPPO)NoNearly linear in length (FFT)Constant
HyenaLong convolutions and element-wise gatesNo (the kernel is fixed; the gates depend on the input)Nearly linear in length (FFT)Not constant as a convolution
MambaSSM whose parameters depend on the inputYesLinear in length (parallel scan)Constant
Mamba-2SSM with state decay restricted to a scalarYesLinear in length (mainly matrix multiplications)Constant
RWKVLinear RNN with an exponentially decaying weighted averageNo (constant per channel)Linear in lengthConstant
RetNetRetention with decayNo (constant per head)Quadratic when parallel, linear when chunkedConstant

Rough guidelines for choosing are as follows.

  • 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, LL, and see the whole sequence, and the filter values are not learned directly but built by a small FFN that takes the time tt 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 NN.

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(logโก2L+D))O(NDL(\log_2 L + D)).

References

  1. M. Poli, S. Massaroli, E. Nguyen, D. Y. Fu, T. Dao, S. Baccus, Y. Bengio, S. Ermon, and C. Rรฉ, "Hyena Hierarchy: Towards Larger Convolutional Language Models," arXiv:2302.10866, 2023.
  2. A. Gu and T. Dao, "Mamba: Linear-Time Sequence Modeling with Selective State Spaces," arXiv:2312.00752, 2023.
  3. Official implementation (safari)