SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2105.14039 · NeurIPS · 2021

Towards mental time travel: a hierarchical memory for reinforcement learning agents

Deepmind London, Andrea Banino, Felix Hill, Andrew Lampinen, Stephanie Chan

arXiv · PDF · Open in the Atlas

Code that ran

3 of 6 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (2 of them constructed an object rather than computing a result; 1 honoured the contract we drafted, 0 violated it and 2 have no contract verdict; 0 failures of our instrument; 3 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/2105.14039.json · badge: /api/ran/2105.14039.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/HTM-pytorch community
Papers with Code archive
2 ran · 0 no recorded run
deepmind/deepmind-research alias (classifier label)
classifier basis: classifier_2025
1 ran · 3 no recorded run
FunctionStatusWhere it lives
HTMAttention Ran
ran on a synthesized input · constructed an object; no result was computed
lucidrains/HTM-pytorch/htm_pytorch/htm_pytorch.py
code served (permissive licence) · get_code("4edc3f6c9182d6ba")
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, HTMAttention: 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
from math import ceil
from einops import rearrange, repeat

torch.manual_seed(0)

# Define the helper function and modules used by HTMAttention
def exists(val):
    return val is not None

def pad_to_multiple(t, multiple, dim=-2, value=0.0):
    seq_len = t.shape[dim]
    pad_to_len = ceil(seq_len / multiple) * multiple
    remainder = pad_to_len - seq_len
    if remainder == 0:
        return t
    zeroes = (0, 0) * (-dim - 1)
    import torch.nn.functional as F
    padded_t = F.pad(t, (*zeroes, remainder, 0), value=value)
    return padded_t

class SinusoidalPosition(nn.Module):
    def __init__(self, dim, min_timescale=2.0, max_timescale=10000.0):
        super().__init__()
        freqs = torch.arange(0, dim, min_timescale)
        inv_freqs = max_timescale ** (-freqs / dim)
        self.register_buffer('inv_freqs', inv_freqs)

    def forward(self, x):
        seq_len = x.shape[-2]
        seq = torch.arange(seq_len - 1, -1, -1.0)
        sinusoidal_inp = rearrange(seq, 'n -> n ()') * rearrange(self.inv_freqs, 'd -> () d')
        pos_emb = torch.cat((sinusoidal_inp.sin(), sinusoidal_inp.cos()), dim=-1)
        return pos_emb

class Attention(nn.Module):
    def __init__(self, dim, dim_head=64, heads=8):
        super().__init__()
        self.scale = dim_head ** (-0.5)
        self.heads = heads
        inner_dim = dim_head * heads
        self.to_q = nn.Linear(dim, inner_dim, bias=False)
        self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)
        self.to_out = nn.Linear(inner_dim, dim)

    def forward(self, x, mems, mask=None):
        h = self.heads
        q, k, v = (self.to_q(x), *self.to_kv(mems).chunk(2, dim=-1))
        q, k, v = tuple(rearrange(t, 'b ... (h d) -> (b h) ... d', h=h) for t in (q, k, v))
        q = q * self.scale
        import torch
        sim = torch.einsum('b m i d, b m i j d -> b m i j', q, k)
        if exists(mask):
            mask = repeat(mask, 'b ... -> (b h) ...', h=h)
            mask_value = -torch.finfo(sim.dtype).max
            sim = sim.masked_fill(~mask, mask_value)
        attn = sim.softmax(dim=-1)
        out = torch.einsum('... i j, ... i j d -> ... i d', attn, v)
        out = rearrange(out, '(b h) ... d -> b ... (h d)', h=h)
        return self.to_out(out)

# Now create small valid arguments for HTMAttention
batch_size = 2
query_len = 5
mem_len = 16
dim = 4
heads = 2
dim_head = 2
topk_mems = 2
mem_chunk_size = 4

# queries: (batch, query_len, dim)
queries = torch.randn(batch_size, query_len, dim)

# memories: (batch, mem_len, dim)
memories = torch.randn(batch_size, mem_len, dim)

# mask: (batch, mem_len) - boolean mask for memories
mask = torch.ones(batch_size, mem_len, dtype=torch.bool)

# chunk_attn_mask: (batch, query_len, num_chunks) where num_chunks = ceil(mem_len / mem_chunk_size)
num_chunks = ceil(mem_len / mem_chunk_size)
chunk_attn_mask = torch.ones(batch_size, query_len, num_chunks, dtype=torch.bool)

ARGS = {
    'dim': dim,
    'heads': heads,
    'topk_mems': topk_mems,
    'mem_chunk_size': mem_chunk_size,
    'dim_head': dim_head,
    'add_pos_enc': True,
    'eps': 1e-5
}
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 HTMAttention — 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 HTMAttention 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
SinusoidalPosition Ran
ran on a synthesized input · constructed an object; no result was computed
lucidrains/HTM-pytorch/htm_pytorch/htm_pytorch.py
code served (permissive licence) · get_code("d5ba387dec7cb4ba")
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, SinusoidalPosition: 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)

# Construct arguments for SinusoidalPosition.__init__
# Parameters: dim, min_timescale=2.0, max_timescale=10000.0

ARGS = {
    'dim': 8,
    'min_timescale': 2.0,
    'max_timescale': 10000.0
}
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 SinusoidalPosition — 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 SinusoidalPosition 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
sinusoid_position_encoding Ran
ran, honoured the contract we drafted
deepmind/deepmind-research/hierarchical_transformer_memory/hierarchical_attention/htm_attention.py
code served (permissive licence) · get_code("1e8ece086c64bdec")
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 ndarray, ndim 2, dtype family float, shape (8, 16) 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 jax.numpy as jnp
import numpy as np

# Construct arguments for sinusoid_position_encoding
sequence_length = 8
hidden_size = 16
min_timescale = 2.0
max_timescale = 10000.0

ARGS = {
    "sequence_length": sequence_length,
    "hidden_size": hidden_size,
    "min_timescale": min_timescale,
    "max_timescale": max_timescale,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
jax, numpy — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type ndarray, ndim 2, dtype family float, shape (8, 16) — shape (8, 16) 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
HierarchicalMemory Not yet run
unverified (harvested, no recorded run)
deepmind/deepmind-research/hierarchical_transformer_memory/hierarchical_attention/htm_attention.py
code served (permissive licence) · get_code("2edf304a64ef7730")
How it ran

no invocation recorded.

HierarchicalMemoryAttention Not yet run
unverified (harvested, no recorded run)
deepmind/deepmind-research/hierarchical_transformer_memory/hierarchical_attention/htm_attention.py
code served (permissive licence) · get_code("47ba4f0ef6df2621")
How it ran

no invocation recorded.

hk_vmap Not yet run
unverified (harvested, no recorded run)
deepmind/deepmind-research/hierarchical_transformer_memory/hierarchical_attention/htm_attention.py
code served (permissive licence) · get_code("f91e2499666b6b69")
How it ran

no invocation recorded.

Also present in other papers' code

Of 6 samples lifted from this paper's linked repositories, 6 carry a function identity and 0 do not. Of the 6 distinct functions with an identity, 0 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 0 later) and 6 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.

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

Reinforcement learning agents often forget details of the past, especially after delays or distractor tasks. Agents with common memory architectures struggle to recall and integrate across multiple timesteps of a past event, or even to recall the details of a single timestep that is followed by distractor tasks. To address these limitations, we propose a Hierarchical Chunk Attention Memory (HCAM), which helps agents to remember the past in detail. HCAM stores memories by dividing the past into chunks, and recalls by first performing high-level attention over coarse summaries of the chunks, and then performing detailed attention within only the most relevant chunks. An agent with HCAM can therefore "mentally time-travel"remember past events in detail without attending to all intervening events. We show that agents with HCAM substantially outperform agents with other memory architectures at tasks requiring long-term recall, retention, or reasoning over memory. These include recalling where an object is hidden in a 3D environment, rapidly learning to navigate efficiently in a new neighborhood, and rapidly learning and retaining new object names. Agents with HCAM can extrapolate to task sequences an order of magnitude longer than they were trained on, and can even generalize zero-shot from a meta-learning setting to maintaining knowledge across episodes. HCAM improves agent sample efficiency, generalization, and generality (by solving tasks that previously required specialized architectures). Our work is a step towards agents that can learn, interact, and adapt in complex and temporallyextended environments. [44]-specifically, a gated version of TransformerXL [9]. However, using TransformerXL memories on challenging memory tasks still requires auxiliary self-supervision [19], and might even benefit from new unsupervised learning mechanisms [3]. Furthermore, even in supervised tasks Transformers can struggle to recall details from long sequences [54]. In the next section, we propose a new hierarchical attention memory architecture for RL agents that can help overcome these challenges. 2 Hierarchical Chunk Attention Memory . . .

For agents

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

get_harvested_code_for_paper("2105.14039")
get_code_for_paper("2105.14039")
have("2105.14039")

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

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

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

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

Connect an agent — have() is free.