Metadata-Version: 2.4
Name: gatedlearn
Version: 0.1.0
Summary: Error-gated continual learning: surprise-gated updates and compartmentalised memory, derived from the Drosophila connectome study (error-gating is necessary for memory consolidation)
Author: Junrong Du
License: MIT
Keywords: continual-learning,catastrophic-forgetting,neuromodulation,error-gating,lifelong-learning
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24
Requires-Dist: torch>=2.0
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Dynamic: license-file

# gatedlearn

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

**Error-gated continual learning.** Surprise-gated updates and
compartmentalised memory, derived from the Drosophila whole-connectome study:

- **Error gating is necessary for consolidation.** With a dopaminergic error
  signal gating plasticity, learned behaviour consolidated in 94% of cases;
  passive re-scaling without it preserved only ~20% (T59e).
- **Compartmentalisation beats shared outputs.** Per-behaviour output
  compartments preserved 100% of old behaviours under new learning vs 88%
  for a shared head (T100).

## Install

```bash
pip install -e .        # requires torch
pip install -e ".[dev]" # + pytest
```

## Usage

```python
import torch
from gatedlearn import GatedLearner, backward_transfer

learner = GatedLearner(in_dim=32, out_dim=2, hidden=128, lr=1e-3)

for task_id, (x, y) in task_stream:            # a stream of tasks
    learner.learn_task(task_id, x, y, epochs=15)

learner.predict(x, task_id="T0")
backward_transfer(learner, task_data)          # per-task retention
learner.report()                               # gate statistics
```

Set `baseline="ungated"` for the matched control (same architecture, gate
always open).

## How the gate works

`ErrorGatedOptimizer` wraps any torch optimiser. A batch passes the gate
only if it carries a real learning signal:

1. **Consolidation criterion (primary)**: total gradient norm vs an
   adaptive floor (`max(grad_floor, grad_ratio x running-mean grad norm)`).
   A plateau whose gradients have fallen below 10% of the recent typical
   level is *consolidated* -- further updates are drift, and are refused
   (gradients zeroed).
2. **Surprise criterion**: online z-score of the loss,
   `|loss - fast_baseline| / noise_scale >= z_threshold` (default 4).
   A genuine level shift (new task) reopens the gate.
3. **Fallback statistics-only path** (no `grad_norm`): fast/slow baseline
   drift. Tuning-sensitive; prefer passing the gradient norm.

Refused steps have their gradients zeroed: below the noise floor there is
nothing to learn (the T59e lesson).

## Benchmark (synthetic, this repo)

Five conflicting tasks (same inputs, different labelling rules) + 60 epochs
of consolidation pressure on the last task:

| condition | old-task retention after pressure |
|---|---|
| ungated control | 0.884 |
| gated (`grad_ratio=0.5, grad_floor=0.05`) | 0.892 |

**Honest read-out**: on this small synthetic stream the gate is
neutral-to-slightly-positive; the compartment heads already protect most of
the retention, and the tasks are too easy to produce large interference.
The deterministic correctness of the gating *mechanism* is covered by unit
tests (consolidated plateaus close the gate; level shifts reopen it); the
T59e biological experiment is the evidence that the mechanism matters at
scale.

## Tests

```bash
python -m pytest tests/ -q   # 6 passed
```

## License

MIT
