Metadata-Version: 2.4
Name: dabsn
Version: 1.1.0
Summary: DABSN recurrent modeling framework with native CPU and CUDA runtimes
Author: Nicholas Rosdahl
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/BleedingXiko/dabsn
Project-URL: Documentation, https://github.com/BleedingXiko/dabsn#readme
Project-URL: Paper, https://github.com/BleedingXiko/dabsn/blob/main/paper1/main.pdf
Project-URL: Source, https://github.com/BleedingXiko/dabsn
Project-URL: Issues, https://github.com/BleedingXiko/dabsn/issues
Keywords: deep-learning,neural-network,recurrent-neural-network,sequence-modeling,pytorch,triton
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch>=2.6
Requires-Dist: numpy>=1.24
Requires-Dist: ninja>=1.11
Requires-Dist: safetensors>=0.4.5
Provides-Extra: test
Requires-Dist: pytest>=8; extra == "test"
Requires-Dist: pyflakes>=3; extra == "test"
Provides-Extra: dev
Requires-Dist: ruff>=0.9; extra == "dev"
Requires-Dist: mypy>=1.13; extra == "dev"
Requires-Dist: build>=1.2; extra == "dev"
Provides-Extra: security
Requires-Dist: pip-audit>=2.7; extra == "security"
Requires-Dist: detect-secrets>=1.5; extra == "security"
Requires-Dist: cyclonedx-bom>=5; extra == "security"
Provides-Extra: cuda-turing
Requires-Dist: torch==2.6.0; platform_system == "Linux" and extra == "cuda-turing"
Requires-Dist: triton==3.2.0; platform_system == "Linux" and extra == "cuda-turing"
Provides-Extra: paper
Requires-Dist: matplotlib>=3.8; extra == "paper"
Dynamic: license-file

# 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](#papers).

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:

```bash
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

```python
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

```python
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

```python
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](examples/capacity_train.py) and
[minimal training without Capacity](examples/minimal_train.py).

## 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:

```text
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:

```python
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](ARCHITECTURE.md) 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](docs/capacity.md)
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](docs/online-temporal-credit-and-prepared-memory.md)
for executable examples and state ownership.

## Native execution and speed

```python
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](ARCHITECTURE.md#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

```python
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](ARCHITECTURE.md#runtime-contract),
[distributed execution](ARCHITECTURE.md#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](https://doi.org/10.5281/zenodo.24268811) · [PDF](paper3/main.pdf) · [Source and results](paper3/) ·
[Reproduction](paper3/reproduce/README.md)

### 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](https://doi.org/10.5281/zenodo.24268687) · [PDF](paper2/main.pdf) · [Source, proofs, and results](paper2/) ·
[Reproduction](paper2/README.md)

### 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](paper1/main.pdf) · [Source, results, and reproduction](paper1/)

## Citation

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

```bibtex
@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](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](LICENSE).
