SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2112.04426 · 2021

Improving language models by retrieving from trillions of tokens

Michela Paganini, Erich Elsen, Karen Simonyan, Oriol Vinyals, Sebastian Borgeaud, Simon Osindero, Arthur Mensch, Katie Millican, Roman Ring, Eliza Rutherford, Jacob Menick, Laurent Sifre, and 17 more

arXiv · PDF · Open in the Atlas

Code that ran

16 of 23 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (5 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 3 violated it and 11 have no contract verdict; 2 failures of our instrument; 7 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/2112.04426.json · badge: /api/ran/2112.04426.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
lucidrains/RETRO-pytorch community
Papers with Code archive
8 ran · 5 no recorded run
labmlai/annotated_deep_learning_paper_implementations community
Papers with Code archive
5 ran · 2 no recorded run
copy not recorded community
not in the paper's declared repositories
3 ran · 0 no recorded run
FunctionStatusWhere it lives
Attention Ran
ran on a synthesized input · constructed an object; no result was computed
lucidrains/RETRO-pytorch/retro_pytorch/retro_pytorch.py
code served (permissive licence) · get_code("03b81e2f9a4d2d4c")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned an instance of its own class, Attention: the run constructed the object and did not call it, so no result was computed. 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

torch.manual_seed(0)

ARGS = {
    'dim': 64,
    'context_dim': 64,
    'dim_head': 16,
    'heads': 4,
    'causal': False,
    'dropout': 0.1,
    'null_kv': False,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
einops, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Attention — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a Attention output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not 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: none by the harness; any seed is in the setup block
ChunkedCrossAttention Ran
ran on a synthesized input
labmlai/annotated_deep_learning_paper_implementations/labml_nn/transformers/retro/model.py
code served (permissive licence) · get_code("f393e5da1f357aea")
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, 10, 8) 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 math
import torch
from torch import nn

class ChunkedCrossAttention(nn.Module):
    """
    ## Chunked Cross-Attention Layer $	ext{C\\small{CA}}$

    This is similar to the cross-attention layer defined above.

    This is used in the decoder to pay attention to the retrieved neighbor chunks.

    *We do not use any explicit positional embeddings here.
    We assume that the model can represent positional information in the embeddings implicitly.*
    """

    def __init__(self, d_model: int, n_heads: int, d_k: int, chunk_len: int):
        """
        * `d_model` is the number of features in transformer embeddings
        * `n_heads` is the number of attention heads
        * `d_k` is the number of features per head
        * `chunk_len` is the length of a chunk
        """
        super().__init__()
        self.chunk_len = chunk_len
        self.n_heads = n_heads
        self.d_k = d_k
        self.scale = 1 / math.sqrt(self.d_k)
        self.query = nn.Linear(d_model, n_heads * d_k)
        self.key = nn.Linear(d_model, n_heads * d_k)
        self.value = nn.Linear(d_model, n_heads * d_k)
        self.norm = nn.LayerNorm(d_model)
        self.softmax = nn.Softmax(dim=-1)
        self.output = nn.Linear(n_heads * d_k, d_model)

    def forward(self, h: torch.Tensor, e: torch.Tensor):
        """
        `h` are the input embeddings of shape `[batch_size, seq_len, d_model]`
        `e` are the retrieved nearest neighbors of shape `[batch_size, chunks, neighbors, neighbor_len, d_model]`
        """
        batch_size, chunks, neighbors, neighbor_len, d_model = e.shape
        if chunks == 0:
            return h
        h_res = h
        h = h[:, self.chunk_len - 1:]
        h = self.norm(h)
        if h.shape[1] < chunks * self.chunk_len:
            h = torch.cat((h, h.new_zeros(batch_size, chunks * self.chunk_len - h.shape[1], d_model)), dim=1)
        h = h.reshape(batch_size, chunks, self.chunk_len, d_model)
        q = self.query(h).view(*h.shape[:-1], self.n_heads, self.d_k)
        k = self.key(e).view(*e.shape[:-1], self.n_heads, self.d_k)
        v = self.value(e).view(*e.shape[:-1], self.n_heads, self.d_k)
        attn = torch.einsum('bcihd,bcnjhd->bchinj', q, k)
        attn = attn * self.scale
        attn = self.softmax(attn.view(*attn.shape[:-2], -1)).view(attn.shape)
        h = torch.einsum('bchinj,bcnjhd->bcihd', attn, v)
        h = h.reshape(batch_size, chunks * self.chunk_len, -1)
        h = self.output(h)
        h = torch.cat((h.new_zeros(batch_size, self.chunk_len - 1, d_model), h), dim=1)
        return h[:, :h_res.shape[1]] + h_res


INIT_ARGS = {
    'd_model': 8,
    'n_heads': 2,
    'd_k': 4,
    'chunk_len': 3,
}

ARGS = {
    'h': torch.randn(2, 10, 8),
    'e': torch.randn(2, 3, 4, 5, 8),
}

if __name__ == '__main__':
    model = ChunkedCrossAttention(**INIT_ARGS)
    output = model(**ARGS)
    print(f"Output shape: {output.shape}")
    print(f"Expected shape: {ARGS['h'].shape}")
    assert output.shape == ARGS['h'].shape, f"Shape mismatch: {output.shape} vs {ARGS['h'].shape}"
    print("Test passed!")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
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, 10, 8) — shape (2, 10, 8) 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)
CrossAttention Ran
ran on a synthesized input
labmlai/annotated_deep_learning_paper_implementations/labml_nn/transformers/retro/model.py
code served (permissive licence) · get_code("c3e56d6f2af858c1")
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 5, dtype family float, shape (2, 3, 5, 6, 8) 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 math
import torch
from torch import nn

class CrossAttention(nn.Module):
    """
    ## Cross-Attention Layer $	ext{C\\small{A}}$

    This is similar to the self-attention layer defined above, except that
    it gets keys and values from a different set of embeddings than the queries.

    This is used in the encoder to encode the retrieved chunks based on the
    input chunks.

    *We do not use any explicit positional embeddings here.
    We assume that the model can represent positional information in the embeddings implicitly.*
    """

    def __init__(self, d_model: int, n_heads: int, d_k: int):
        """
        * `d_model` is the number of features in transformer embeddings
        * `n_heads` is the number of attention heads
        * `d_k` is the number of features per head
        """
        super().__init__()
        self.n_heads = n_heads
        self.d_k = d_k
        self.scale = 1 / math.sqrt(self.d_k)
        self.query = nn.Linear(d_model, n_heads * d_k)
        self.key = nn.Linear(d_model, n_heads * d_k)
        self.value = nn.Linear(d_model, n_heads * d_k)
        self.norm = nn.LayerNorm(d_model)
        self.softmax = nn.Softmax(dim=-1)
        self.output = nn.Linear(n_heads * d_k, d_model)

    def forward(self, e: torch.Tensor, h: torch.Tensor):
        """
        * `e` are the retrieved nearest neighbor chunk embeddings with shape
          `[batch_size, chunks, neighbors, neighbor_len, d_model]`
        * `h` are the input chunks from which the nearest neighbors were retrieved with shape
          `[batch_size, chunks, chunk_len, d_model]`. This is already normalized.
        """
        e_res = e
        e = self.norm(e)
        q = self.query(e).view(*e.shape[:-1], self.n_heads, self.d_k)
        k = self.key(h).view(*h.shape[:-1], self.n_heads, self.d_k)
        v = self.value(h).view(*h.shape[:-1], self.n_heads, self.d_k)
        attn = torch.einsum('bcnihd,bcjhd->bcnhij', q, k)
        attn = attn * self.scale
        attn = self.softmax(attn)
        e = torch.einsum('bcnhij,bcjhd->bcnihd', attn, v)
        e = e.reshape(*e.shape[:-2], -1)
        e = self.output(e)
        return e + e_res


INIT_ARGS = {
    'd_model': 8,
    'n_heads': 2,
    'd_k': 4,
}

ARGS = {
    'e': torch.randn(2, 3, 5, 6, 8),
    'h': torch.randn(2, 3, 7, 8),
}

if __name__ == '__main__':
    model = CrossAttention(**INIT_ARGS)
    output = model(**ARGS)
    print(f"Output shape: {output.shape}")
    print(f"Expected shape: {ARGS['e'].shape}")
    assert output.shape == ARGS['e'].shape, f"Shape mismatch: {output.shape} vs {ARGS['e'].shape}"
    print("Test passed!")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 5, dtype family float, shape (2, 3, 5, 6, 8) — shape (2, 3, 5, 6, 8) 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)
FeedForward Ran
ran on a synthesized input · constructed an object; no result was computed
lucidrains/RETRO-pytorch/retro_pytorch/retro_pytorch.py
code served (permissive licence) · get_code("38be50d72d5874d6")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned an instance of its own class, FeedForward: the run constructed the object and did not call it, so no result was computed. 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
from torch import nn

torch.manual_seed(0)

ARGS = {
    "dim": 8,
    "mult": 4,
    "dropout": 0.1,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type FeedForward — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a FeedForward output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not 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: none by the harness; any seed is in the setup block
FeedForward Ran
ran on a synthesized input
labmlai/annotated_deep_learning_paper_implementations/labml_nn/transformers/retro/model.py
code served (permissive licence) · get_code("1fae1fc6f059aacd")
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

class FeedForward(nn.Module):
    """
    ### Position-wise Feed Forward Layer $	ext{F\\small{FW}}$

    This consists of two linear layers and an activation in the middle.
    """

    def __init__(self, d_model: int, d_ff: int):
        """
        * `d_model` is the number of features in transformer embeddings
        * `d_ff` is the number features in the hidden layer
        """
        super().__init__()
        self.lin1 = nn.Linear(d_model, d_ff)
        self.lin2 = nn.Linear(d_ff, d_model)
        self.act = nn.ReLU()
        self.norm = nn.LayerNorm(d_model)

    def forward(self, h: torch.Tensor):
        """
        `h` are the embeddings of shape `[batch_size, seq_len, d_model]`
        """
        h_res = h
        h = self.norm(h)
        h = self.lin1(h)
        h = self.act(h)
        h = self.lin2(h)
        return h + h_res


INIT_ARGS = {
    'd_model': 4,
    'd_ff': 8,
}

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

if __name__ == '__main__':
    model = FeedForward(**INIT_ARGS)
    output = model(**ARGS)
    print(f"Output shape: {output.shape}")
    print(f"Expected shape: {ARGS['h'].shape}")
    assert output.shape == ARGS['h'].shape, "Output shape mismatch"
    print("Success!")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
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)
PostNorm Ran
ran on a synthesized input · constructed an object; no result was computed
lucidrains/RETRO-pytorch/retro_pytorch/retro_pytorch.py
code served (permissive licence) · get_code("562d2542a1eaacef")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned an instance of its own class, PostNorm: the run constructed the object and did not call it, so no result was computed. 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
from torch import nn, einsum

torch.manual_seed(0)

class RMSNorm(nn.Module):
    def __init__(self, dim, *, eps=1e-08, gated=False):
        super().__init__()
        self.eps = eps
        self.scale = dim ** (-0.5)
        self.gamma = nn.Parameter(torch.ones(dim))
        self.weight = nn.Parameter(torch.ones(dim)) if gated else None

    def forward(self, x):
        norm = x.norm(keepdim=True, dim=-1) * self.scale
        out = x / norm.clamp(min=self.eps) * self.gamma
        if not self.weight is not None:
            return out
        return out * (x * self.weight).sigmoid()

def exists(val):
    return val is not None

class PostNorm(nn.Module):
    def __init__(self, dim, fn, scale_residual=1, norm_klass=RMSNorm):
        super().__init__()
        self.fn = fn
        self.scale_residual = scale_residual
        self.norm = norm_klass(dim)

    def forward(self, x, *args, **kwargs):
        residual = x * self.scale_residual
        out = self.fn(x, *args, **kwargs) + residual
        return self.norm(out)

# Create a simple function that takes x and returns a tensor
class SimpleFunction(nn.Module):
    def forward(self, x, *args, **kwargs):
        return torch.ones_like(x)

# Build the arguments for PostNorm
dim = 4
fn = SimpleFunction()
scale_residual = 1
norm_klass = RMSNorm

ARGS = {
    'dim': dim,
    'fn': fn,
    'scale_residual': scale_residual,
    'norm_klass': norm_klass
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type PostNorm — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a PostNorm output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not 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: none by the harness; any seed is in the setup block
PreNorm Ran
ran on a synthesized input · constructed an object; no result was computed
lucidrains/RETRO-pytorch/retro_pytorch/retro_pytorch.py
code served (permissive licence) · get_code("f44be7c955b39fa2")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned an instance of its own class, PreNorm: the run constructed the object and did not call it, so no result was computed. 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
from torch import nn

torch.manual_seed(0)

class RMSNorm(nn.Module):
    def __init__(self, dim, *, eps=1e-08, gated=False):
        super().__init__()
        self.eps = eps
        self.scale = dim ** (-0.5)
        self.gamma = nn.Parameter(torch.ones(dim))
        self.weight = nn.Parameter(torch.ones(dim)) if gated else None

    def forward(self, x):
        norm = x.norm(keepdim=True, dim=-1) * self.scale
        out = x / norm.clamp(min=self.eps) * self.gamma
        if not exists(self.weight):
            return out
        return out * (x * self.weight).sigmoid()

def exists(val):
    return val is not None

class PreNorm(nn.Module):
    def __init__(self, dim, fn, norm_klass=RMSNorm):
        super().__init__()
        self.fn = fn
        self.norm = norm_klass(dim)

    def forward(self, x, *args, **kwargs):
        return self.fn(self.norm(x), *args, **kwargs) + x

# Create a simple mock function that accepts normalized input and returns output
class SimpleFn(nn.Module):
    def __init__(self, dim):
        super().__init__()
        self.linear = nn.Linear(dim, dim)
    
    def forward(self, x, *args, **kwargs):
        return self.linear(x)

# Setup arguments
dim = 4
fn = SimpleFn(dim)
norm_klass = RMSNorm

ARGS = {
    'dim': dim,
    'fn': fn,
    'norm_klass': norm_klass
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type PreNorm — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a PreNorm output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not 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: none by the harness; any seed is in the setup block
RMSNorm Ran
ran on a synthesized input · constructed an object; no result was computed
lucidrains/RETRO-pytorch/retro_pytorch/retro_pytorch.py
code served (permissive licence) · get_code("a4ae5f96225b96f3")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned an instance of its own class, RMSNorm: the run constructed the object and did not call it, so no result was computed. 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
from torch import nn

torch.manual_seed(0)

ARGS = {
    'dim': 4,
    'eps': 1e-08,
    'gated': False
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type RMSNorm — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a RMSNorm output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not 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: none by the harness; any seed is in the setup block
RotaryEmbedding Ran
ran on a synthesized input
lucidrains/RETRO-pytorch/retro_pytorch/retro_pytorch.py
code served (permissive licence) · get_code("9fbc41d552de00c6")
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 4, dtype family float, shape (1, 1, 4, 8) 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, einsum
from einops import rearrange, repeat

class RotaryEmbedding(nn.Module):

    def __init__(self, dim):
        super().__init__()
        inv_freq = 1.0 / 10000 ** (torch.arange(0, dim, 2).float() / dim)
        self.register_buffer('inv_freq', inv_freq)

    def forward(self, max_seq_len, *, device, offset=0):
        seq = torch.arange(max_seq_len, device=device) + offset
        freqs = einsum('i , j -> i j', seq.type_as(self.inv_freq), self.inv_freq)
        emb = torch.cat((freqs, freqs), dim=-1)
        return rearrange(emb, 'n d -> 1 1 n d')


INIT_ARGS = {
    'dim': 8
}

ARGS = {
    'max_seq_len': 4,
    'device': torch.device('cpu'),
    'offset': 0
}

if __name__ == '__main__':
    model = RotaryEmbedding(**INIT_ARGS)
    output = model(**ARGS)
    print(f"Output shape: {output.shape}")
    print(f"Output:\n{output}")
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 4, dtype family float, shape (1, 1, 4, 8) — shape (1, 1, 4, 8) 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)
RotaryPositionalEmbeddings Ran
ran on a synthesized input
labmlai/annotated_deep_learning_paper_implementations/labml_nn/transformers/retro/model.py
code served (permissive licence) · get_code("6d63acdd4f116570")
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 4, dtype family float, shape (2, 3, 2, 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

class RotaryPositionalEmbeddings(nn.Module):
    """
    ## [RoPE embeddings](../rope/index.html)

    *We use rotary position embeddings in self-attention layers.
    We assume the positional information gets embedded in embeddings
    and therefore not use them in causal attention.
    [Non-causal self-attention needs explicit positional information
     because it cannot infer it](https://arxiv.org/abs/3999902edc8511eba3db37f65e372566).*
    """

    def __init__(self, d: int, base: int=10000):
        """
        * `d` is the number of features $d$
        * `base` is the constant used for calculating $\\Theta$
        """
        super().__init__()
        self.theta = nn.Parameter(1.0 / base ** (torch.arange(0, d, 2).float() / d), requires_grad=False)

    def forward(self, x: torch.Tensor):
        """
        * `x` is the Tensor at the head of a key or a query with shape `[ batch_size, seq_len, n_heads, d]`
        """
        batch_size, seq_len, n_heads, d = x.shape
        d_2 = d // 2
        seq_idx = torch.arange(seq_len, device=x.device).type_as(self.theta)
        idx_theta = torch.einsum('n,d->nd', seq_idx, self.theta)
        idx_theta2 = torch.cat([idx_theta, idx_theta], dim=1)
        neg_half_x = torch.cat([-x[:, :, :, d_2:], x[:, :, :, :d_2]], dim=-1)
        rx = x * idx_theta2.cos()[None, :, None, :] + neg_half_x * idx_theta2.sin()[None, :, None, :]
        return rx


INIT_ARGS = {
    'd': 4,
    'base': 10000
}

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

if __name__ == '__main__':
    model = RotaryPositionalEmbeddings(**INIT_ARGS)
    output = model(**ARGS)
    print(f"Input shape: {ARGS['x'].shape}")
    print(f"Output shape: {output.shape}")
    print(f"Output:\n{output}")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 4, dtype family float, shape (2, 3, 2, 4) — shape (2, 3, 2, 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)
SelfAttention Ran
ran on a synthesized input
labmlai/annotated_deep_learning_paper_implementations/labml_nn/transformers/retro/model.py
code served (permissive licence) · get_code("4c4fa4155f57fc48")
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, 8) 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
import torch.nn as nn
import math

INIT_ARGS = {
    'd_model': 8,
    'n_heads': 2,
    'd_k': 4,
    'is_causal': False,
}

ARGS = {
    'h': torch.randn(2, 3, 8),
}
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
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, 8) — shape (2, 3, 8) 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)
apply_rotary_pos_emb Ran
ran; our contract draft was wrong, not the code
lucidrains/RETRO-pytorch/retro_pytorch/retro_pytorch.py
code served (permissive licence) · get_code("a6120b0228dbf889")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) 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 einops import rearrange, repeat

torch.manual_seed(0)

# Analyze the function:
# - apply_rotary_pos_emb(t, freqs)
# - t is indexed with [..., :rot_dim] and [..., rot_dim:], so it's a tensor with last dim >= rot_dim
# - freqs is indexed with .shape[-1], and has .cos() and .sin() called on it, so it's a tensor
# - seq_len comes from t.shape[-2], rot_dim from freqs.shape[-1]
# - The function expects t to have at least 2 dimensions (seq_len at -2, feature at -1)

# Create t: shape (batch, seq_len, feature_dim)
# Let's use batch=2, seq_len=3, feature_dim=4
t = torch.randn(2, 3, 4)

# Create freqs: shape (seq_len, rot_dim) or compatible
# rot_dim should be less than feature_dim
# Let's make freqs shape (3, 4) to match seq_len and allow rot_dim=4
freqs = torch.randn(3, 4)

ARGS = {
    't': t,
    'freqs': freqs,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
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: none by the harness; any seed is in the setup block
cast_tuple Ran
ran, violated the contract we drafted
this paper's copy was not recorded; identical code first harvested from dashstander/block-recurrent-transformer
pointer only · get_code("75e2de7f7799802d")
How it ran

The body of this sample is withheld: this paper's copy of the code was not recorded (its link names no repository or source path), so no licence was read for 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.

default Ran
ran, violated the contract we drafted
this paper's copy was not recorded; identical code first harvested from ThomasMrY/VCT
pointer only; the stored copy get_code serves, from ThomasMrY/VCT, is pointer only (licence: NONE) · get_code("60fff7c3c400d7ff")
How it ran

The body of this sample is withheld: this paper's copy of the code was not recorded (its link names no repository or source path), so no licence was read for 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.

exists Ran
ran, violated the contract we drafted
this paper's copy was not recorded; identical code first harvested from ThomasMrY/VCT
pointer only; the stored copy get_code serves, from ThomasMrY/VCT, is pointer only (licence: NONE) · get_code("aa5486a3650902d8")
How it ran

The body of this sample is withheld: this paper's copy of the code was not recorded (its link names no repository or source path), so no licence was read for 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.

rotate_half Ran
ran; our contract draft was wrong, not the code
lucidrains/RETRO-pytorch/retro_pytorch/retro_pytorch.py
code served (permissive licence) · get_code("fdd93453f92f9167")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned Tensor, ndim 2, dtype family float, shape (2, 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 einops import rearrange, repeat

torch.manual_seed(0)

# The function rotate_half takes a single parameter 'x' which is a tensor
# It uses rearrange to reshape x into shape '... (j d) -> ... j d' with j=2
# This means the last dimension must be even (divisible by 2)
# Then it unbinds along dim=-2 and concatenates
# Let's create a small tensor with an even last dimension

x = torch.randn(2, 4)  # batch=2, last_dim=4 (even, so can be split into j=2, d=2)

ARGS = {
    'x': x
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
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 2, dtype family float, shape (2, 4) — shape (2, 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: none by the harness; any seed is in the setup block
ChunkedCrossAttention Not yet run
unverified (harvested, no recorded run)
lucidrains/RETRO-pytorch/retro_pytorch/retro_pytorch.py
code served (permissive licence) · get_code("a18eb1addcd13eca")
How it ran

no invocation recorded.

Decoder Not yet run
unverified (harvested, no recorded run)
lucidrains/RETRO-pytorch/retro_pytorch/retro_pytorch.py
code served (permissive licence) · get_code("df5ec3eb8c24bd01")
How it ran

no invocation recorded.

Encoder Not yet run
unverified (harvested, no recorded run)
lucidrains/RETRO-pytorch/retro_pytorch/retro_pytorch.py
code served (permissive licence) · get_code("dfd283b4f5317daf")
How it ran

no invocation recorded.

NearestNeighborEncoder Not yet run
unverified (harvested, no recorded run)
labmlai/annotated_deep_learning_paper_implementations/labml_nn/transformers/retro/model.py
code served (permissive licence) · get_code("ed827370476041d7")
How it ran

no invocation recorded.

RETRO Not yet run
unverified (harvested, no recorded run)
lucidrains/RETRO-pytorch/retro_pytorch/retro_pytorch.py
code served (permissive licence) · get_code("c136963c983ee0fb")
How it ran

no invocation recorded.

RetroModel Not yet run
unverified (harvested, no recorded run)
labmlai/annotated_deep_learning_paper_implementations/labml_nn/transformers/retro/model.py
code served (permissive licence) · get_code("5156ed7e3c0f7fef")
How it ran

no invocation recorded.

deepnorm_init Not yet run
unverified (harvested, no recorded run)
lucidrains/RETRO-pytorch/retro_pytorch/retro_pytorch.py
code served (permissive licence) · get_code("2f92b91f3350e0c9")
How it ran

no invocation recorded.

Also present in other papers' code

Of 23 samples lifted from this paper's linked repositories, 23 carry a function identity and 0 do not. Of the 23 distinct functions with an identity, 5 are also present in other papers whose code we hold (2 with at least one paper dated earlier, 2 the same month, 5 later) and 18 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
exists
brick of this paper's assembly: helper
486 other papers
72 dated earlier, 2 the same month, 410 later, 2 undated · 78 only as an assembly brick
1603.08155 (2016-03)
Perceptual Losses for Real-Time Style Transfer and Super-Resolution
1611.07004 (2016-11)
Image-to-Image Translation with Conditional Adversarial Networks
1804.04637 (2018-04)
EMBER: An Open Dataset for Training Static PE Malware Machine Learning Models
and 483 more not named here
default
brick of this paper's assembly: helper
163 other papers
34 dated earlier, 1 the same month, 127 later, 1 undated · 27 only as an assembly brick
1603.08155 (2016-03)
Perceptual Losses for Real-Time Style Transfer and Super-Resolution
1810.00825 (2018-10)
Set Transformer: A Framework for Attention-based Permutation-Invariant Neural Networks
1907.01470 (2019-07)
Augmenting Self-attention with Persistent Memory
and 160 more not named here
rotate_half
brick of this paper's assembly: helper
13 other papers
13 later · 2 only as an assembly brick
2202.07765 (2022-02)
General-purpose, long-context autoregressive modeling with Perceiver AR
2203.07852 (2022-03)
Block-Recurrent Transformers
2204.02311 (2022-04)
PaLM: Scaling Language Modeling with Pathways
and 10 more not named here
apply_rotary_pos_emb
brick of this paper's assembly: helper
1 other paper
1 later
2203.07852 (2022-03)
Block-Recurrent Transformers
cast_tuple
brick of this paper's assembly: helper
1 other paper
1 later
2203.07852 (2022-03)
Block-Recurrent Transformers

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

We enhance auto-regressive language models by conditioning on document chunks retrieved from a large corpus, based on local similarity with preceding tokens. With a 2 trillion token database, our Retrieval-Enhanced Transformer (R ) obtains comparable performance to GPT-3 and Jurassic-1 on the Pile, despite using 25× fewer parameters. After fine-tuning, R performance translates to downstream knowledge-intensive tasks such as question answering. R combines a frozen B retriever, a differentiable encoder and a chunked cross-attention mechanism to predict tokens based on an order of magnitude more data than what is typically consumed during training. We typically train R from scratch, yet can also rapidly R fit pre-trained transformers with retrieval and still achieve good performance. Our work opens up new avenues for improving language models through explicit memory at unprecedented scale.

For agents

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

get_harvested_code_for_paper("2112.04426")
get_code_for_paper("2112.04426")
have("2112.04426")

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

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

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

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

Connect an agent — have() is free.