Skip to main content

DABSN

One recurrent layer with content-addressed memory, for PyTorch.

DABSN is a single recurrent layer: a nonlinear recurrent core, plus a memory the layer chooses what to admit into and reads back by content. Use it as a complete sequence model, or add its memory to an existing transformer as one branch.

A transformer with one DABSN memory branch and no positional encoding has no architectural context cap. Trained at 256 tokens, the paper-3 models retain 96.9% MQAR accuracy at 64× the training length, 100% at 8× the stored pairs, and 96–100% passkey digit accuracy at 1,048,576 tokens (4096×) across three seeds. Results and limits.

The layer trains with ordinary backpropagation through time (BPTT) or with online temporal credit, which carries learning state beyond the retained computation graph. Optional Capacity adds a bank of learned recurrent features, dense or sparse. Native CPU and CUDA kernels cover forward and backward. Models are ordinary torch.nn.Module objects; applications own their training loops, data, optimizers, and schedules.

Install

Requires Python 3.10+ and PyTorch 2.6+. Install the PyTorch build appropriate for your machine, then:

pip install dabsn

For Turing GPUs such as T4 and GTX 1660 Ti, pip install 'dabsn[cuda-turing]' pins PyTorch 2.6.0 and Triton 3.2.0 on Linux. Use FP16 there; the batched core runs in place of the persistent one. The pins and sm_75 kernel compilation were tested; physical T4 execution was not.

Quick start

Memory for an existing transformer

import torch
from dabsn import DABSNHostMemory

h = torch.randn(2, 256, 128)  # [batch, positions, host width]
norm = torch.nn.LayerNorm(128)
memory = DABSNHostMemory(dim=128)
h = h + memory(norm(h))

DABSNHostMemory is the DABSN read alone, behind two projections and four scalar tags derived from the host's latents; it has no DABSN core. It returns only the memory branch, so the host chooses residual, normalization, and placement. Query and write projections start as identity maps, and the admission window starts at 1.5. The default geometry is causal seq; field and hybrid are also supported.

Admission depends on content. At fixed width, reading a sequence costs O(T * N) for T positions and N admitted entries, and querying an existing bank costs O(N). The bank can grow with history; admitting a constant fraction of positions makes sequence read work quadratic.

A DABSN language model

import torch
from dabsn import DABSNSequenceLM
from dabsn.runtime import build_training_optimizer

model = DABSNSequenceLM(vocab=256, hidden_dim=64, state_dim=48, read_geometry="seq")
optimizer = build_training_optimizer(model, lr=1e-3, weight_decay=0.0)

ids = torch.randint(0, 256, (2, 129))
logits = model.forward_sequence(ids[:, :-1])
loss = torch.nn.functional.cross_entropy(logits.flatten(0, 1), ids[:, 1:].flatten())
loss.backward()
optimizer.step()

The same constructor takes temporal_credit="online", capacity=..., tie_embeddings=True, and a downstream mlp_ratio or moe. The pretrain CLI command trains this model on a memory-mapped token corpus with exact resume.

A block with sparse Capacity

import torch
from dabsn import CapacityConfig, build_dabsn
from dabsn.kernels import enable
from dabsn.runtime import build_training_optimizer

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
enable(device.type, required=True)

model = build_dabsn(
    input_dim=8,
    out_dim=3,
    hidden_dim=32,
    state_dim=24,
    read_geometry="seq",
    output_adapter="token",
    capacity=CapacityConfig(mode="sparse", size=256, active_units=16),
).to(device)

inputs = torch.randn(2, 16, 8, device=device)
targets = torch.randint(0, 3, (2, 16), device=device)
optimizer = build_training_optimizer(model, lr=1e-3, weight_decay=0.0)

optimizer.zero_grad(set_to_none=True)
logits = model.forward_sequence(inputs)
loss = torch.nn.functional.cross_entropy(logits.flatten(0, 1), targets.flatten())
loss.backward()
optimizer.step()

This builds one DABSN layer with 256 Capacity rows, 16 active per input, on continuous input features. The combined optimizer prepares sparse row gradients during step(). The dimensions and optimizer settings illustrate the API. See Capacity training and minimal training without Capacity.

Inside the layer

The layer has distinct input, output, and recurrent-state widths. The core maintains baseline, energy, and saturation state. Read combines admitted content memory, successor induction, permanent associative memory, and a recurrent long-memory channel. Optional Capacity contributes alongside Read before the state-to-output-width projection:

input ──┬── Core ──┬── expressed state ────────────────┐
        │          └── Read (admitted + long memory) ──┼── sum → projection
        └── Capacity (dense or sparse) ────────────────┘
Geometry Read eligibility Intended structure
seq Causal prefix Language, events, control streams
field Whole object Images, boards, sets
hybrid Learned sequence/field mixture Structured streams

DABSNModel handles continuous features, DABSNSequenceLM adds token embeddings and a language-model head, and DABSNTaskModel uses registered application-owned adapters. residual=True adds a layer residual. In BPTT, mlp_ratio adds a dense MLP on the layer output, or moe adds sparse experts:

from dabsn import DABSNModel

model = DABSNModel(
    input_dim=128, out_dim=16, hidden_dim=128, state_dim=96,
    read_geometry="seq", output_adapter="token",
    moe={"experts": 8, "top_k": 2, "inner_dim": 512,
         "router": "switch", "balance_coefficient": 0.01},
)

The architecture contract describes every construction option.

Capacity

Capacity expands the layer's learned recurrent features without changing the core width or the number of DABSN scans. Its keys, biases, retention parameters, and output values are learned; each feature has a recurrent value, and selected features update from the current input and contribute to the layer output.

Mode Configuration Execution
Dense CapacityConfig(mode="dense", size=4096) Updates and reads every row
Sparse CapacityConfig(mode="sparse", size=4096, active_units=64) Updates and reads exactly 64 geometrically selected rows per input

Sparse rows are chosen by fixed geometric addressing, not a learned router. Parameter and state storage grow with size; sparse compute uses only the selected rows. Capacity is optional, works with all three geometries, and supports BPTT and online credit on the reference, C++ CPU, and Triton CUDA paths. Use build_training_optimizer, which gives sparse rows SparseAdam and everything else AdamW. See the Capacity API and state contract for addressing, custom AMP and clipping loops, and checkpoint contents.

Training: BPTT or online credit

temporal_credit="bptt" is the default. temporal_credit="online" carries architecture-specific eligibility across bounded autograd chunks, so learning state does not grow with elapsed history; the separate admitted read bank still can. Online training works with or without Capacity. Downstream MLPs and MoEs require BPTT. This structured rule is not generic exact RTRL or full-stack BPTT gradient equivalence. Carrying state between batches requires stable stream identities and explicit lane resets.

Prepared inference memory computes historical admission once, then supports queries and extensions over exact admitted-event pages, with no fixed top-k, eviction, or lossy compression. This .dmem path currently supports incremental queries with seq Read.

See online training, exact resume, and prepared memory for executable examples and state ownership.

Native execution and speed

from dabsn.kernels import enable, status

enable("cuda", required=True)   # Triton/CUDA
# enable("cpu", required=True)  # C++/OpenMP
# enable("reference")          # PyTorch reference
print(status())

Backend activation is process-wide, and required native execution raises rather than silently switching runtime families. Where several exact CUDA routes exist for a shape, the faster one is measured on first use and cached per GPU; nothing needs to be configured. Kernel coverage, precision, and the override variables are in the runtime contract.

Component measurements on an NVIDIA A40, forward + backward without an optimizer update, under BF16 autocast (online core operands remain FP32):

Component Shape Tokens/s Reference at the same shape
Core, BPTT H=768, B=16, T=2048 800,577 cuDNN LSTM: 560,831
Core, online credit H=768, B=16, T=2048 576,030 —
Core, BPTT H=256, B=64, T=512 4,134,689 cuDNN LSTM: 1,668,203
Capacity, BPTT B=8, T=2048, C=32768, A=1024, D=S=2048 919,418 MLP: 2,811,733
Capacity, online credit Same 476,457 —

Here H is core width, B batch, and T sequence length. Capacity has C rows, A active rows, input/output width D, and state width S; the reference MLP is 2048 → 1024 → 2048. The LSTM performs roughly twice the recurrent work, so its comparison is per layer, not per FLOP.

At B=1, T=16,384, H=128 in BF16 on the same A40, admitted-read forward takes about 4 ms against about 1 ms for PyTorch fused causal attention. The read performs three reads with two value tensors. On an AMD EPYC 7713 allocation with 8 vCPUs, PyTorch 2.8, and FP32, a full sequence-geometry layer reaches 11,698 tokens/s for inference at H=256, B=1, T=1024, and 9,763 tokens/s for forward + backward at H=256, B=8, T=128.

These are component and layer measurements, not full-model training rates. The recurrent core advances sequentially; batch supplies device parallelism, while admission determines the separate read cost.

Checkpoints and distributed execution

from dabsn import load_dabsn, save_dabsn

save_dabsn(model, "model.safetensors")
restored = load_dabsn("model.safetensors", map_location="cpu")

Atomic SafeTensors checkpoints preserve the layer configuration and weights. Registered external experts require explicit trust when loading. Optimizer and carried training state are stored separately.

Distributed support includes DDP, FSDP wrapped at the DABSN block, tensor parallelism over recurrent state units, and expert parallelism. Pipeline and context parallelism do not ship. setup_distributed runs one tiny all-reduce across the workers before training. If they cannot reach each other, it raises DistributedPreflightError (within 120 seconds by default) instead of hanging. On cloud PCIe GPUs the fix it names is usually NCCL_P2P_DISABLE=1; leave peer-to-peer on for NVLink nodes.

The library also supplies sharded training checkpoints, export, gradient verification, and distributed gradient clipping. The train, pretrain, and finetune CLI commands are convenience examples. See the runtime and persistence contracts, distributed execution, and dabsn --help.

Papers

3. Attention is My Memory

Positional Encoding-free Length Invariance in Transformers

One memory branch gives a transformer content-addressed retrieval without positional encoding. Main synthetic models use width 128 and four layers; the branch adds 82,839 parameters, 2.9% of the base model.

MQAR evaluation NoPE + memory, front RoPE + YaRN, fine-tuned
Distance: 16,384 tokens, 64× training length 96.9 ± 2.8% 94.9 ± 5.7%
Load: 512 pairs, 8× largest training load 100.0 ± 0.0% 37.9 ± 10.9%

Results are means ± standard deviations over three seeds. Memory models train at 256 tokens; the YaRN baseline receives additional fine-tuning at 1024. Extreme passkey evaluation reaches 100%, 96%, and 100% digit accuracy at 1,048,576 tokens over ten prompts per seed; plain NoPE scores 10% on its evaluated seed.

The 459-run protocol includes learning-rate selection, larger models, and enwik8. At the training length, position-free language modelling reaches 1.444 bits per character (RoPE: 1.450; ALiBi: 1.426); loss rises beyond it. Retrieval generalization does not establish general length invariance on copying or natural text, or constant compute and memory cost.

Paper · PDF · Source and results · Reproduction

2. Experience as a Persistent Object

Online Temporal Credit in DABSN

The paper specifies E, proves partition composition at fixed parameters and an exact identity for omitted influence, and constructs histories separating E from the full terminal state–parameter Jacobian in both directions. Experiments test delayed learning, causal edits with forward computation held fixed, objectives selected after experience, and direct parameter action.

Online credit and full BPTT both reach 100% temporal-order accuracy at lengths 128, 512, and 2048; at 4096 their means are 84.8% and 85.9%. A core driven by E for credit, direction, and pace, without core optimizer state, matches the AdamW comparisons on copy, MQAR, and key–value recall. Online credit loses BPTT's exact A5/60 length generalization, and 64-step truncated BPTT remains much stronger on the uninterrupted-stream tasks.

Paper · PDF · Source, proofs, and results · Reproduction

1. One Layer, Both Gaps

A Persistent-Modulation Recurrence that Generalizes Copy and Tracks Non-Solvable Group State

One architecture, trained separately per task, tests copying and non-solvable group-state tracking with causal ablations of its state and read pathways.

Task Train length Evaluation length Result
Copy, vocabulary 64 64 3,200 (50×) 0.961 ± 0.035, three seeds
A5/60 word problem 256 16,384 (64×) 1.000, two seeds

Paper · Source, results, and reproduction

Citation

Cite the papers relevant to the architecture, online credit, or host memory:

@misc{rosdahl2026attentionmemory,
  title  = {Attention is My Memory: Positional Encoding-free Length Invariance
            in Transformers},
  author = {Rosdahl, Nicholas},
  year   = {2026},
  doi    = {10.5281/zenodo.24268811},
  url    = {https://doi.org/10.5281/zenodo.24268811}
}

@misc{rosdahl2026experience,
  title  = {Experience as a Persistent Object: Online Temporal Credit in DABSN},
  author = {Rosdahl, Nicholas},
  year   = {2026},
  doi    = {10.5281/zenodo.24268687},
  url    = {https://doi.org/10.5281/zenodo.24268687}
}

@misc{rosdahl2026onelayer,
  title  = {One Layer, Both Gaps: A Persistent-Modulation Recurrence that
            Generalizes Copy and Tracks Non-Solvable Group State},
  author = {Rosdahl, Nicholas},
  year   = {2026},
  doi    = {10.5281/zenodo.21391204},
  url    = {https://github.com/BleedingXiko/dabsn}
}

CITATION.cff contains software metadata, paper 1's preferred citation, and references to papers 2 and 3. DABSN is released under the Apache License 2.0.

Metadata

Release files for dabsn 1.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for dabsn 1.1.0
File Size Uploaded Provenance Actions
dabsn-1.1.0.tar.gz 930.5 kB Without provenance Details for dabsn-1.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for dabsn 1.1.0
File Interpreter ABI Platform Actions
dabsn-1.1.0-py3-none-any.whl Python 3 none any Details for dabsn-1.1.0-py3-none-any.whl

Total release size: 1.4 MB

Release files / dabsn-1.1.0.tar.gz

Download URL dabsn-1.1.0.tar.gz
Size 930.5 kB
Tags Source
SHA-256 checksum
How to use checksums
b5ca5c524d274543ce4d1fd0c22fc7896f918ee70fb100af9e97f521ee86aa23
BLAKE2b-256 checksum
How to use checksums
ea9cec2e2a6b6aa73186a50a63f563de59d64b5550dae843451e2ff914d3ccfb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.15

Release files / dabsn-1.1.0-py3-none-any.whl

Download URL dabsn-1.1.0-py3-none-any.whl
Size 437.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
956183dd5e175d66ed8de93fb8c2ccbc65b06f4b43eb4baaaf6782e5732ac548
BLAKE2b-256 checksum
How to use checksums
997a4b552544b0d2d18075cb1db2eec1dbccc1b4469426567cc58515ae1b161b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.15

Security for dabsn 1.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page