SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2209.10655 · ICLR · 2023

Mega: Moving Average Equipped Gated Attention

Graham Neubig, Xuezhe Ma, Xiang Kong, Luke Zettlemoyer, Jonathan May, Chunting Zhou, Liangke Gui, Meta Research

arXiv · PDF · Open in the Atlas

Code that ran

12 of 13 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (6 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 7 have no contract verdict; 5 failures of our instrument; 1 no recorded run), measured 2026-11-23; repository links from the Papers with Code archive attributed under CC BY-SA, no affiliation; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2209.10655.json · badge: /api/ran/2209.10655.svg

Each repository's role is a label: a classifier's output recorded on the link, or, where no role is recorded, what the Papers with Code archive marked. The line under it names its basis. Neither says who wrote the code.

RepositoryRoleRan
facebookresearch/mega canonical (classifier label)
classifier basis not recorded on the link
3 ran · 0 no recorded run
ZIZUN/MAFiD community
Papers with Code archive
7 ran · 1 no recorded run
lucidrains/gated-state-spaces-pytorch community
Papers with Code archive
2 ran · 0 no recorded run
FunctionStatusWhere it lives
DSS Ran
ran on a synthesized input
lucidrains/gated-state-spaces-pytorch/gated_state_spaces_pytorch/gss.py
code served (permissive licence) · get_code("7cf1fc5a8fb4711f")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned Tensor, ndim 3, dtype family float, shape (2, 3, 4) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
from torch import nn
from einops import rearrange

class DSS(nn.Module):

    def __init__(self, *, dim, kernel_N=512, dss_kernel_lambda_imag_exp=True):
        super().__init__()
        self.norm = nn.LayerNorm(dim)
        self.Lambda_real = nn.Parameter(torch.randn(kernel_N))
        self.Lambda_imag = nn.Parameter(torch.randn(kernel_N))
        self.C_real = nn.Parameter(torch.randn(dim, kernel_N))
        self.C_imag = nn.Parameter(torch.randn(dim, kernel_N))
        self.param_D = nn.Parameter(torch.randn(dim))
        self.dss_kernel_lambda_imag_exp = dss_kernel_lambda_imag_exp

    def forward(self, x):
        """
        einstein notation:
        b - batch
        l - sequence length
        d - dimension
        """
        from torch.fft import rfft, irfft
        from torch import einsum
        
        device, seq_len = (x.device, x.shape[1])
        u = self.norm(x)
        residual = u * self.param_D
        Lambda_imag = self.Lambda_imag.exp() if self.dss_kernel_lambda_imag_exp else self.Lambda_imag
        Lambda = -self.Lambda_real.exp() + 1j * Lambda_imag
        C = self.C_real + 1j * self.C_imag
        arange = torch.arange(seq_len, device=device)
        S = (rearrange(Lambda, 'n -> n 1') * rearrange(arange, 'l -> 1 l')).exp()
        C = C * (Lambda.exp() - 1) / Lambda
        K = einsum('h n, n l -> l h', C, S).real
        u_f = rfft(u, n=seq_len * 2, dim=-2)
        K_f = rfft(K, n=seq_len * 2, dim=-2)
        y = irfft(u_f * K_f, seq_len * 2, dim=-2)[..., :seq_len, :]
        return y + residual


INIT_ARGS = {
    'dim': 4,
    'kernel_N': 8,
    'dss_kernel_lambda_imag_exp': True,
}

ARGS = {
    'x': torch.randn(2, 3, 4),
}

if __name__ == '__main__':
    model = DSS(**INIT_ARGS)
    output = model(**ARGS)
    print(f"Output shape: {output.shape}")
    print(f"Output dtype: {output.dtype}")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
einops, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 3, dtype family float, shape (2, 3, 4) — shape (2, 3, 4) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
Embedding Ran
ran; our contract draft was wrong, not the code · constructed an object; no result was computed
facebookresearch/mega/fairseq/models/mega.py
pointer only (licence: MIT); the stored copy get_code serves, from instance-wise-ordered-transformer/iot, is pointer only (licence: NOASSERTION) · get_code("96cbb5e9ca5b6be0")
How it ran

The body of this sample is withheld: this paper's link allows the body inline (MIT), but get_code serves the stored copy, first harvested from instance-wise-ordered-transformer/iot, and GitHub could not classify the licence of that repository (NOASSERTION). The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

GSS Ran
ran on a synthesized input
lucidrains/gated-state-spaces-pytorch/gated_state_spaces_pytorch/gss.py
code served (permissive licence) · get_code("e0fb8682bea0936e")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned Tensor, ndim 3, dtype family float, shape (2, 3, 4) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
from torch import nn

# Import the classes
from torch.fft import rfft, irfft
from einops import rearrange

class DSS(nn.Module):

    def __init__(self, *, dim, kernel_N=512, dss_kernel_lambda_imag_exp=True):
        super().__init__()
        self.norm = nn.LayerNorm(dim)
        self.Lambda_real = nn.Parameter(torch.randn(kernel_N))
        self.Lambda_imag = nn.Parameter(torch.randn(kernel_N))
        self.C_real = nn.Parameter(torch.randn(dim, kernel_N))
        self.C_imag = nn.Parameter(torch.randn(dim, kernel_N))
        self.param_D = nn.Parameter(torch.randn(dim))
        self.dss_kernel_lambda_imag_exp = dss_kernel_lambda_imag_exp

    def forward(self, x):
        """
        einstein notation:
        b - batch
        l - sequence length
        d - dimension
        """
        device, seq_len = (x.device, x.shape[1])
        u = self.norm(x)
        residual = u * self.param_D
        Lambda_imag = self.Lambda_imag.exp() if self.dss_kernel_lambda_imag_exp else self.Lambda_imag
        Lambda = -self.Lambda_real.exp() + 1j * Lambda_imag
        C = self.C_real + 1j * self.C_imag
        arange = torch.arange(seq_len, device=device)
        S = (rearrange(Lambda, 'n -> n 1') * rearrange(arange, 'l -> 1 l')).exp()
        C = C * (Lambda.exp() - 1) / Lambda
        K = einsum('h n, n l -> l h', C, S).real
        u_f = rfft(u, n=seq_len * 2, dim=-2)
        K_f = rfft(K, n=seq_len * 2, dim=-2)
        y = irfft(u_f * K_f, seq_len * 2, dim=-2)[..., :seq_len, :]
        return y + residual

class GSS(nn.Module):
    """ Pseudocode 3.2 """

    def __init__(self, *, dim, dim_expansion_factor=4, dss_kernel_N=512, dss_kernel_H=256, reverse_seq=False, dss_kernel_lambda_imag_exp=True):
        super().__init__()
        self.reverse_seq = reverse_seq
        self.norm = nn.LayerNorm(dim)
        dim_hidden = int(dim_expansion_factor * dim)
        self.to_u = nn.Sequential(nn.Linear(dim, dim_hidden, bias=False), nn.GELU())
        self.to_v = nn.Sequential(nn.Linear(dim, dss_kernel_H, bias=False), nn.GELU())
        self.dss = DSS(dim=dss_kernel_H, kernel_N=dss_kernel_N, dss_kernel_lambda_imag_exp=dss_kernel_lambda_imag_exp)
        self.to_gate = nn.Linear(dss_kernel_H, dim_hidden, bias=False)
        self.to_out = nn.Linear(dim_hidden, dim)

    def forward(self, x):
        if self.reverse_seq:
            x = torch.flip(x, dims=(1,))
        residual, x = (x.clone(), self.norm(x))
        u = self.to_u(x)
        v = self.to_v(x)
        v = self.dss(v)
        uc = self.to_gate(v)
        out = self.to_out(uc * u)
        out = out + residual
        if self.reverse_seq:
            out = torch.flip(out, dims=(1,))
        return out

from torch import einsum

INIT_ARGS = {
    'dim': 4,
    'dim_expansion_factor': 4,
    'dss_kernel_N': 64,
    'dss_kernel_H': 8,
    'reverse_seq': False,
    'dss_kernel_lambda_imag_exp': True,
}

ARGS = {
    'x': torch.randn(2, 3, 4),
}

if __name__ == '__main__':
    model = GSS(**INIT_ARGS)
    output = model(**ARGS)
    print(f"Output shape: {output.shape}")
    print(f"Expected shape: (2, 3, 4)")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
einops, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 3, dtype family float, shape (2, 3, 4) — shape (2, 3, 4) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
LaplacianAttnFn Ran
ran on a synthesized input
ZIZUN/MAFiD/src/model.py
pointer only (licence: NONE) · get_code("28048afa2b58e989")
How it ran

The body of this sample is withheld: GitHub detected no licence in this paper's repository, ZIZUN/MAFiD when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

Linear Ran
ran; our contract draft was wrong, not the code · constructed an object; no result was computed
facebookresearch/mega/fairseq/models/mega.py
pointer only (licence: MIT); the stored copy get_code serves, from instance-wise-ordered-transformer/iot, is pointer only (licence: NOASSERTION) · get_code("8cd8cb0d1e9e63e4")
How it ran

The body of this sample is withheld: this paper's link allows the body inline (MIT), but get_code serves the stored copy, first harvested from instance-wise-ordered-transformer/iot, and GitHub could not classify the licence of that repository (NOASSERTION). The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

MultiHeadedEMA Ran
ran on a synthesized input · constructed an object; no result was computed
ZIZUN/MAFiD/src/model.py
pointer only (licence: NONE) · get_code("d65478e4afde1394")
How it ran

The body of this sample is withheld: GitHub detected no licence in this paper's repository, ZIZUN/MAFiD when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

OffsetScale Ran
ran on a synthesized input · constructed an object; no result was computed
ZIZUN/MAFiD/src/model.py
pointer only (licence: NONE) · get_code("fd172a441158b8cf")
How it ran

The body of this sample is withheld: GitHub detected no licence in this paper's repository, ZIZUN/MAFiD when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

SingleHeadedAttention Ran
ran on a synthesized input · constructed an object; no result was computed
ZIZUN/MAFiD/src/model.py
pointer only (licence: NONE) · get_code("bf0381787b2cfd85")
How it ran

The body of this sample is withheld: GitHub detected no licence in this paper's repository, ZIZUN/MAFiD when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

T5RelativePositionBias Ran
ran on a synthesized input · constructed an object; no result was computed
ZIZUN/MAFiD/src/model.py
pointer only (licence: NONE) · get_code("75a6e13f59e67f7e")
How it ran

The body of this sample is withheld: GitHub detected no licence in this paper's repository, ZIZUN/MAFiD when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

append_dims Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
ZIZUN/MAFiD/src/model.py
pointer only (licence: NONE) · get_code("af830e39fdd08afa")
How it ran

The body of this sample is withheld: GitHub detected no licence in this paper's repository, ZIZUN/MAFiD when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

conv1d_fft Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
ZIZUN/MAFiD/src/model.py
pointer only (licence: NONE) · get_code("c3e96d57908b9ca9")
How it ran

The body of this sample is withheld: GitHub detected no licence in this paper's repository, ZIZUN/MAFiD when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

safe_readline Ran
ran; our contract draft was wrong, not the code
facebookresearch/mega/fairseq/binarizer.py
pointer only (licence: MIT); the stored copy get_code serves, from agi-content-generation/EKD, is pointer only (licence: NOASSERTION) · get_code("82bdf940665aeeb4")
How it ran

The body of this sample is withheld: this paper's link allows the body inline (MIT), but get_code serves the stored copy, first harvested from agi-content-generation/EKD, and GitHub could not classify the licence of that repository (NOASSERTION). The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

MegaLayer Not yet run
unverified (harvested, no recorded run)
ZIZUN/MAFiD/src/model.py
pointer only (licence: NONE) · get_code("cfbd8ca4d8912d27")
How it ran

The body of this sample is withheld: GitHub detected no licence in this paper's repository, ZIZUN/MAFiD when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. No invocation recorded.

Also present in other papers' code

Of 13 samples lifted from this paper's linked repositories, 13 carry a function identity and 0 do not. Of the 13 distinct functions with an identity, 4 are also present in other papers whose code we hold (3 with at least one paper dated earlier, 1 the same month, 4 later) and 9 are only here among the 52,977 papers whose code Syntology holds (as of 2026-09-26).

Only here means: among the 52,977 papers whose code Syntology holds (51,887 with lifted samples, 1,090 through their assemblies only), as of 2026-09-26, no other paper's lifted samples or current assembly bricks contain an identical function body after normalisation.

FunctionAlso present inEarliest-datedOthers named
safe_readline 66 other papers
44 dated earlier, 1 the same month, 17 later, 4 same year, order not determinable
1610.02424 (2016-10)
Diverse Beam Search: Decoding Diverse Solutions from Neural Sequence Models
1802.06901 (2018-02)
Deterministic Non-Autoregressive Neural Sequence Modeling by Iterative Refinement
1904.01038 (2019-04)
FAIRSEQ: A Fast, Extensible Toolkit for Sequence Modeling
and 63 more not named here
Linear 58 other papers
29 dated earlier, 28 later, 1 same year, order not determinable · 5 only as an assembly brick
1409.0473 (2014-09)
Neural Machine Translation by Jointly Learning to Align and Translate
1706.03762 (2017-06)
Attention Is All You Need
1904.01681 (2019-04)
Augmented Neural ODEs
and 55 more not named here
Embedding 29 other papers
16 dated earlier, 13 later
1904.01681 (2019-04)
Augmented Neural ODEs
1906.12183 (2019-06)
Neural ODEs as the Deep Limit of ResNets with constant weights
2002.03184 (2020-02)
Time-aware Large Kernel Convolutions
and 26 more not named here
OffsetScale
brick of this paper's assembly: helper
1 other paper
1 later
2212.14041 (2022-12)
Deciphering RNA Secondary Structure Prediction: A Probabilistic K-Rook Matching Perspective

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-23.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

The design choices in the Transformer attention mechanism, including weak inductive bias and quadratic computational complexity, have limited its application for modeling long sequences. In this paper, we introduce Mega, a simple, theoretically grounded, single-head gated attention mechanism equipped with (exponential) moving average to incorporate inductive bias of position-aware local dependencies into the position-agnostic attention mechanism. We further propose a variant of Mega that offers linear time and space complexity yet yields only minimal quality loss, by efficiently splitting the whole sequence into multiple chunks with fixed length. Extensive experiments on a wide range of sequence modeling benchmarks, including the Long Range Arena, neural machine translation, autoregressive language modeling, and image and speech classification, show that Mega achieves significant improvements over other sequence models, including variants of Transformers and recent state space models. 1

For agents

The same record, over MCP at https://syntology.ai/mcp:

get_harvested_code_for_paper("2209.10655")
get_code_for_paper("2209.10655")
have("2209.10655")

The run record, dated, one paper per request, free:

curl https://syntology.ai/api/ran/2209.10655.json

A badge for a README (the split and the date, never a ratio):

[![Syntology run record](https://syntology.ai/api/ran/2209.10655.svg)](https://syntology.ai/paper/2209.10655)

Connect an agent — have() is free.