SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2106.01540 · NeurIPS · 2021

Luna: Linear Unified Nested Attention

Xuezhe Ma, Xiang Kong, Luke Zettlemoyer, Lti, Sinong Wang, Jonathan May, Hao Ma

arXiv · PDF · Open in the Atlas

Code that ran

5 of 10 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (0 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 1 violated it and 1 has no contract verdict; 3 failures of our instrument; 5 no recorded run), measured 2026-11-22; 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/2106.01540.json · badge: /api/ran/2106.01540.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
XuezheMax/fairseq-apollo canonical (classifier label)
classifier basis: census
4 ran · 3 no recorded run
sooftware/luna-transformer community
Papers with Code archive
1 ran · 2 no recorded run
FunctionStatusWhere it lives
MultiHeadAttention Ran
ran on a synthesized input
sooftware/luna-transformer/luna_transformer/attention.py
code served (permissive licence) · get_code("9b0ec916edfd0481")
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 tuple. The image it ran in was not recorded. If your copy returns the same type 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
import torch.nn as nn
import numpy as np

# Construct the class
INIT_ARGS = {
    'dim': 8,
    'num_attention_heads': 2,
}

# Arguments for the forward method
ARGS = {
    'query': torch.randn(2, 3, 8),      # (batch=2, q_len=3, d_model=8)
    'key': torch.randn(2, 4, 8),        # (batch=2, k_len=4, d_model=8)
    'value': torch.randn(2, 4, 8),      # (batch=2, v_len=4, d_model=8)
    'mask': None,
}

# Instantiate and call
if __name__ == '__main__':
    from torch.nn import Module
    
    # Import the classes
    import torch.nn.functional as F
    from typing import Optional, Tuple
    
    class DotProductAttention(nn.Module):
        def __init__(self, dim: int, scale: bool=True) -> None:
            super(DotProductAttention, self).__init__()
            if scale:
                self.sqrt_dim = np.sqrt(dim)
            else:
                self.sqrt_dim = 1

        def forward(self, query: torch.FloatTensor, key: torch.FloatTensor, value: torch.FloatTensor, mask: Optional[torch.FloatTensor]=None) -> Tuple[torch.FloatTensor, torch.FloatTensor]:
            score = torch.matmul(query, key.transpose(2, 3)) / self.sqrt_dim
            if mask is not None:
                score.masked_fill_(mask, -10000.0)
            attn = F.softmax(score, -1)
            if len(query.size()) == 3:
                context = torch.bmm(attn, value)
            else:
                context = torch.matmul(attn, value)
            return (context, attn)

    class MultiHeadAttention(nn.Module):
        def __init__(self, dim: int=512, num_attention_heads: int=8) -> None:
            super(MultiHeadAttention, self).__init__()
            assert dim % num_attention_heads == 0, 'hidden_dim % num_attention_heads should be zero.'
            self.d_head = int(dim / num_attention_heads)
            self.num_attention_heads = num_attention_heads
            self.query_proj = nn.Linear(dim, self.d_head * num_attention_heads)
            self.key_proj = nn.Linear(dim, self.d_head * num_attention_heads)
            self.value_proj = nn.Linear(dim, self.d_head * num_attention_heads)
            self.scaled_dot_attn = DotProductAttention(dim, scale=True)

        def forward(self, query: torch.FloatTensor, key: torch.FloatTensor, value: torch.FloatTensor, mask: Optional[torch.FloatTensor]=None) -> Tuple[torch.FloatTensor, torch.FloatTensor]:
            batch_size = value.size(0)
            query = self.query_proj(query).view(batch_size, -1, self.num_attention_heads, self.d_head).transpose(1, 2)
            key = self.key_proj(key).view(batch_size, -1, self.num_attention_heads, self.d_head).transpose(1, 2)
            value = self.value_proj(value).view(batch_size, -1, self.num_attention_heads, self.d_head).transpose(1, 2)
            if mask is not None:
                mask = mask.unsqueeze(1).repeat(1, self.num_attention_heads, 1, 1)
            context, attn = self.scaled_dot_attn(query, key, value, mask)
            context = context.transpose(1, 2).reshape(batch_size, -1, self.num_attention_heads * self.d_head)
            return (context, attn)
    
    model = MultiHeadAttention(**INIT_ARGS)
    output, attn = model(**ARGS)
    print(f"Output shape: {output.shape}")
    print(f"Attention shape: {attn.shape}")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple — a tuple output has no array shape of its own; none is stated
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)
distributed_init Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
XuezheMax/fairseq-apollo/fairseq/distributed_utils.py
pointer only (licence: MIT); the stored copy get_code serves, from dashenzi721/csp, is pointer only (licence: NONE) · get_code("07969f7041022050")
How it ran

The body of this sample is withheld: MIT, as GitHub detects it on this paper's repository, XuezheMax/fairseq-apollo, is in the permissive set, but a licence decision keeps the body a pointer: the reason for that decision is not recorded with it. 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.

is_master Ran
ran, violated the contract we drafted
XuezheMax/fairseq-apollo/fairseq/distributed_utils.py
pointer only (licence: MIT); the stored copy get_code serves, from agi-content-generation/EKD, is pointer only (licence: NOASSERTION) · get_code("90b79fe15491de83")
How it ran

The body of this sample is withheld: MIT, as GitHub detects it on this paper's repository, XuezheMax/fairseq-apollo, is in the permissive set, but a licence decision keeps the body a pointer: the reason for that decision is not recorded with it. 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
XuezheMax/fairseq-apollo/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: MIT, as GitHub detects it on this paper's repository, XuezheMax/fairseq-apollo, is in the permissive set, but a licence decision keeps the body a pointer: the reason for that decision is not recorded with it. 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.

url_to_filename Ran
ran; our contract draft was wrong, not the code
XuezheMax/fairseq-apollo/fairseq/file_utils.py
pointer only (licence: MIT); the stored copy get_code serves, from agi-content-generation/EKD, is pointer only (licence: NOASSERTION) · get_code("9418b43048e4e4ec")
How it ran

The body of this sample is withheld: MIT, as GitHub detects it on this paper's repository, XuezheMax/fairseq-apollo, is in the permissive set, but a licence decision keeps the body a pointer: the reason for that decision is not recorded with it. 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.

DotProductAttention Not yet run
unverified (harvested, no recorded run)
sooftware/luna-transformer/luna_transformer/attention.py
code served (permissive licence) · get_code("f42cf74a0708c772")
How it ran

no invocation recorded.

LinearUnifiedNestedAttention Not yet run
unverified (harvested, no recorded run)
sooftware/luna-transformer/luna_transformer/attention.py
code served (permissive licence) · get_code("e29a0daaf387dc67")
How it ran

no invocation recorded.

all_reduce Not yet run
unverified (harvested, no recorded run)
XuezheMax/fairseq-apollo/fairseq/distributed_utils.py
pointer only (licence: MIT); the stored copy get_code serves, from agi-content-generation/EKD, is pointer only (licence: NOASSERTION) · get_code("199e96db5edd0edd")
How it ran

The body of this sample is withheld: MIT, as GitHub detects it on this paper's repository, XuezheMax/fairseq-apollo, is in the permissive set, but a licence decision keeps the body a pointer: the reason for that decision is not recorded with it. 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.

filename_to_url Not yet run
unverified (harvested, no recorded run)
XuezheMax/fairseq-apollo/fairseq/file_utils.py
pointer only (licence: MIT); the stored copy get_code serves, from dashenzi721/csp, is pointer only (licence: NONE) · get_code("b1a033619f614e17")
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 dashenzi721/csp, and GitHub detected no licence in that repository 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.

load_archive_file Not yet run
unverified (harvested, no recorded run)
XuezheMax/fairseq-apollo/fairseq/file_utils.py
pointer only (licence: MIT); the stored copy get_code serves, from dashenzi721/csp, is pointer only (licence: NONE) · get_code("bd3fe80662b28bc7")
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 dashenzi721/csp, and GitHub detected no licence in that repository 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 10 samples lifted from this paper's linked repositories, 10 carry a function identity and 0 do not. Of the 10 distinct functions with an identity, 7 are also present in other papers whose code we hold (7 with at least one paper dated earlier, 5 the same month, 7 later) and 3 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
23 dated earlier, 3 the same month, 38 later, 2 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
url_to_filename 48 other papers
24 dated earlier, 1 the same month, 21 later, 2 same year, order not determinable · 8 only as an assembly brick
1610.02424 (2016-10)
Diverse Beam Search: Decoding Diverse Solutions from Neural Sequence Models
1809.11096 (2018-09)
Large Scale GAN Training for High Fidelity Natural Image Synthesis
1810.04805 (2018-10)
BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding
and 45 more not named here
is_master 18 other papers
8 dated earlier, 2 the same month, 7 later, 1 same year, order not determinable
1610.02424 (2016-10)
Diverse Beam Search: Decoding Diverse Solutions from Neural Sequence Models
1902.01388 (2019-02)
Re-examination of the Role of Latent Variables in Sequence Modeling
2004.14524 (2020-04)
Simulated Multiple Reference Training Improves Low-Resource Machine Translation
and 15 more not named here
all_reduce 16 other papers
3 dated earlier, 2 the same month, 10 later, 1 same year, order not determinable
1610.02424 (2016-10)
Diverse Beam Search: Decoding Diverse Solutions from Neural Sequence Models
2021.findings-emnlp.366 (2021 (year only))
Rethinking Zero-shot Neural Machine Translation: From a Perspective of Latent Variables
2104.08771 (2021-04)
Cross-Attention is All You Need: Adapting Pretrained Transformers for Machine Translation
and 13 more not named here
filename_to_url 12 other papers
3 dated earlier, 8 later, 1 same year, order not determinable
1610.02424 (2016-10)
Diverse Beam Search: Decoding Diverse Solutions from Neural Sequence Models
2007.07691 (2020-07)
A Multilingual Parallel Corpora Collection Effort for Indian Languages
2021.findings-emnlp.366 (2021 (year only))
Rethinking Zero-shot Neural Machine Translation: From a Perspective of Latent Variables
and 9 more not named here
load_archive_file 12 other papers
2 dated earlier, 9 later, 1 same year, order not determinable
1610.02424 (2016-10)
Diverse Beam Search: Decoding Diverse Solutions from Neural Sequence Models
2021.findings-emnlp.366 (2021 (year only))
Rethinking Zero-shot Neural Machine Translation: From a Perspective of Latent Variables
2104.08771 (2021-04)
Cross-Attention is All You Need: Adapting Pretrained Transformers for Machine Translation
and 9 more not named here
distributed_init 7 other papers
2 dated earlier, 2 the same month, 3 later
1610.02424 (2016-10)
Diverse Beam Search: Decoding Diverse Solutions from Neural Sequence Models
2105.12967 (2021-05)
Selective Knowledge Distillation for Neural Machine Translation
2106.01597 (2021-06)
ZmBART: An Unsupervised Cross-lingual Transfer Framework for Language Generation
and 4 more not named here

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

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 quadratic computational and memory complexities of the Transformer's attention mechanism have limited its scalability for modeling long sequences. In this paper, we propose Luna, a linear unified nested attention mechanism that approximates softmax attention with two nested linear attention functions, yielding only linear (as opposed to quadratic) time and space complexity. As compared to a more traditional attention mechanism, Luna introduces an additional sequence with a fixed length as input and an additional corresponding output, which allows Luna to perform attention operation linearly, while also storing adequate contextual information. We perform extensive evaluations on three benchmarks of sequence modeling tasks: long-context sequence modeling, neural machine translation and masked language modeling for large-scale pretraining. Competitive or even better experimental results demonstrate both the effectiveness and efficiency of Luna compared to a variety of strong baseline methods including the full-rank attention and other efficient sparse and dense attention methods. The implementation of our model is available at https://github.com/XuezheMax/fairseq-apollo.

For agents

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

get_harvested_code_for_paper("2106.01540")
get_code_for_paper("2106.01540")
have("2106.01540")

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

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

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

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

Connect an agent — have() is free.