Skip to content
cndichengyuPublic

About

A non-Transformer multi-timescale dynamical base with active inference, calibrated planning and fair multi-seed benchmarks. Train on your own feature streams.

Topics

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

MTDB — Multi-Timescale Dynamical Base

English | 中文

tests Python PyTorch License: MIT Status

A non-Transformer training substrate for the sensorimotor–intuition–memory layer of hybrid AGI systems: sparse multi-timescale dynamics, Kuramoto phase routing, working/attractor memory, three-factor local plasticity, sleep-replay consolidation, and a compressed interface for upper-layer world models.

architecture

Status: research prototype. Not AGI, and not a drop-in Transformer replacement. MTDB implements the bottom layer of a hybrid architecture — perception compression, temporal dynamics, online adaptation, prediction-error (surprise) signals and stable long-term memory. Language, logic and planning still belong to upper-layer world models / neuro-symbolic reasoners / agents. All experiments here are small-scale synthetic probes; they are evidence, not an AGI claim.


Why this exists

Transformers are excellent sequence models, but the bottom of an embodied, continually learning system needs different properties:

  • Energy & sparsity — computation on sparse, local connections instead of dense quadratic attention.
  • Continuous time — state that evolves across multiple time constants, not only discrete token positions.
  • Online adaptation — learning during inference without a global backward pass.
  • Stable memory — surprise-gated writes and attractor retrieval instead of an ever-growing context window.
  • Grounding — a sensorimotor feature stream and phase-based binding as first-class citizens.

MTDB is a concrete, runnable attempt at that layer. It is intentionally small enough to train on a laptop CPU, so the architecture can be tested and falsified quickly.


30-second results

CPU-only, configs/standard.yaml (2,048 units, 257k parameters, ~4 min):

Probe MTDB Strongest non-Transformer baseline Notes
Next observation, horizon=5 MSE 0.0486 persistence 0.0744; linear-AR(4) 0.0532 8.7% lower MSE than linear-AR
Anomaly detection ROC-AUC 0.722 input-change 0.647 3-step smoothing: 0.748 vs 0.745 (tie)
Delayed recall, 8 classes 1.000 @ delay 48 chance 0.125 delay 96: 0.231 (with memory writes) vs 0.134 (frozen)
Online adaptation, regime B −6.9% MSE — regime A degrades only 1.7%
Forgetting stress + sleep replay A: 0.0495 → 0.1147 → 0.0481 — replay recovers almost all forgetting

prediction comparison

Full tables, curves, ablations and caveats: RESULTS_EN.md · 中文版.


v0.3: active inference, calibrated planning, honest negative results

The model can choose its own observations: before acting it simulates candidate probes and selects the most informative one by expected free energy. On an 8-class active-sensing task (noisy, partly redundant probes), one-step expected-information-gain planning improves sample efficiency at small probe budgets. Results are mean ± 95% CI over 3 seeds; the Transformer baseline is parameter-matched and is also given the same active planner and learned probe table for a fair comparison:

Probe budget MTDB active d1 MTDB fixed Transformer passive Transformer + active Bayes oracle
2 0.430 ± 0.114 0.230 0.193 0.390 0.410
3 0.633 ± 0.127 0.397 0.370 0.450 0.733
4 0.670 ± 0.131 0.730 0.607 0.623 0.727
5 0.777 ± 0.165 0.793 0.603 0.650 0.780

active inference

What this does not show: a universal Transformer victory. At larger budgets a fixed probe order catches up, and the Transformer with the same active planner closes much of the gap. We also report two negative results instead of hiding them:

  • multi-step particle planning (depth 2) did not beat one-step EIG on this task;
  • label-free online probe-reliability adaptation under drift saturated its own noise estimates and hurt accuracy.

Calibration (temperature scaling + split conformal) improves NLL/ECE and reaches ~0.90 conformal coverage, but ECE remains high (~0.5), so closing the gap to the Bayesian oracle is still open work.

Full protocol, per-seed data, negative results and limitations: ACTIVE_INFERENCE.md.

# ~70 s on CPU, 3 seeds, calibration + drift + Transformer-active baseline
python scripts/active_benchmark.py

What is inside

Layer Code What it does
A. Multi-timescale dynamics mtdb/core/dynamics.py Sparse fan-in recurrent core; τ ∈ {10, 100, 1000} ms; exponential-Euler discretisation; spectral-radius init; homeostatic bias
B. Phase synchronization mtdb/core/phase.py Kuramoto phases, synchronization-cluster features [r, mean x, fraction], cluster membership for binding/routing
C. Memory mtdb/core/memory.py Content-addressed working-memory slots; top-k attractor prototypes; surprise/novelty-gated writes
D. Local plasticity mtdb/core/plasticity.py Eligibility/STDP trace + error broadcast + reward modulation + Oja/row-norm stability, no BPTT
E. Sleep replay mtdb/core/consolidation.py Regime-balanced replay, prototype abstraction, prune/renormalise, gated readout re-fit
Interface mtdb/core/interface.py Explicit, addressable z(t) packet for upper layers
Readouts mtdb/training/readout.py Closed-form ridge and online RLS with Bayesian precision init — no backprop
Training pipeline mtdb/training/trainer.py 3-stage training + forgetting stress test + ablations + delayed recall
Custom data mtdb/tasks/array.py Convert your own [N, T, F] feature streams into trainer-ready sequences
Active inference (v0.3) mtdb/active/ One-step EIG + multi-step particle planning; temperature/conformal calibration; online noise adaptation; active-sensing benchmark with fair Transformer baseline
Transformer baseline mtdb/baselines/transformer.py Small causal Transformer used only for fair active-sensing comparisons
Synthetic worlds mtdb/tasks/synthetic.py Multimodal prediction/anomaly world and delayed-recall world

The base itself never uses backpropagation. Only the upper readout is fitted, by least squares / recursive least squares.


Interface z(t)

With the standard preset, the 283-dimensional packet is:

Slice Dim Meaning
h 128 compressed multi-timescale latent state
phase 36 12 synchronization clusters × [coherence, mean state, fraction]
wm 48 working-memory readout
attractor 48 long-term attractor retrieval
input / delta 10 + 10 current observation and its first difference
trace (optional) F decaying sensory evidence trace, enabled by include_sensory_trace=True
aux 3 (surprise, sync, confidence)

Consume it in any upper layer:

out = system.step(sensor_features)      # sensor_features: [F] tensor
z = out.packet.z                         # [283]
surprise = out.packet.surprise           # scalar, for attention / exploration / writes

Quick start

git clone https://github.com/cndichengyu/mtdb.git
cd mtdb

# Python 3.10+; a venv with CPU PyTorch is enough
python -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"

# 1-minute synthetic probe (768 units)
python scripts/train.py --config configs/debug.yaml

# standard probe (2,048 units, CPU ~4 min)
python scripts/train.py --config configs/standard.yaml --run-name demo_standard

# tests
pytest tests -q

Artifacts are written to artifacts/<run_name>/: results.json, checkpoint.pt, checkpoint_stage1.pt, resolved config and five figures.


Train on your own data

The base only needs a feature stream. Prepare an .npz file with:

# data/my_stream.npz
#   train: [N, T, F]   training stream
#   eval:  [N, T, F]   held-out stream
# optional:
#   train_b / eval_b:                 second regime for the online experiment
#   eval_anomaly: [N, T, F]           stream with injected anomalies
#   eval_anomaly_mask: [N, T] bool    anomaly labels

Then:

python scripts/train.py --config configs/standard.yaml --data data/my_stream.npz

Features are z-scored using training-split statistics only; targets are derived as x[t + horizon]. The input dimension is inferred automatically. For sleep replay, make sequences at least consolidation.window_len ticks long (96 in debug, 128 in standard), or lower that config value. You can also call the API directly:

from mtdb.config import ExperimentConfig
from mtdb.tasks.array import make_streams_from_arrays
from mtdb.training.trainer import MTDBTrainer

streams, meta = make_streams_from_arrays(
    train=my_train_array,          # [N, T, F]
    eval=my_eval_array,            # [N, T, F]
    horizon=5,
    normalize=True,
)
cfg = ExperimentConfig.from_yaml("configs/standard.yaml")
trainer = MTDBTrainer(cfg, streams=streams)
results = trainer.run()

For a complete runnable example see examples/custom_stream.py.


How training works

  1. Unsupervised predictive-coding pretraining — drive the base with sensor streams; update only self-prediction / homeostasis locally; fit the upper readout with ridge least squares.
  2. Online task learning — initialize RLS from the stage-1 posterior, adapt the readout tick-by-tick, and optionally update recurrent weights with three-factor local plasticity; surprise-gated memory writes happen during inference.
  3. Sleep replay consolidation — replay old + new experience, abstract attractor prototypes, prune/renormalise synapses, and re-fit the readout only when replay error improves.

Two built-in diagnostics make the claims checkable: an aggressive-forgetting stress test (forget=0.999 followed by sleep replay) and component ablations (full / no_phase / no_memory / single_tau / fast_only).


Presets and scaling

Preset Units Fan-in Interface Params Runtime (CPU)
configs/debug.yaml 768 16 207 95k ~1 min
configs/standard.yaml 2048 24 283 257k ~4 min
configs/mvp.yaml 16384 32 435 ~2M not run in CI

The core step is O(N·K) with sparse gathers. The current code is a discrete-tick approximation of an event-driven substrate; hardware mapping (neuromorphic / in-memory computing) is a design target, not a measured result.


Results gallery

anomaly recall
surprise response & anomaly ROC delayed-recall accuracy vs delay
online training
online adaptation & sleep recovery stage-1 predictive-coding curve

Honest limitations

  • Synthetic 10-D world only; not validated on real vision/audio/robotics yet.
  • Phase and memory ablations are small on short-horizon prediction; the clearest evidence for slow timescales is the delayed-recall curve and the fast_only ablation.
  • Working memory only shows a clear advantage at long delays (96 steps: 0.231 vs 0.134).
  • Sleep consolidation currently lives mostly in the readout; recurrent synapses are pruned/renormalised but not replayed with STDP.
  • No language/reasoning/planning; no hardware power/latency measurements.
  • Anomaly detection should use checkpoint_stage1.pt; online adaptation changes the surprise normalisation statistics (documented in the results).
  • The active benchmark is a synthetic 8-class task; the advantage comes mostly from active evidence acquisition, and a Transformer given the same planner closes much of the gap. No universal superiority claim.
  • Multi-step particle planning and label-free online probe adaptation are implemented but were negative on this benchmark; see ACTIVE_INFERENCE.md.
  • Real event-camera/audio/robot validation is not done; the active benchmark is synthetic.

See ARCHITECTURE_EN.md §9 for the full risk list.


Roadmap

  1. Done in v0.2/v0.3: active-inference loop, multi-step planning, calibration, fair Transformer baseline, multi-seed CIs. Open: label-free drift adaptation, uncertainty calibration to Bayes-oracle level, real active-perception streams.
  2. Event-driven / spiking kernels instead of dense ticks.
  3. Close the loop: phase clusters select modules/memory slots/gains.
  4. Trajectory-level STDP replay (not only readout re-fitting).
  5. Hierarchical MTDB connected to a world model / SSM / neuro-symbolic reasoner.
  6. Real multimodal front-ends: event cameras, audio, touch/proprioception.
  7. 10⁴–10⁵ units with measured power, latency and throughput.

Repository layout

mtdb/
├── core/          # dynamics, phase, memory, plasticity, consolidation, interface
├── training/      # ridge/RLS readouts + 3-stage trainer
├── tasks/         # synthetic worlds + custom-array adapter
├── active/        # v0.3 active inference: environment, planning, calibration
├── eval/          # metrics and figures
├── baselines/     # persistence / mean / linear-AR / small Transformer
configs/           # debug / standard / mvp presets
scripts/           # train.py / eval.py / active_benchmark.py
examples/          # custom stream example
tests/             # unit + integration tests (CI)
assets/            # architecture and result figures
results/           # committed JSON results (base demos + active v0.2/v0.3)

Testing and CI

pytest tests -q
ruff check mtdb scripts tests --select F401,F841,F821,E9

CI runs the test suite, a 1-epoch smoke train, and a quick active-inference benchmark on every push and pull request.


Citation

@misc{mtdb2026,
  title        = {MTDB: Multi-Timescale Dynamical Base},
  author       = {cndichengyu},
  year         = {2026},
  howpublished = {\url{https://github.com/cndichengyu/mtdb}},
  note         = {A non-Transformer training substrate for hybrid AGI prototypes}
}

Citation metadata is also in CITATION.cff. MIT licensed.


Contributing

This is an early research prototype; reproducible experiments, negative results and clearly scoped extensions are all welcome. See CONTRIBUTING.md and open an issue with your config/results.json if you find something interesting.

If this direction is useful to you, a ⭐ helps other researchers find the project.

About

A non-Transformer multi-timescale dynamical base with active inference, calibrated planning and fair multi-seed benchmarks. Train on your own feature streams.

Topics

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages