SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2110.07732 · ICLR · 2022

The Neural Data Router: Adaptive Control Flow in Transformers Improves Systematic Generalization

J Ürgen Schmidhuber, Kazuki Irie, Róbert Csordás

arXiv · PDF · Open in the Atlas

Code that ran

7 of 11 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, 1 violated it and 5 have no contract verdict; 1 failure of our instrument; 4 no recorded run), measured 2026-11-23; 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/2110.07732.json · badge: /api/ran/2110.07732.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
RobertCsordas/ndr canonical (classifier label)
classifier basis: classifier_2025
1 ran · 0 no recorded run
robertcsordas/ndr marked official in Papers with Code
Papers with Code archive
6 ran · 4 no recorded run
FunctionStatusWhere it lives
AttentionMask Ran
ran on a synthesized input · constructed an object; no result was computed
robertcsordas/ndr/layers/transformer/ndr.py
code served (permissive licence) · get_code("28c21d66cc3361af")
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, AttentionMask: 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 dataclasses import dataclass
from typing import Optional

torch.manual_seed(0)

@dataclass
class AttentionMask:
    src_length_mask: Optional[torch.Tensor]
    position_mask: Optional[torch.Tensor]

# Create small tensors for the attention masks
src_length_mask = torch.randint(0, 2, (2, 4), dtype=torch.bool)
position_mask = torch.randint(0, 2, (2, 3), dtype=torch.bool)

ARGS = {
    "src_length_mask": src_length_mask,
    "position_mask": position_mask,
}
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 AttentionMask — 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 AttentionMask 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
LayerWithVisualization Ran
ran on a synthesized input · constructed an object; no result was computed
robertcsordas/ndr/layers/transformer/ndr.py
code served (permissive licence) · get_code("e0c7a1fa7f8f1165")
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, LayerWithVisualization: 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)

class LayerWithVisualization(torch.nn.Module):

    def __init__(self):
        super().__init__()
        self.visualization_enabled = False

    def prepare(self):
        pass

    def plot(self, options: dict) -> dict:
        raise NotImplementedError()


ARGS = {}
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 LayerWithVisualization — 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 LayerWithVisualization 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
MultiHeadAttentionBase Ran
ran on a synthesized input · constructed an object; no result was computed
robertcsordas/ndr/layers/transformer/ndr.py
code served (permissive licence) · get_code("51c7e36152503851")
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, MultiHeadAttentionBase: 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
import math

torch.manual_seed(0)

ARGS = {
    "state_size": 8,
    "n_heads": 2,
    "dropout": 0.1,
    "projection_size": None,
}
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 MultiHeadAttentionBase — 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 MultiHeadAttentionBase 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
RegularizedLayer Ran
ran on a synthesized input · constructed an object; no result was computed
robertcsordas/ndr/layers/transformer/ndr.py
code served (permissive licence) · get_code("c9270f7c12e670a5")
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, RegularizedLayer: 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 typing import Dict, Any, Callable

torch.manual_seed(0)

class RegularizedLayer:

    def __init__(self) -> None:
        super().__init__()
        self.reg_accumulated = 0
        self.regularization_present = False

    @property
    def reg_enabled(self) -> bool:
        return self.training and self.regularization_present

    def add_reg(self, l: Callable[[], torch.Tensor]):
        if self.reg_enabled:
            self.reg_accumulated = self.reg_accumulated + l()

    def get_reg_loss(self) -> torch.Tensor:
        rl = self.reg_accumulated
        self.reg_accumulated = 0
        return rl


# The __init__ method has no parameters (besides self)
ARGS = {}
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 RegularizedLayer — 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 RegularizedLayer 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
RelativeAttentionBase Ran
ran on a synthesized input · constructed an object; no result was computed
robertcsordas/ndr/layers/transformer/ndr.py
code served (permissive licence) · get_code("5cc9456646f6915c")
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, RelativeAttentionBase: 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
import math

torch.manual_seed(0)

# Define the minimal classes needed
class AttentionMask:
    def __init__(self, src_length_mask=None, position_mask=None):
        self.src_length_mask = src_length_mask
        self.position_mask = position_mask

class LayerWithVisualization(nn.Module):
    def __init__(self):
        super().__init__()
        self.visualization_enabled = False
    
    def prepare(self):
        pass
    
    def plot(self, options):
        raise NotImplementedError()

class MultiHeadAttentionBase(LayerWithVisualization):
    def __init__(self, state_size, n_heads, dropout=0.1, projection_size=None):
        assert state_size % n_heads == 0
        super().__init__()
        self.attention_to_visualize = []
        self.state_size = state_size
        self.projection_size = projection_size or state_size // n_heads
        self.n_heads = n_heads
        self.scale = 1.0 / math.sqrt(self.projection_size)
        self.dropout = nn.Dropout(dropout)
    
    @staticmethod
    def apply_logit_masks(logits, mask, val=float('-inf')):
        if mask.position_mask is not None:
            logits = logits.masked_fill(mask.position_mask, val)
        if mask.src_length_mask is not None:
            b, i = mask.src_length_mask.shape
            pad_dims = logits.ndim - 2
            logits = logits.masked_fill(mask.src_length_mask.view([b] + [1] * pad_dims + [i]), val)
        return logits
    
    def _masked_softmax(self, logits, mask):
        if mask is None or (mask.src_length_mask is None and mask.position_mask is None):
            return torch.nn.functional.softmax(logits, -1)
        bb, n_time_dest, n_time_src = logits.shape
        logits = logits.view(bb // self.n_heads, self.n_heads, n_time_dest, n_time_src)
        logits = self.apply_logit_masks(logits, mask)
        logits = torch.nn.functional.softmax(logits, -1)
        return logits.view(bb, n_time_dest, n_time_src)
    
    def _attention_read(self, mask, scores, v):
        s_reshape = scores.view(-1, self.n_heads, *scores.shape[1:])
        if self.visualization_enabled:
            self.attention_to_visualize.append(s_reshape[0])
        return (torch.bmm(scores, v), s_reshape)
    
    def transform_data(self, input, proj, n_projs):
        n_batch, n_steps, _ = input.shape
        transformed = proj(input).view(n_batch, n_steps, self.n_heads, n_projs, -1).permute(0, 2, 1, 3, 4).contiguous().view(n_batch * self.n_heads, n_steps, n_projs, -1)
        return transformed.unbind(dim=2)
    
    def plot(self, options):
        return {}

class RelativeAttentionBase(MultiHeadAttentionBase):
    def __init__(self, state_size, n_heads, dropout, projection_size=None):
        super().__init__(state_size, n_heads, dropout=dropout, projection_size=projection_size)
        self.scale = nn.Parameter(torch.tensor([self.scale]))
        self.s_bias = nn.Parameter(torch.tensor([0.0]))
        self.vis_pos_vs_content = []

# Setup arguments
state_size = 8
n_heads = 2
dropout = 0.1
projection_size = None

ARGS = {
    'state_size': state_size,
    'n_heads': n_heads,
    'dropout': dropout,
    'projection_size': projection_size,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
matplotlib, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type RelativeAttentionBase — 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 RelativeAttentionBase 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
UniversalTransformerRandomLayerEncoderWithLayer Ran
ran; our contract draft was wrong, not the code
RobertCsordas/ndr/layers/transformer/ndr.py
code served (permissive licence) · get_code("06cf617792cacde6")
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 function. 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

torch.manual_seed(0)

# Define a minimal layer that can be called with (data, *args, **kwargs)
class MinimalLayer(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(4, 4)
    
    def forward(self, data, *args, **kwargs):
        return self.linear(data)

# Create the layer class to pass
layer_class = MinimalLayer

# Define arguments for UniversalTransformerRandomLayerEncoderWithLayer
ARGS = {
    "layer": layer_class
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type function — a function output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a function 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
shift Ran
ran, violated the contract we drafted
robertcsordas/ndr/layers/transformer/ndr.py
code served (permissive licence) · get_code("fd07c4fcaa87fe04")
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, 4, 2) 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.functional as F

torch.manual_seed(0)

# Create a small 2D position matrix
# The function expects a tensor with at least 2 dimensions
# Shape: (batch=2, height=4, width=3) - distinct sizes for clarity
posmat = torch.randn(2, 4, 3)

ARGS = {
    "posmat": posmat
}
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 Tensor, ndim 3, dtype family float, shape (2, 4, 2) — shape (2, 4, 2) 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
AttentionMergeMixin Not yet run
unverified (harvested, no recorded run)
robertcsordas/ndr/layers/transformer/ndr.py
code served (permissive licence) · get_code("df234de93fadef4e")
How it ran

no invocation recorded.

FixedRelativeMultiheadAttention Not yet run
unverified (harvested, no recorded run)
robertcsordas/ndr/layers/transformer/ndr.py
code served (permissive licence) · get_code("fc0009775b8227c6")
How it ran

no invocation recorded.

FixedRelativeMultiheadAttentionBase Not yet run
unverified (harvested, no recorded run)
robertcsordas/ndr/layers/transformer/ndr.py
code served (permissive licence) · get_code("1a1e99543d24b2e2")
How it ran

no invocation recorded.

NDRResidual Not yet run
unverified (harvested, no recorded run)
robertcsordas/ndr/layers/transformer/ndr.py
code served (permissive licence) · get_code("ac16130612e4864a")
How it ran

no invocation recorded.

Also present in other papers' code

Of 11 samples lifted from this paper's linked repositories, 11 carry a function identity and 0 do not. Of the 11 distinct functions with an identity, 3 are also present in other papers whose code we hold (1 with at least one paper dated earlier, 0 the same month, 2 later) and 8 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
AttentionMask
brick of this paper's assembly: helper
1 other paper
1 later
2310.19089 (2023-10)
Pushdown Layers: Encoding Recursive Structure in Transformer Language Models
UniversalTransformerRandomLayerEncoderWithLayer 1 other paper
1 dated earlier
1812.11760 (2018-12)
Multilingual Constituency Parsing with Self-Attention and Pre-Training
shift
brick of this paper's assembly: helper
1 other paper
1 later
2312.07987 (2023-12)
SwitchHead: Accelerating Transformers with Mixture-of-Experts Attention

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

Despite progress across a broad range of applications, Transformers have limited success in systematic generalization. The situation is especially frustrating in the case of algorithmic tasks, where they often fail to find intuitive solutions that route relevant information to the right node/operation at the right time in the grid represented by Transformer columns. To facilitate the learning of useful control flow, we propose two modifications to the Transformer architecture, copy gate and geometric attention. Our novel Neural Data Router (NDR) achieves 100% length generalization accuracy on the classic compositional table lookup task, as well as near-perfect accuracy on the simple arithmetic task and a new variant of ListOps testing for generalization across computational depths. NDR's attention and gating patterns tend to be interpretable as an intuitive form of neural routing. Our code is public. 1

For agents

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

get_harvested_code_for_paper("2110.07732")
get_code_for_paper("2110.07732")
have("2110.07732")

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

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

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

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

Connect an agent — have() is free.