Commit ·
a53bd89
1
Parent(s): e194c40
Sync Sonapse 0.3.0 Frontier Pack with Hugging Face LFS assets
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .github/dependabot.yml +12 -0
- .github/workflows/regression.yml +73 -8
- .pre-commit-config.yaml +20 -0
- CITATION.cff +25 -0
- MANIFEST.in +2 -0
- README.md +18 -1
- docs/ENGINEERING.md +226 -0
- docs/compatibility/manifest-pre-frontier.json +1140 -0
- docs/frontier/CONTRACT.md +94 -0
- docs/frontier/README.md +52 -0
- docs/frontier/REFERENCES.md +176 -0
- docs/frontier/modules/anytime_inference.md +252 -0
- docs/frontier/modules/btsp_memory.md +311 -0
- docs/frontier/modules/causal_emergence.md +247 -0
- docs/frontier/modules/connectomics.md +195 -0
- docs/frontier/modules/continuum_memory.md +264 -0
- docs/frontier/modules/dendritic_layer.md +233 -0
- docs/frontier/modules/experiment_design.md +211 -0
- docs/frontier/modules/hh_cable.md +217 -0
- docs/frontier/modules/joint_failure.md +307 -0
- docs/frontier/modules/kuramoto_binding.md +337 -0
- docs/frontier/modules/morphogenesis.md +182 -0
- docs/frontier/modules/muon_optimizer.md +259 -0
- docs/frontier/modules/nir_export.md +220 -0
- docs/frontier/modules/quality_diversity.md +439 -0
- docs/frontier/modules/recursive_refiner.md +258 -0
- docs/frontier/modules/rigl_sparse.md +204 -0
- docs/frontier/modules/sparse_dictionary.md +258 -0
- docs/frontier/modules/synchrony.md +338 -0
- docs/neuroweave/CHANGELOG.md +60 -1
- docs/neuroweave/FEATURE_MATRIX.md +2 -2
- docs/neuroweave/README.md +183 -11
- pyproject.toml +55 -3
- scripts/neuroweave_compat_manifest.py +158 -51
- synapse/__init__.py +1 -1
- synapse/adaptation_study.py +2 -2
- synapse/agent.py +24 -4
- synapse/capabilities.py +3 -3
- synapse/cli.py +25 -1
- synapse/config.py +42 -0
- synapse/energy_efficiency_assay.py +1 -1
- synapse/frontier/__init__.py +7 -0
- synapse/frontier/anytime.py +511 -0
- synapse/frontier/bridge.py +141 -0
- synapse/frontier/btsp.py +964 -0
- synapse/frontier/causal_emergence.py +1365 -0
- synapse/frontier/cli_commands.py +223 -0
- synapse/frontier/connectomics.py +1205 -0
- synapse/frontier/continuum_memory.py +767 -0
- synapse/frontier/dendritic.py +592 -0
.github/dependabot.yml
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version: 2
|
| 2 |
+
updates:
|
| 3 |
+
- package-ecosystem: "pip"
|
| 4 |
+
directory: "/"
|
| 5 |
+
schedule:
|
| 6 |
+
interval: "weekly"
|
| 7 |
+
open-pull-requests-limit: 5
|
| 8 |
+
- package-ecosystem: "github-actions"
|
| 9 |
+
directory: "/"
|
| 10 |
+
schedule:
|
| 11 |
+
interval: "weekly"
|
| 12 |
+
open-pull-requests-limit: 5
|
.github/workflows/regression.yml
CHANGED
|
@@ -15,22 +15,83 @@ concurrency:
|
|
| 15 |
group: regression-${{ github.workflow }}-${{ github.ref }}
|
| 16 |
cancel-in-progress: true
|
| 17 |
|
|
|
|
|
|
|
|
|
|
| 18 |
jobs:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
pytest:
|
| 20 |
runs-on: ubuntu-latest
|
| 21 |
timeout-minutes: 60
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
env:
|
| 23 |
OMP_NUM_THREADS: '1'
|
| 24 |
MKL_NUM_THREADS: '1'
|
| 25 |
OPENBLAS_NUM_THREADS: '1'
|
| 26 |
steps:
|
| 27 |
- name: Check out source
|
| 28 |
-
uses: actions/checkout@v4
|
|
|
|
|
|
|
| 29 |
|
| 30 |
-
- name: Set up Python
|
| 31 |
-
uses: actions/setup-python@v5
|
| 32 |
with:
|
| 33 |
-
python-version:
|
| 34 |
cache: pip
|
| 35 |
cache-dependency-path: pyproject.toml
|
| 36 |
|
|
@@ -40,13 +101,17 @@ jobs:
|
|
| 40 |
- name: Install project and test dependencies
|
| 41 |
run: python -m pip install -e '.[test,connectomes,yaml]'
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
- name: Run full regression suite
|
| 44 |
-
run: python -m pytest -q --junitxml=pytest-results.xml
|
| 45 |
|
| 46 |
- name: Upload test report
|
| 47 |
if: always()
|
| 48 |
-
uses: actions/upload-artifact@v4
|
| 49 |
with:
|
| 50 |
-
name: pytest-results
|
| 51 |
-
path: pytest-results.xml
|
| 52 |
if-no-files-found: ignore
|
|
|
|
| 15 |
group: regression-${{ github.workflow }}-${{ github.ref }}
|
| 16 |
cancel-in-progress: true
|
| 17 |
|
| 18 |
+
# Every action is pinned to a full commit SHA (resolved with
|
| 19 |
+
# `gh api repos/<owner>/<repo>/git/ref/tags/<tag>`); the trailing comment names
|
| 20 |
+
# the release so Dependabot can propose updates.
|
| 21 |
jobs:
|
| 22 |
+
lint-and-contracts:
|
| 23 |
+
runs-on: ubuntu-latest
|
| 24 |
+
timeout-minutes: 15
|
| 25 |
+
steps:
|
| 26 |
+
- name: Check out source
|
| 27 |
+
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
| 28 |
+
with:
|
| 29 |
+
persist-credentials: false
|
| 30 |
+
|
| 31 |
+
- name: Set up Python
|
| 32 |
+
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
| 33 |
+
with:
|
| 34 |
+
python-version: '3.12'
|
| 35 |
+
cache: pip
|
| 36 |
+
cache-dependency-path: pyproject.toml
|
| 37 |
+
|
| 38 |
+
- name: Install CPU PyTorch, project and lint tooling
|
| 39 |
+
run: |
|
| 40 |
+
python -m pip install torch==2.11.0 --index-url https://download.pytorch.org/whl/cpu
|
| 41 |
+
python -m pip install . 'ruff==0.15.16'
|
| 42 |
+
|
| 43 |
+
- name: Start an agent from the installed wheel
|
| 44 |
+
working-directory: ${{ runner.temp }}
|
| 45 |
+
run: |
|
| 46 |
+
python - <<'PY'
|
| 47 |
+
from synapse.agent import IntegratedAgent
|
| 48 |
+
from synapse.config import SynapseConfig, tidal_checkpoint_path
|
| 49 |
+
from synapse.frontier.spec import MODULE_IDS
|
| 50 |
+
|
| 51 |
+
assert tidal_checkpoint_path().is_file()
|
| 52 |
+
assert len(MODULE_IDS) == 18
|
| 53 |
+
IntegratedAgent(SynapseConfig(nodes_per_source=16))
|
| 54 |
+
PY
|
| 55 |
+
|
| 56 |
+
- name: Ruff lint check
|
| 57 |
+
run: ruff check synapse tests scripts
|
| 58 |
+
|
| 59 |
+
- name: JavaScript syntax check
|
| 60 |
+
run: node --check synapse/web/app.js
|
| 61 |
+
|
| 62 |
+
- name: Pre-NEUROWEAVE compatibility manifest check
|
| 63 |
+
run: python scripts/neuroweave_compat_manifest.py --check
|
| 64 |
+
|
| 65 |
+
- name: Pre-Frontier compatibility manifest check
|
| 66 |
+
run: >-
|
| 67 |
+
python scripts/neuroweave_compat_manifest.py
|
| 68 |
+
--manifest docs/compatibility/manifest-pre-frontier.json
|
| 69 |
+
--baseline-tag sonapse-pre-frontier-baseline
|
| 70 |
+
--check
|
| 71 |
+
|
| 72 |
pytest:
|
| 73 |
runs-on: ubuntu-latest
|
| 74 |
timeout-minutes: 60
|
| 75 |
+
strategy:
|
| 76 |
+
fail-fast: false
|
| 77 |
+
matrix:
|
| 78 |
+
# torch 2.11.0+cpu manylinux_2_28_x86_64 wheels exist for cp310, cp312 and cp313
|
| 79 |
+
# (https://download.pytorch.org/whl/cpu/torch/, checked 2026-11-20).
|
| 80 |
+
python-version: ['3.10', '3.12', '3.13']
|
| 81 |
env:
|
| 82 |
OMP_NUM_THREADS: '1'
|
| 83 |
MKL_NUM_THREADS: '1'
|
| 84 |
OPENBLAS_NUM_THREADS: '1'
|
| 85 |
steps:
|
| 86 |
- name: Check out source
|
| 87 |
+
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
| 88 |
+
with:
|
| 89 |
+
persist-credentials: false
|
| 90 |
|
| 91 |
+
- name: Set up Python ${{ matrix.python-version }}
|
| 92 |
+
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
| 93 |
with:
|
| 94 |
+
python-version: ${{ matrix.python-version }}
|
| 95 |
cache: pip
|
| 96 |
cache-dependency-path: pyproject.toml
|
| 97 |
|
|
|
|
| 101 |
- name: Install project and test dependencies
|
| 102 |
run: python -m pip install -e '.[test,connectomes,yaml]'
|
| 103 |
|
| 104 |
+
- name: Install NIR for the interchange round-trip test
|
| 105 |
+
if: matrix.python-version == '3.12'
|
| 106 |
+
run: python -m pip install 'nir==1.0.8' 'h5py==3.14.0'
|
| 107 |
+
|
| 108 |
- name: Run full regression suite
|
| 109 |
+
run: python -m pytest -q --junitxml=pytest-results-${{ matrix.python-version }}.xml
|
| 110 |
|
| 111 |
- name: Upload test report
|
| 112 |
if: always()
|
| 113 |
+
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
| 114 |
with:
|
| 115 |
+
name: pytest-results-py${{ matrix.python-version }}
|
| 116 |
+
path: pytest-results-${{ matrix.python-version }}.xml
|
| 117 |
if-no-files-found: ignore
|
.pre-commit-config.yaml
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hooks are frozen to full commit SHAs (resolved with `gh api .../git/ref/tags/<tag>`).
|
| 2 |
+
# Ruff reads the same [tool.ruff] selection from pyproject.toml as CI.
|
| 3 |
+
repos:
|
| 4 |
+
- repo: https://github.com/astral-sh/ruff-pre-commit
|
| 5 |
+
rev: 22f0422809455ec89ffdcf5a00170ba816e42ddb # frozen: v0.15.16
|
| 6 |
+
hooks:
|
| 7 |
+
- id: ruff-check
|
| 8 |
+
exclude: ^synapse/_vendor/
|
| 9 |
+
- repo: https://github.com/pre-commit/pre-commit-hooks
|
| 10 |
+
rev: 3e8a8703264a2f4a69428a0aa4dcb512790b2c8c # frozen: v6.0.0
|
| 11 |
+
hooks:
|
| 12 |
+
- id: check-yaml
|
| 13 |
+
- id: check-json
|
| 14 |
+
exclude: ^(docs/results/|synapse/_vendor/)
|
| 15 |
+
# Whitespace fixers are limited to the configuration/metadata file types this
|
| 16 |
+
# change introduces, so they never rewrite existing Python, Markdown or data files.
|
| 17 |
+
- id: end-of-file-fixer
|
| 18 |
+
files: \.(cff|ya?ml)$
|
| 19 |
+
- id: trailing-whitespace
|
| 20 |
+
files: \.(cff|ya?ml)$
|
CITATION.cff
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
cff-version: 1.2.0
|
| 2 |
+
title: "Sonapse-LAB / SYNAPSE: a CPU-first connectome research workbench"
|
| 3 |
+
message: "If you use Sonapse-LAB or SYNAPSE in your research, please cite it using the metadata below."
|
| 4 |
+
type: software
|
| 5 |
+
authors:
|
| 6 |
+
- given-names: Kai
|
| 7 |
+
family-names: Piper
|
| 8 |
+
alias: kai9987kai
|
| 9 |
+
abstract: >-
|
| 10 |
+
Integrated connectome, weight-programming and bounded recursive-self-improvement
|
| 11 |
+
research workbench with opt-in NEUROWEAVE and Frontier extensions, sealed experiment
|
| 12 |
+
receipts and additive compatibility manifests. Synthetic research software; no claim
|
| 13 |
+
of biological fidelity or general intelligence.
|
| 14 |
+
license: Apache-2.0
|
| 15 |
+
version: 0.3.0
|
| 16 |
+
date-released: "2026-11-19"
|
| 17 |
+
repository-code: "https://github.com/kai9987kai/Sonapse-LAB"
|
| 18 |
+
url: "https://huggingface.co/Kai9987kai/Sonapse-LAB"
|
| 19 |
+
keywords:
|
| 20 |
+
- computational-neuroscience
|
| 21 |
+
- connectomics
|
| 22 |
+
- neuromorphic-computing
|
| 23 |
+
- reinforcement-learning
|
| 24 |
+
- spiking-neural-networks
|
| 25 |
+
- reproducibility
|
MANIFEST.in
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
include CITATION.cff
|
| 2 |
+
global-exclude *.pyc *.pyo
|
README.md
CHANGED
|
@@ -389,6 +389,23 @@ The runtime provides toggleable research implementations of recent frontier tech
|
|
| 389 |
|
| 390 |
All options are configurable in `SynapseConfig`, controllable via the web workbench HUD and settings, and fully preserved across mid-episode state checkpoints.
|
| 391 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 392 |
## Upstream Lineage & Research Grounding
|
| 393 |
|
| 394 |
SYNAPSE unifies innovations from:
|
|
@@ -411,7 +428,7 @@ It is **off by default**:
|
|
| 411 |
All results are `synthetic_abstraction`: not biological validation, not emotions, not FPGA hardware.
|
| 412 |
|
| 413 |
What it includes:
|
| 414 |
-
- 45 mechanisms
|
| 415 |
- 16 sensory channels with scalar-only privacy rules
|
| 416 |
- 24 experiments with sealed receipts
|
| 417 |
- package, standalone HTML and FPGA-mapping exports
|
|
|
|
| 389 |
|
| 390 |
All options are configurable in `SynapseConfig`, controllable via the web workbench HUD and settings, and fully preserved across mid-episode state checkpoints.
|
| 391 |
|
| 392 |
+
## Frontier Pack
|
| 393 |
+
|
| 394 |
+
Sonapse 0.3.0 includes 18 experimental modules covering neural dynamics, memory,
|
| 395 |
+
connectivity, sparse learning, experiment design and model interchange. List the
|
| 396 |
+
modules and experiments, then run the Hodgkin–Huxley cable reference check:
|
| 397 |
+
|
| 398 |
+
```bash
|
| 399 |
+
python -m synapse.cli frontier catalog
|
| 400 |
+
python -m synapse.cli frontier experiment --id hh_cable --quick
|
| 401 |
+
```
|
| 402 |
+
|
| 403 |
+
Ordinary agent runs leave the pack disabled. Max Mode enables read-only observers.
|
| 404 |
+
The workbench also has an isolated lab for stepping observers and running experiments.
|
| 405 |
+
Each experiment produces a receipt with its checks or comparisons and a digest.
|
| 406 |
+
The results describe synthetic models. See the [module catalog](docs/frontier/README.md)
|
| 407 |
+
for individual controls, results and limitations.
|
| 408 |
+
|
| 409 |
## Upstream Lineage & Research Grounding
|
| 410 |
|
| 411 |
SYNAPSE unifies innovations from:
|
|
|
|
| 428 |
All results are `synthetic_abstraction`: not biological validation, not emotions, not FPGA hardware.
|
| 429 |
|
| 430 |
What it includes:
|
| 431 |
+
- 45 mechanisms, all consumed by the runtime. `associative_memory` and `fast_weights` became engine-level mechanisms on 2026-11-19 ([rules](docs/neuroweave/README.md#6-learning-mechanisms), `tests/test_neuroweave_assoc_fastweights.py`); the standalone page does not execute them, and no benefit has been shown.
|
| 432 |
- 16 sensory channels with scalar-only privacy rules
|
| 433 |
- 24 experiments with sealed receipts
|
| 434 |
- package, standalone HTML and FPGA-mapping exports
|
docs/ENGINEERING.md
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Engineering notes (v0.3.0)
|
| 2 |
+
|
| 3 |
+
Toolchain, local checks, CI, security posture and the additive-compatibility contract for
|
| 4 |
+
**Sonapse-LAB / SYNAPSE 0.3.0**. Everything here describes configuration in this repository or a run made
|
| 5 |
+
locally on 2026-11-20 (Windows 11 on ARM64, Python 3.12.10, ruff 0.15.16, Node v24). GitHub Actions did not run
|
| 6 |
+
as part of writing this page, so no CI result is claimed.
|
| 7 |
+
|
| 8 |
+
The 0.3.0 engineering changes are additive. They add metadata, tooling, documentation, a theme selector and
|
| 9 |
+
accessibility attributes; they do not change simulation, training, checkpoint or HTTP behaviour.
|
| 10 |
+
|
| 11 |
+
## 1. Toolchain
|
| 12 |
+
|
| 13 |
+
| Item | Where | Value |
|
| 14 |
+
|---|---|---|
|
| 15 |
+
| Version | `pyproject.toml`, `synapse/__init__.py` | `0.3.0`; `python -m synapse --version` prints `synapse-connectome-lab 0.3.0` |
|
| 16 |
+
| Python | `requires-python` | `>=3.10`; CI matrix `3.10`, `3.12`, `3.13` |
|
| 17 |
+
| Build backend | `[build-system]` | `setuptools>=77` (PEP 639 `license = "Apache-2.0"` + `license-files`) |
|
| 18 |
+
| Runtime deps | `[project] dependencies` | `torch>=2.4`, `numpy>=1.26`, `scipy>=1.11` (unchanged) |
|
| 19 |
+
| Extras | `[project.optional-dependencies]` | `test`, `connectomes`, `yaml` (unchanged) |
|
| 20 |
+
| Dev group | `[dependency-groups]` (PEP 735) | `pytest>=8`, `ruff>=0.8`, `pip-audit>=2.7`, `hypothesis>=6` |
|
| 21 |
+
| Citation | `CITATION.cff` | CFF 1.2.0; validated locally against the CFF 1.2.0 JSON schema |
|
| 22 |
+
|
| 23 |
+
Install the `dev` group with any installer that implements PEP 735, or install the four packages directly:
|
| 24 |
+
|
| 25 |
+
```bash
|
| 26 |
+
python -m pip install "pytest>=8" "ruff>=0.8" "pip-audit>=2.7" "hypothesis>=6"
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
Package metadata was built locally with `setuptools.build_meta.prepare_metadata_for_build_wheel` (setuptools 81):
|
| 30 |
+
it reports `Metadata-Version: 2.4`, `License-Expression: Apache-2.0`, `License-File: LICENSE`, the keywords,
|
| 31 |
+
classifiers and both `Project-URL` entries.
|
| 32 |
+
|
| 33 |
+
The distribution includes the Tidal checkpoint in `share/synapse-connectome-lab/`. The agent uses the
|
| 34 |
+
checkout or configured `SYNAPSE_HOME/artifacts/tidal_core.pt` first. For a wheel install it can also locate
|
| 35 |
+
the bundled checkpoint. Both distribution formats exclude generated Python bytecode.
|
| 36 |
+
|
| 37 |
+
## 2. Local checks
|
| 38 |
+
|
| 39 |
+
Run tests single-threaded, as CI does:
|
| 40 |
+
|
| 41 |
+
```bash
|
| 42 |
+
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 python -m pytest -q
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
Static checks (the same commands as the `lint-and-contracts` CI job):
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
ruff check synapse tests scripts
|
| 49 |
+
node --check synapse/web/app.js
|
| 50 |
+
python scripts/neuroweave_compat_manifest.py --check
|
| 51 |
+
python scripts/neuroweave_compat_manifest.py --manifest docs/compatibility/manifest-pre-frontier.json \
|
| 52 |
+
--baseline-tag sonapse-pre-frontier-baseline --check
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
`tests/test_compat_manifest_tool.py` covers the manifest tool, both manifests, version consistency
|
| 56 |
+
(`pyproject.toml`, `synapse.__version__`, `CITATION.cff`, `--version`), the action SHA pins and the static
|
| 57 |
+
theme/accessibility checks in section 7.
|
| 58 |
+
|
| 59 |
+
### Pre-commit
|
| 60 |
+
|
| 61 |
+
`.pre-commit-config.yaml` pins both hook repositories to full commit SHAs:
|
| 62 |
+
|
| 63 |
+
| Repository | Tag | Commit | Hooks |
|
| 64 |
+
|---|---|---|---|
|
| 65 |
+
| `astral-sh/ruff-pre-commit` | v0.15.16 | `22f0422809455ec89ffdcf5a00170ba816e42ddb` | `ruff-check` (reads `[tool.ruff]` from `pyproject.toml`) |
|
| 66 |
+
| `pre-commit/pre-commit-hooks` | v6.0.0 | `3e8a8703264a2f4a69428a0aa4dcb512790b2c8c` | `check-yaml`, `check-json`, `end-of-file-fixer`, `trailing-whitespace` |
|
| 67 |
+
|
| 68 |
+
`check-json` excludes `docs/results/` and `synapse/_vendor/`. The whitespace fixers only touch `*.cff`, `*.yml` and
|
| 69 |
+
`*.yaml`, so they never rewrite existing Python, Markdown or data files. The hook ids were confirmed in each
|
| 70 |
+
repository's `.pre-commit-hooks.yaml` at the pinned commit. The JSON, YAML and whitespace hooks were emulated
|
| 71 |
+
locally over all tracked and new files (0 failures); `pre-commit` itself was not installed or run.
|
| 72 |
+
|
| 73 |
+
## 3. Lint policy
|
| 74 |
+
|
| 75 |
+
`[tool.ruff]`: `target-version = "py310"`, `line-length = 140`, `extend-exclude = ["synapse/_vendor"]`. The enforced
|
| 76 |
+
selection covers correctness rules, including undefined names in runtime code and annotations.
|
| 77 |
+
|
| 78 |
+
```toml
|
| 79 |
+
select = [
|
| 80 |
+
"E9", "F63", "F7", "F50", "F52", "F601", "F602", "F621", "F622", "F821", "F822", "F823", "F901",
|
| 81 |
+
"W605", "PLE",
|
| 82 |
+
"B002", "B003", "B004", "B011", "B012", "B013", "B014", "B015", "B016", "B019", "B020",
|
| 83 |
+
"B021", "B022", "B025", "B026", "B029", "B030", "B031", "B032", "B033", "B034", "B035", "B039",
|
| 84 |
+
]
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
`ruff check synapse tests scripts` printed `All checks passed!` on 2026-11-20. With `target-version = "py310"`,
|
| 88 |
+
ruff also reports syntax that needs a newer interpreter (for example `except*` or PEP 701 f-strings) under `E9`;
|
| 89 |
+
a local probe file confirmed this. That keeps the Python 3.10 CI leg honest.
|
| 90 |
+
|
| 91 |
+
### Broader rule set (future work, not enforced)
|
| 92 |
+
|
| 93 |
+
`ruff check --select=F,E,W,B,UP --statistics synapse tests scripts` (same `pyproject.toml` settings), measured
|
| 94 |
+
2026-11-20 with ruff 0.15.16 while other work was still landing in the tree: **5,522 findings**, 3,209 of them
|
| 95 |
+
auto-fixable. The largest groups:
|
| 96 |
+
|
| 97 |
+
| Rule | Count | Meaning |
|
| 98 |
+
|---|---:|---|
|
| 99 |
+
| `UP006` | 1,709 | `typing.List`/`Dict` annotations instead of built-in generics |
|
| 100 |
+
| `F401` | 797 | unused import |
|
| 101 |
+
| `UP035` | 630 | deprecated `typing` import |
|
| 102 |
+
| `E501` | 567 | line longer than 140 |
|
| 103 |
+
| `E702` | 494 | several statements on one line (semicolon) |
|
| 104 |
+
| `UP045` | 334 | `Optional[X]` instead of `X \| None` |
|
| 105 |
+
| `E701` | 289 | several statements on one line (colon) |
|
| 106 |
+
| `W293` | 285 | whitespace on a blank line |
|
| 107 |
+
| `B905` | 186 | `zip()` without `strict=` |
|
| 108 |
+
| `F841` | 55 | unused local variable |
|
| 109 |
+
| `B007` | 54 | unused loop variable |
|
| 110 |
+
| `UP037` | 45 | quoted annotation |
|
| 111 |
+
| `B023` | 15 | closure uses a loop variable |
|
| 112 |
+
| `F821` | 5 | undefined name |
|
| 113 |
+
| `B006` | 4 | mutable default argument |
|
| 114 |
+
|
| 115 |
+
The release review resolved all five `F821` findings and enabled the rule in CI. The `B023` and `B006`
|
| 116 |
+
findings remain candidates for review.
|
| 117 |
+
|
| 118 |
+
## 4. Continuous integration (`.github/workflows/regression.yml`)
|
| 119 |
+
|
| 120 |
+
Triggers, permissions (`contents: read`) and concurrency are unchanged. Every action is pinned to a full commit
|
| 121 |
+
SHA, resolved on 2026-11-20 with `gh api repos/<owner>/<repo>/git/ref/tags/<tag>` (all three tags are lightweight
|
| 122 |
+
tags that point directly at commits, so no dereferencing was needed):
|
| 123 |
+
|
| 124 |
+
| Action | Tag | Commit |
|
| 125 |
+
|---|---|---|
|
| 126 |
+
| `actions/checkout` | v4.4.0 | `11d5960a326750d5838078e36cf38b85af677262` |
|
| 127 |
+
| `actions/setup-python` | v5.6.0 | `a26af69be951a213d495a4c3e4e4022e16d87065` |
|
| 128 |
+
| `actions/upload-artifact` | v4.6.2 | `ea165f8d65b6e75b540449e92b4886f43607fa02` |
|
| 129 |
+
|
| 130 |
+
The major versions match the previously used `@v4`/`@v5`/`@v4` references. Checkout uses
|
| 131 |
+
`persist-credentials: false`.
|
| 132 |
+
|
| 133 |
+
Jobs:
|
| 134 |
+
|
| 135 |
+
1. **`lint-and-contracts`** (Python 3.12, `timeout-minutes: 15`): installs CPU `torch==2.11.0`, the project and
|
| 136 |
+
`ruff==0.15.16`, starts a 16-node-per-source agent from the installed wheel outside the checkout, then runs
|
| 137 |
+
`ruff check synapse tests scripts`, `node --check synapse/web/app.js` (Node from the
|
| 138 |
+
runner image), the pre-NEUROWEAVE manifest check and the pre-Frontier manifest check.
|
| 139 |
+
2. **`pytest`** (`timeout-minutes: 60`, `fail-fast: false`, matrix `3.10`, `3.12`, `3.13`): same steps as before
|
| 140 |
+
(CPU `torch==2.11.0`, `pip install -e '.[test,connectomes,yaml]'`, `python -m pytest -q` with one BLAS/OpenMP
|
| 141 |
+
thread), with a per-version JUnit report artifact. Python 3.12 also installs `nir==1.0.8` and
|
| 142 |
+
`h5py==3.14.0` to exercise the HDF5 interchange path. The other legs exercise the JSON fallback.
|
| 143 |
+
|
| 144 |
+
`torch-2.11.0+cpu` `manylinux_2_28_x86_64` wheels for `cp310`, `cp312` and `cp313` were listed at
|
| 145 |
+
<https://download.pytorch.org/whl/cpu/torch/> when checked on 2026-11-20, so no matrix entry was dropped.
|
| 146 |
+
|
| 147 |
+
`.github/dependabot.yml` checks `pip` and `github-actions` weekly (at most 5 open PRs each). The version comment
|
| 148 |
+
after each SHA lets Dependabot propose pin updates.
|
| 149 |
+
|
| 150 |
+
## 5. Security posture
|
| 151 |
+
|
| 152 |
+
These controls exist in the code (paths are relative to the repository root):
|
| 153 |
+
|
| 154 |
+
- **HTTP workbench** (`synapse/server.py`): responses carry `Content-Security-Policy: default-src 'self';
|
| 155 |
+
script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; img-src 'self' data:; connect-src 'self'`,
|
| 156 |
+
`X-Content-Type-Options: nosniff` and `Cache-Control: no-store`. `POST` requires a loopback host and same
|
| 157 |
+
origin, `Content-Type: application/json`, and a body of 1 byte to 1 MiB (`MAX_BODY`); JSON with `NaN` or
|
| 158 |
+
`Infinity` is rejected and responses are serialised with `allow_nan=False`.
|
| 159 |
+
- **Checkpoints**: `synapse/stateio.py` loads archives with `torch.load(..., map_location='cpu', weights_only=True)`.
|
| 160 |
+
Weight archives in `synapse/experiments.py` and connectome caches in `synapse/connectome_assets.py` use
|
| 161 |
+
`np.load(..., allow_pickle=False)`.
|
| 162 |
+
- **Known exception**: `synapse/capabilities.py` (bundled MaleCNS type table under `synapse/_vendor`) and
|
| 163 |
+
`synapse/connectome_compiler.py` (default bundled dataset, or a caller-supplied `data_path`) call
|
| 164 |
+
`np.load(..., allow_pickle=True)`. Only pass trusted files there; removing the pickle requirement is open work.
|
| 165 |
+
- **Read-only package inspection**: `NeuroWeaveWorkbenchAPI.inspect` in `synapse/neuroweave/workbench_api.py` accepts
|
| 166 |
+
at most `MAX_INSPECT_BYTES = 1_000_000` bytes of package text and returns `read_only: true` and
|
| 167 |
+
`live_state_changed: false`.
|
| 168 |
+
- **No raw media**: the NEUROWEAVE workbench API and package reader reject raw frame/audio keys
|
| 169 |
+
(`RAW_MEDIA_KEYS` in `synapse/neuroweave/workbench_api.py` and `synapse/neuroweave/package.py`); the sensory
|
| 170 |
+
endpoints take bounded derived summaries.
|
| 171 |
+
- **Offline exports**: standalone HTML exports (`synapse/portable_export.py`, `synapse/neuroweave/standalone.py`)
|
| 172 |
+
set a `default-src 'none'` CSP meta tag.
|
| 173 |
+
- **Frontier modules**: `docs/frontier/CONTRACT.md` requires `import_state` to validate fully before mutating.
|
| 174 |
+
|
| 175 |
+
## 6. Additive compatibility contract
|
| 176 |
+
|
| 177 |
+
Two manifests record the public surface of a baseline tag. A later tree passes `--check` when every recorded
|
| 178 |
+
item is still present and every recorded config default is equal; new items may be added freely.
|
| 179 |
+
|
| 180 |
+
| Manifest | Baseline tag | Commit |
|
| 181 |
+
|---|---|---|
|
| 182 |
+
| `docs/neuroweave/compatibility-manifest.json` (default) | `sonapse-pre-neuroweave-baseline` | `6f2761b` |
|
| 183 |
+
| `docs/compatibility/manifest-pre-frontier.json` | `sonapse-pre-frontier-baseline` | `b9d8270` |
|
| 184 |
+
|
| 185 |
+
Recorded sections: `config_defaults`, `cli_commands`, `cli_flags`, `http_routes`, `web_dom_ids`,
|
| 186 |
+
`checkpoint_namespaces`, `test_modules`, `max_mode_enabled_features`.
|
| 187 |
+
|
| 188 |
+
`scripts/neuroweave_compat_manifest.py`:
|
| 189 |
+
|
| 190 |
+
- `--check` / `--write` with no other flags behave as before (default manifest and tag).
|
| 191 |
+
- `--manifest PATH` selects another manifest (relative paths resolve against the repository root).
|
| 192 |
+
- `--baseline-tag TAG` labels a written manifest; with `--check` the manifest must also record that tag.
|
| 193 |
+
- `--root DIR` collects from another tree, such as a worktree of the baseline tag (run in a fresh interpreter).
|
| 194 |
+
- Route discovery scans `/api/...` string literals in every `synapse/**/*.py` except `synapse/_vendor`; CLI
|
| 195 |
+
discovery reads `synapse/cli.py` plus `synapse/neuroweave/cli_commands.py` and `synapse/frontier/cli_commands.py`
|
| 196 |
+
when they exist. Discovery only adds items to the current surface, so it cannot make an older manifest fail.
|
| 197 |
+
|
| 198 |
+
The pre-Frontier manifest was generated from a temporary worktree of `sonapse-pre-frontier-baseline`.
|
| 199 |
+
Regenerating it on 2026-11-20 with the current script produced a byte-identical file:
|
| 200 |
+
|
| 201 |
+
```bash
|
| 202 |
+
git worktree add <tmp>/pre-frontier-wt sonapse-pre-frontier-baseline
|
| 203 |
+
python scripts/neuroweave_compat_manifest.py --write --root <tmp>/pre-frontier-wt \
|
| 204 |
+
--manifest docs/compatibility/manifest-pre-frontier.json --baseline-tag sonapse-pre-frontier-baseline
|
| 205 |
+
git worktree remove --force <tmp>/pre-frontier-wt
|
| 206 |
+
```
|
| 207 |
+
|
| 208 |
+
## 7. Workbench theme and accessibility
|
| 209 |
+
|
| 210 |
+
- **Theme selector** (sidebar, `#theme-select`): Dark (default), Light, System. Dark leaves `<html>` without a
|
| 211 |
+
`data-theme` attribute, so a first visit with nothing stored renders exactly as before. Light and System set
|
| 212 |
+
`data-theme`; the `prefers-color-scheme` media query applies only under `data-theme="system"`. The choice is
|
| 213 |
+
stored under `synapse_theme_v1` in `localStorage`, and every storage call is wrapped in `try`/`catch`.
|
| 214 |
+
Canvases and the chat console stay dark in every theme because their drawing code assumes a dark background.
|
| 215 |
+
- **Contrast**: the test computes WCAG 2.x contrast for every light-theme text colour against every light surface,
|
| 216 |
+
with translucent fills composited over the page and panel colours. The lowest measured pair is 4.66:1 (teal
|
| 217 |
+
`#0b6e5b` on the composited tag fill `#e2dfdb`). White on accent fills is at least 6.18:1, omnibus buttons
|
| 218 |
+
on their inline tints are at least 6.16:1, and the dark chat console's colours are at least 4.80:1.
|
| 219 |
+
- **Accessibility**: a skip link to the focusable `<h1 id="title">`, `:focus-visible` outlines for links, `summary`
|
| 220 |
+
and programmatic focus targets (buttons and form fields already had them), `aria-current="page"` on the active
|
| 221 |
+
nav button (set inside the existing tab handler), `aria-label`s that contain the visible text on
|
| 222 |
+
pictograph-prefixed controls, and `role="status"`/`aria-live="polite"` on status lines that lacked a live region.
|
| 223 |
+
- **Manual check** (2026-11-20, built-in browser, `python -m synapse --nodes 16 serve`): a first load with
|
| 224 |
+
nothing stored was dark with no `data-theme`; Light persisted across a reload; with OS light emulation, System
|
| 225 |
+
switched to the light palette while Dark stayed dark; choosing Dark cleared the stored value; switching tabs
|
| 226 |
+
moved `aria-current`; the skip link moved focus to `#title`. The console showed no errors.
|
docs/compatibility/manifest-pre-frontier.json
ADDED
|
@@ -0,0 +1,1140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"baseline_commit": "b9d8270",
|
| 3 |
+
"baseline_commit_full": "b9d82707c4575fc4147765357487cc092b518736",
|
| 4 |
+
"baseline_tag": "sonapse-pre-frontier-baseline",
|
| 5 |
+
"checkpoint_namespaces": [
|
| 6 |
+
"active_inference",
|
| 7 |
+
"aether_bridge",
|
| 8 |
+
"apical_engine",
|
| 9 |
+
"archimedes_engine",
|
| 10 |
+
"auditory_encoder_state",
|
| 11 |
+
"comm_fabric",
|
| 12 |
+
"criticality_homeostat",
|
| 13 |
+
"cross_graft_engine",
|
| 14 |
+
"dendritic_ltc",
|
| 15 |
+
"dpo_engine",
|
| 16 |
+
"dsag_v1",
|
| 17 |
+
"dvgem_memory",
|
| 18 |
+
"event_backend",
|
| 19 |
+
"fatigue_controller",
|
| 20 |
+
"glymphatic_engine",
|
| 21 |
+
"graft_bus",
|
| 22 |
+
"grafted_diffusion",
|
| 23 |
+
"graph_diffusion",
|
| 24 |
+
"holographic_vsa",
|
| 25 |
+
"hyperbolic_manifold",
|
| 26 |
+
"knowledge_pool",
|
| 27 |
+
"kuramoto_engine",
|
| 28 |
+
"memory_carrier_nexus",
|
| 29 |
+
"metaplasticity_bcm",
|
| 30 |
+
"mixed_affect",
|
| 31 |
+
"multitimescale",
|
| 32 |
+
"neural_graft",
|
| 33 |
+
"neurowave_x2",
|
| 34 |
+
"neuroweave_v1",
|
| 35 |
+
"oscillatory_coherence",
|
| 36 |
+
"overflow_mini_brain",
|
| 37 |
+
"phase_protocol",
|
| 38 |
+
"programmed_prior_status",
|
| 39 |
+
"recurrent_planner",
|
| 40 |
+
"relational_memory",
|
| 41 |
+
"selective_ssm",
|
| 42 |
+
"source_provenance",
|
| 43 |
+
"spectral_reservoir",
|
| 44 |
+
"spiking_engine",
|
| 45 |
+
"synthetic_glands",
|
| 46 |
+
"tether_coordinator",
|
| 47 |
+
"thermodynamics",
|
| 48 |
+
"torch_rng",
|
| 49 |
+
"transfer_entropy",
|
| 50 |
+
"wave_solver",
|
| 51 |
+
"wpac"
|
| 52 |
+
],
|
| 53 |
+
"cli_commands": [
|
| 54 |
+
"ablate",
|
| 55 |
+
"ablation",
|
| 56 |
+
"adaptation-verify",
|
| 57 |
+
"astrocyte",
|
| 58 |
+
"atlas",
|
| 59 |
+
"autoprogram",
|
| 60 |
+
"benchmarks",
|
| 61 |
+
"capabilities",
|
| 62 |
+
"causal-growth",
|
| 63 |
+
"checkpoint-migration",
|
| 64 |
+
"coconut-think",
|
| 65 |
+
"connectome",
|
| 66 |
+
"connectome-assay",
|
| 67 |
+
"connectome-datasets",
|
| 68 |
+
"connectome-inventory",
|
| 69 |
+
"continual-backprop",
|
| 70 |
+
"controlled-study",
|
| 71 |
+
"curriculum-verify",
|
| 72 |
+
"diffusion-repair",
|
| 73 |
+
"dpo-align",
|
| 74 |
+
"dsag",
|
| 75 |
+
"ecology",
|
| 76 |
+
"efficiency",
|
| 77 |
+
"evidence",
|
| 78 |
+
"experiment",
|
| 79 |
+
"experiments",
|
| 80 |
+
"export",
|
| 81 |
+
"fast-memory",
|
| 82 |
+
"flagship",
|
| 83 |
+
"flagship-milestone",
|
| 84 |
+
"free_energy",
|
| 85 |
+
"frontier-innovations",
|
| 86 |
+
"frontier-v2",
|
| 87 |
+
"homeostasis",
|
| 88 |
+
"hyperprogram",
|
| 89 |
+
"import-legacy",
|
| 90 |
+
"inspect",
|
| 91 |
+
"lesion",
|
| 92 |
+
"live-rsi",
|
| 93 |
+
"manifest-check",
|
| 94 |
+
"manifold",
|
| 95 |
+
"mechanisms",
|
| 96 |
+
"meta-plasticity",
|
| 97 |
+
"metamorphic",
|
| 98 |
+
"mimomix",
|
| 99 |
+
"motifs",
|
| 100 |
+
"multi-connectome",
|
| 101 |
+
"multistep-plan",
|
| 102 |
+
"neural-comm",
|
| 103 |
+
"neurogenesis",
|
| 104 |
+
"neurowave-x2",
|
| 105 |
+
"neuroweave",
|
| 106 |
+
"omnibus",
|
| 107 |
+
"patch",
|
| 108 |
+
"planning-study",
|
| 109 |
+
"planning-verify",
|
| 110 |
+
"pretrain",
|
| 111 |
+
"reusable-skills",
|
| 112 |
+
"rsi-verify",
|
| 113 |
+
"scale-neurons",
|
| 114 |
+
"self-model-audit",
|
| 115 |
+
"sequence-search",
|
| 116 |
+
"serve",
|
| 117 |
+
"sleep-train",
|
| 118 |
+
"smoke",
|
| 119 |
+
"spectral",
|
| 120 |
+
"spiking",
|
| 121 |
+
"status",
|
| 122 |
+
"study",
|
| 123 |
+
"tool-arena",
|
| 124 |
+
"topology",
|
| 125 |
+
"transplant",
|
| 126 |
+
"uncertainty-calibrate",
|
| 127 |
+
"unified-eval",
|
| 128 |
+
"validate",
|
| 129 |
+
"verify",
|
| 130 |
+
"world-model-cem",
|
| 131 |
+
"world4d"
|
| 132 |
+
],
|
| 133 |
+
"cli_flags": [
|
| 134 |
+
"--active-training",
|
| 135 |
+
"--agent-nodes",
|
| 136 |
+
"--assay-trials",
|
| 137 |
+
"--batch-size",
|
| 138 |
+
"--budget",
|
| 139 |
+
"--candidates",
|
| 140 |
+
"--cem-horizon",
|
| 141 |
+
"--checkpoint",
|
| 142 |
+
"--compute-threads",
|
| 143 |
+
"--config",
|
| 144 |
+
"--connectome-mode",
|
| 145 |
+
"--csv",
|
| 146 |
+
"--diagnostic-episodes",
|
| 147 |
+
"--donor-task",
|
| 148 |
+
"--dsag",
|
| 149 |
+
"--dsag-config",
|
| 150 |
+
"--dsag-gain",
|
| 151 |
+
"--edits",
|
| 152 |
+
"--episodes",
|
| 153 |
+
"--eval-episodes",
|
| 154 |
+
"--eval-task",
|
| 155 |
+
"--feature",
|
| 156 |
+
"--fpga",
|
| 157 |
+
"--frontier-all",
|
| 158 |
+
"--frozen",
|
| 159 |
+
"--gain",
|
| 160 |
+
"--generations",
|
| 161 |
+
"--horizon",
|
| 162 |
+
"--horizons",
|
| 163 |
+
"--host",
|
| 164 |
+
"--html",
|
| 165 |
+
"--id",
|
| 166 |
+
"--input-dim",
|
| 167 |
+
"--landscapes",
|
| 168 |
+
"--mechanisms",
|
| 169 |
+
"--milestone-steps",
|
| 170 |
+
"--min-gain",
|
| 171 |
+
"--name",
|
| 172 |
+
"--neural-graft",
|
| 173 |
+
"--neurons",
|
| 174 |
+
"--neuroweave",
|
| 175 |
+
"--neuroweave-config",
|
| 176 |
+
"--nodes",
|
| 177 |
+
"--nodes-per-source",
|
| 178 |
+
"--out",
|
| 179 |
+
"--output",
|
| 180 |
+
"--pairs",
|
| 181 |
+
"--patch-type",
|
| 182 |
+
"--payload",
|
| 183 |
+
"--ponder",
|
| 184 |
+
"--port",
|
| 185 |
+
"--programmed-connectome",
|
| 186 |
+
"--query",
|
| 187 |
+
"--query-steps",
|
| 188 |
+
"--quick",
|
| 189 |
+
"--receipt",
|
| 190 |
+
"--repair-iters",
|
| 191 |
+
"--save",
|
| 192 |
+
"--save-report",
|
| 193 |
+
"--seed",
|
| 194 |
+
"--seeds",
|
| 195 |
+
"--seeds-per-landscape",
|
| 196 |
+
"--sleep-steps",
|
| 197 |
+
"--steps",
|
| 198 |
+
"--steps-per-stage",
|
| 199 |
+
"--steps-per-task",
|
| 200 |
+
"--study-nodes",
|
| 201 |
+
"--support-steps",
|
| 202 |
+
"--synapse-agent",
|
| 203 |
+
"--target",
|
| 204 |
+
"--targets",
|
| 205 |
+
"--task",
|
| 206 |
+
"--task-horizon",
|
| 207 |
+
"--tasks",
|
| 208 |
+
"--test-task",
|
| 209 |
+
"--think-depth",
|
| 210 |
+
"--topology",
|
| 211 |
+
"--total-neurons",
|
| 212 |
+
"--training-steps",
|
| 213 |
+
"--updates",
|
| 214 |
+
"--workers"
|
| 215 |
+
],
|
| 216 |
+
"config_defaults": {
|
| 217 |
+
"active_inference_planner": false,
|
| 218 |
+
"active_training": false,
|
| 219 |
+
"aether_bridge_control": "none",
|
| 220 |
+
"aether_bridge_gamma": 0.0,
|
| 221 |
+
"aether_bridge_modes": 16,
|
| 222 |
+
"aether_graft_bridge": false,
|
| 223 |
+
"affective_core": false,
|
| 224 |
+
"apical_amplification": false,
|
| 225 |
+
"archimedes_buoyancy": false,
|
| 226 |
+
"causal_world_model": false,
|
| 227 |
+
"cognition_interval": 8,
|
| 228 |
+
"compute_threads": 1,
|
| 229 |
+
"connectome_mode": "proxy",
|
| 230 |
+
"connectome_sources": [
|
| 231 |
+
"flywire",
|
| 232 |
+
"manc",
|
| 233 |
+
"optic-lobe"
|
| 234 |
+
],
|
| 235 |
+
"continual_backprop": false,
|
| 236 |
+
"criticality_homeostat": false,
|
| 237 |
+
"cross_connectome_graft": false,
|
| 238 |
+
"cross_model_exchange": false,
|
| 239 |
+
"dendritic_ltc": false,
|
| 240 |
+
"dormant_lifecycle": true,
|
| 241 |
+
"dsag": null,
|
| 242 |
+
"dvgem_memory": false,
|
| 243 |
+
"event_driven_backend": false,
|
| 244 |
+
"evo_compat": false,
|
| 245 |
+
"experience_horizon": 1,
|
| 246 |
+
"experience_planning": false,
|
| 247 |
+
"experimental_cognition": false,
|
| 248 |
+
"fast_weight_memory": false,
|
| 249 |
+
"frontier_all": false,
|
| 250 |
+
"glymphatic_clearance": false,
|
| 251 |
+
"graft_batch_size": 64,
|
| 252 |
+
"graft_bus_enabled": false,
|
| 253 |
+
"graft_updates": 2,
|
| 254 |
+
"grafted_diffusion": false,
|
| 255 |
+
"graph_diffusion": false,
|
| 256 |
+
"holographic_vsa": false,
|
| 257 |
+
"hyperbolic_manifold": false,
|
| 258 |
+
"latent_reasoning": false,
|
| 259 |
+
"live_chat": false,
|
| 260 |
+
"live_microphone": false,
|
| 261 |
+
"memory_carrier_nexus": false,
|
| 262 |
+
"meta_plasticity": false,
|
| 263 |
+
"metaplasticity_bcm": false,
|
| 264 |
+
"microsteps": 2,
|
| 265 |
+
"multitimescale_learning": false,
|
| 266 |
+
"neural_comm_dim": 16,
|
| 267 |
+
"neural_comm_drop_rate": 0.0,
|
| 268 |
+
"neural_comm_enabled": false,
|
| 269 |
+
"neural_comm_every": 1,
|
| 270 |
+
"neural_comm_latency_steps": 0,
|
| 271 |
+
"neural_comm_max_aux_current": 0.5,
|
| 272 |
+
"neural_comm_max_bits": 128,
|
| 273 |
+
"neural_comm_max_messages": 4,
|
| 274 |
+
"neural_comm_mode": "continuous",
|
| 275 |
+
"neural_comm_precision_bits": 4,
|
| 276 |
+
"neural_comm_topology": "hybrid_causal",
|
| 277 |
+
"neural_graft": false,
|
| 278 |
+
"neural_pulses": false,
|
| 279 |
+
"neuroendocrine": false,
|
| 280 |
+
"neurowave_enabled": false,
|
| 281 |
+
"neurowave_x2_dendritic": false,
|
| 282 |
+
"neurowave_x2_development": false,
|
| 283 |
+
"neurowave_x2_development_level": 0,
|
| 284 |
+
"neurowave_x2_dimension": 16,
|
| 285 |
+
"neurowave_x2_enabled": false,
|
| 286 |
+
"neurowave_x2_gamma": 0.0,
|
| 287 |
+
"neurowave_x2_phase": true,
|
| 288 |
+
"neurowave_x2_plasticity": false,
|
| 289 |
+
"neurowave_x2_precision_bits": 32,
|
| 290 |
+
"neurowave_x2_protocol": "adaptive",
|
| 291 |
+
"neurowave_x2_spectral_basis": "hybrid",
|
| 292 |
+
"neurowave_x2_spectral_modes": 8,
|
| 293 |
+
"neuroweave": null,
|
| 294 |
+
"nodes_per_source": 100,
|
| 295 |
+
"oscillatory_coherence": false,
|
| 296 |
+
"overflow_mini_brain": false,
|
| 297 |
+
"planner_algorithm": "experience_mpc",
|
| 298 |
+
"programmed_connectome": false,
|
| 299 |
+
"quantum_kuramoto": false,
|
| 300 |
+
"readout": "absolute",
|
| 301 |
+
"relational_memory": false,
|
| 302 |
+
"seed": 7,
|
| 303 |
+
"selective_state_space": false,
|
| 304 |
+
"self_model": false,
|
| 305 |
+
"shared_knowledge": false,
|
| 306 |
+
"sleep_replay": false,
|
| 307 |
+
"spectral_reservoir": false,
|
| 308 |
+
"spiking_neuromorphic": false,
|
| 309 |
+
"structural_learning": true,
|
| 310 |
+
"surprise_memory": true,
|
| 311 |
+
"synthetic_glands": false,
|
| 312 |
+
"task": "forage",
|
| 313 |
+
"tether_coordinator": false,
|
| 314 |
+
"thermodynamics": false,
|
| 315 |
+
"total_neurons": null,
|
| 316 |
+
"transfer_entropy": false,
|
| 317 |
+
"value_guided_planning": false,
|
| 318 |
+
"verifiable_dpo": false,
|
| 319 |
+
"verifier_rsi": false,
|
| 320 |
+
"virtual_ecology_v2": false
|
| 321 |
+
},
|
| 322 |
+
"contract": "additive-only: every recorded item must remain present; defaults must stay equal",
|
| 323 |
+
"http_routes": [
|
| 324 |
+
"/api/",
|
| 325 |
+
"/api/ablation-engine/run",
|
| 326 |
+
"/api/aether_bridge/status",
|
| 327 |
+
"/api/apical/status",
|
| 328 |
+
"/api/apical_reservoir_hyperbolic",
|
| 329 |
+
"/api/archimedes/status",
|
| 330 |
+
"/api/atlas",
|
| 331 |
+
"/api/audio",
|
| 332 |
+
"/api/audio/push",
|
| 333 |
+
"/api/audio/toggle",
|
| 334 |
+
"/api/autoprogram",
|
| 335 |
+
"/api/benchmark-suite/catalog",
|
| 336 |
+
"/api/benchmark-suite/run",
|
| 337 |
+
"/api/capabilities",
|
| 338 |
+
"/api/causal-world/run",
|
| 339 |
+
"/api/causal_9arm",
|
| 340 |
+
"/api/chat",
|
| 341 |
+
"/api/checkpoint-migration/run",
|
| 342 |
+
"/api/checkpoints",
|
| 343 |
+
"/api/connectome/fusion/couple",
|
| 344 |
+
"/api/connectome/fusion/summary",
|
| 345 |
+
"/api/connectome/pac",
|
| 346 |
+
"/api/connectome/pac/enable",
|
| 347 |
+
"/api/connectome/stdp",
|
| 348 |
+
"/api/connectome/stdp/enable",
|
| 349 |
+
"/api/connectomes",
|
| 350 |
+
"/api/connectomes/fusion",
|
| 351 |
+
"/api/connectomes/fusion/couple",
|
| 352 |
+
"/api/connectomes/fusion/summary",
|
| 353 |
+
"/api/connectomes/inventory",
|
| 354 |
+
"/api/continual_backprop/status",
|
| 355 |
+
"/api/controlled_study",
|
| 356 |
+
"/api/criticality_vsa",
|
| 357 |
+
"/api/cross_graft/status",
|
| 358 |
+
"/api/diffusion_dpo",
|
| 359 |
+
"/api/dormant/status",
|
| 360 |
+
"/api/dsag/status",
|
| 361 |
+
"/api/dvgem_tether",
|
| 362 |
+
"/api/ecology",
|
| 363 |
+
"/api/ecology/allostasis",
|
| 364 |
+
"/api/ecology/allostasis/enable",
|
| 365 |
+
"/api/ecology/epigenetics",
|
| 366 |
+
"/api/ecology/epigenetics/enable",
|
| 367 |
+
"/api/ecology/evolution",
|
| 368 |
+
"/api/ecology/soundscape",
|
| 369 |
+
"/api/ecology/stats",
|
| 370 |
+
"/api/ecology/step",
|
| 371 |
+
"/api/ecology/tournament/cataclysm",
|
| 372 |
+
"/api/ecology/tournament/run",
|
| 373 |
+
"/api/ecology/tournament/status",
|
| 374 |
+
"/api/ecology/vocalize",
|
| 375 |
+
"/api/event-driven/run",
|
| 376 |
+
"/api/evo/candidates",
|
| 377 |
+
"/api/evo/transact",
|
| 378 |
+
"/api/experience/mode",
|
| 379 |
+
"/api/experience/preview",
|
| 380 |
+
"/api/export",
|
| 381 |
+
"/api/export/status/",
|
| 382 |
+
"/api/exports/",
|
| 383 |
+
"/api/fast_weight/status",
|
| 384 |
+
"/api/flagship",
|
| 385 |
+
"/api/frontier/innovations",
|
| 386 |
+
"/api/frontier/v2_innovations",
|
| 387 |
+
"/api/frontier_v4_assay",
|
| 388 |
+
"/api/glymphatic/status",
|
| 389 |
+
"/api/graft_bus/status",
|
| 390 |
+
"/api/hyperbolic/status",
|
| 391 |
+
"/api/hyperprogram",
|
| 392 |
+
"/api/invoke",
|
| 393 |
+
"/api/jobs",
|
| 394 |
+
"/api/jobs/cancel",
|
| 395 |
+
"/api/knowledge",
|
| 396 |
+
"/api/kuramoto/status",
|
| 397 |
+
"/api/load",
|
| 398 |
+
"/api/memory_carrier/status",
|
| 399 |
+
"/api/meta-plasticity/run",
|
| 400 |
+
"/api/metamorphic",
|
| 401 |
+
"/api/motif-discovery/run",
|
| 402 |
+
"/api/multimodal/synesthesia",
|
| 403 |
+
"/api/multimodal/synesthesia/burst",
|
| 404 |
+
"/api/neural-comm/bench",
|
| 405 |
+
"/api/neural-comm/config",
|
| 406 |
+
"/api/neural-comm/status",
|
| 407 |
+
"/api/neuroendocrine",
|
| 408 |
+
"/api/neuroweave/",
|
| 409 |
+
"/api/neuroweave/catalog",
|
| 410 |
+
"/api/neuroweave/configure",
|
| 411 |
+
"/api/neuroweave/ecology",
|
| 412 |
+
"/api/neuroweave/experiment",
|
| 413 |
+
"/api/neuroweave/export",
|
| 414 |
+
"/api/neuroweave/inspect",
|
| 415 |
+
"/api/neuroweave/ledger",
|
| 416 |
+
"/api/neuroweave/ledger/lab",
|
| 417 |
+
"/api/neuroweave/lesion",
|
| 418 |
+
"/api/neuroweave/observatory",
|
| 419 |
+
"/api/neuroweave/observatory/lab",
|
| 420 |
+
"/api/neuroweave/sensory",
|
| 421 |
+
"/api/neuroweave/sequence-search",
|
| 422 |
+
"/api/neuroweave/status",
|
| 423 |
+
"/api/neuroweave/step",
|
| 424 |
+
"/api/neuroweave/topology",
|
| 425 |
+
"/api/observatory/activity",
|
| 426 |
+
"/api/observatory/structure",
|
| 427 |
+
"/api/omnibus/reset",
|
| 428 |
+
"/api/omnibus/run",
|
| 429 |
+
"/api/omnibus/status",
|
| 430 |
+
"/api/omnibus/step",
|
| 431 |
+
"/api/pac/status",
|
| 432 |
+
"/api/patch/apply",
|
| 433 |
+
"/api/patch/evaluate",
|
| 434 |
+
"/api/patch/make",
|
| 435 |
+
"/api/patch/preview",
|
| 436 |
+
"/api/patch/rollback",
|
| 437 |
+
"/api/planning-study/receipt/",
|
| 438 |
+
"/api/pulses",
|
| 439 |
+
"/api/pulses/trigger",
|
| 440 |
+
"/api/reconsolidation/status",
|
| 441 |
+
"/api/relational-memory/run",
|
| 442 |
+
"/api/reservoir/status",
|
| 443 |
+
"/api/reset",
|
| 444 |
+
"/api/reusable_skills",
|
| 445 |
+
"/api/rsi/live",
|
| 446 |
+
"/api/save",
|
| 447 |
+
"/api/self_model/status",
|
| 448 |
+
"/api/sim-worker/control",
|
| 449 |
+
"/api/sim-worker/status",
|
| 450 |
+
"/api/sleep/consolidation/status",
|
| 451 |
+
"/api/sleep/dream_cycle",
|
| 452 |
+
"/api/sleep/reconsolidation",
|
| 453 |
+
"/api/sleep/reconsolidation/reactivate",
|
| 454 |
+
"/api/sleep/state",
|
| 455 |
+
"/api/sleep_replay",
|
| 456 |
+
"/api/soundscape",
|
| 457 |
+
"/api/spectral",
|
| 458 |
+
"/api/spiking/status",
|
| 459 |
+
"/api/state",
|
| 460 |
+
"/api/stdp/status",
|
| 461 |
+
"/api/step",
|
| 462 |
+
"/api/studies",
|
| 463 |
+
"/api/supermix/status",
|
| 464 |
+
"/api/supermix_archimedes_nexus_assay",
|
| 465 |
+
"/api/synesthesia",
|
| 466 |
+
"/api/tandem/max",
|
| 467 |
+
"/api/tandem/start",
|
| 468 |
+
"/api/tandem/status",
|
| 469 |
+
"/api/tensors",
|
| 470 |
+
"/api/tool-arena/status",
|
| 471 |
+
"/api/training/config",
|
| 472 |
+
"/api/training/intensive",
|
| 473 |
+
"/api/training/pretrain",
|
| 474 |
+
"/api/training/status",
|
| 475 |
+
"/api/transplant",
|
| 476 |
+
"/api/uncertainty/status",
|
| 477 |
+
"/api/verifier-rsi/run",
|
| 478 |
+
"/api/world4d/status"
|
| 479 |
+
],
|
| 480 |
+
"max_mode_enabled_features": [
|
| 481 |
+
"active_inference_planner",
|
| 482 |
+
"active_training",
|
| 483 |
+
"aether_graft_bridge",
|
| 484 |
+
"affective_core",
|
| 485 |
+
"apical_amplification",
|
| 486 |
+
"archimedes_buoyancy",
|
| 487 |
+
"causal_world_model",
|
| 488 |
+
"continual_backprop",
|
| 489 |
+
"criticality_homeostat",
|
| 490 |
+
"cross_connectome_graft",
|
| 491 |
+
"cross_model_exchange",
|
| 492 |
+
"dendritic_ltc",
|
| 493 |
+
"dormant_lifecycle",
|
| 494 |
+
"dsag_v1.axo_branches",
|
| 495 |
+
"dsag_v1.dual_soma",
|
| 496 |
+
"dsag_v1.enabled",
|
| 497 |
+
"dsag_v1.phase_gate_enabled",
|
| 498 |
+
"dsag_v1.plasticity_enabled",
|
| 499 |
+
"dsag_v1.richer_messages",
|
| 500 |
+
"dsag_v1.structural_growth_enabled",
|
| 501 |
+
"dvgem_memory",
|
| 502 |
+
"event_driven_backend",
|
| 503 |
+
"evo_compat",
|
| 504 |
+
"experience_planning",
|
| 505 |
+
"experimental_cognition",
|
| 506 |
+
"fast_weight_memory",
|
| 507 |
+
"frontier_all",
|
| 508 |
+
"glymphatic_clearance",
|
| 509 |
+
"graft_bus_enabled",
|
| 510 |
+
"grafted_diffusion",
|
| 511 |
+
"graph_diffusion",
|
| 512 |
+
"holographic_vsa",
|
| 513 |
+
"hyperbolic_manifold",
|
| 514 |
+
"latent_reasoning",
|
| 515 |
+
"live_chat",
|
| 516 |
+
"live_microphone",
|
| 517 |
+
"memory_carrier_nexus",
|
| 518 |
+
"meta_plasticity",
|
| 519 |
+
"metaplasticity_bcm",
|
| 520 |
+
"multitimescale_learning",
|
| 521 |
+
"neural_comm_enabled",
|
| 522 |
+
"neural_graft",
|
| 523 |
+
"neural_pulses",
|
| 524 |
+
"neuroendocrine",
|
| 525 |
+
"neurowave_enabled",
|
| 526 |
+
"neurowave_x2_dendritic",
|
| 527 |
+
"neurowave_x2_development",
|
| 528 |
+
"neurowave_x2_enabled",
|
| 529 |
+
"neurowave_x2_phase",
|
| 530 |
+
"neurowave_x2_plasticity",
|
| 531 |
+
"neuroweave_v1",
|
| 532 |
+
"neuroweave_v1.adaptive_conduction",
|
| 533 |
+
"neuroweave_v1.adaptive_routing",
|
| 534 |
+
"neuroweave_v1.affective_modulation",
|
| 535 |
+
"neuroweave_v1.associative_memory",
|
| 536 |
+
"neuroweave_v1.astrocyte_regulation",
|
| 537 |
+
"neuroweave_v1.axonal_branches",
|
| 538 |
+
"neuroweave_v1.context_attention",
|
| 539 |
+
"neuroweave_v1.counterfactual_prediction",
|
| 540 |
+
"neuroweave_v1.cross_modal_memory",
|
| 541 |
+
"neuroweave_v1.dendritic_compartments",
|
| 542 |
+
"neuroweave_v1.efference_self_model",
|
| 543 |
+
"neuroweave_v1.expert_routing",
|
| 544 |
+
"neuroweave_v1.extended_somas",
|
| 545 |
+
"neuroweave_v1.fast_weights",
|
| 546 |
+
"neuroweave_v1.flyhash_projection",
|
| 547 |
+
"neuroweave_v1.hierarchical_prediction",
|
| 548 |
+
"neuroweave_v1.hierarchical_temporal_memory",
|
| 549 |
+
"neuroweave_v1.homeostatic_governor",
|
| 550 |
+
"neuroweave_v1.membrane_dynamics",
|
| 551 |
+
"neuroweave_v1.memory_ecology",
|
| 552 |
+
"neuroweave_v1.meta_plasticity",
|
| 553 |
+
"neuroweave_v1.micro_collective",
|
| 554 |
+
"neuroweave_v1.multi_region_routing",
|
| 555 |
+
"neuroweave_v1.multi_soma",
|
| 556 |
+
"neuroweave_v1.multimodal_sensory",
|
| 557 |
+
"neuroweave_v1.neurogenesis",
|
| 558 |
+
"neuroweave_v1.neuromodulator_field",
|
| 559 |
+
"neuroweave_v1.predictive_coding",
|
| 560 |
+
"neuroweave_v1.predictive_ensemble",
|
| 561 |
+
"neuroweave_v1.predictive_replay",
|
| 562 |
+
"neuroweave_v1.q88_state",
|
| 563 |
+
"neuroweave_v1.quantised_synapses",
|
| 564 |
+
"neuroweave_v1.receptor_heterogeneity",
|
| 565 |
+
"neuroweave_v1.representation_fusion",
|
| 566 |
+
"neuroweave_v1.reward_plasticity",
|
| 567 |
+
"neuroweave_v1.sleep_consolidation",
|
| 568 |
+
"neuroweave_v1.sparse_code",
|
| 569 |
+
"neuroweave_v1.specialist_graft",
|
| 570 |
+
"neuroweave_v1.stdp",
|
| 571 |
+
"neuroweave_v1.structural_encoder",
|
| 572 |
+
"neuroweave_v1.structural_plasticity",
|
| 573 |
+
"neuroweave_v1.synaptic_delays",
|
| 574 |
+
"neuroweave_v1.tiled_execution",
|
| 575 |
+
"neuroweave_v1.transmitter_inference",
|
| 576 |
+
"neuroweave_v1.uncertainty_gating",
|
| 577 |
+
"oscillatory_coherence",
|
| 578 |
+
"overflow_mini_brain",
|
| 579 |
+
"programmed_connectome",
|
| 580 |
+
"quantum_kuramoto",
|
| 581 |
+
"relational_memory",
|
| 582 |
+
"selective_state_space",
|
| 583 |
+
"self_model",
|
| 584 |
+
"shared_knowledge",
|
| 585 |
+
"sleep_replay",
|
| 586 |
+
"spectral_reservoir",
|
| 587 |
+
"spiking_neuromorphic",
|
| 588 |
+
"structural_learning",
|
| 589 |
+
"surprise_memory",
|
| 590 |
+
"synthetic_glands",
|
| 591 |
+
"tether_coordinator",
|
| 592 |
+
"thermodynamics",
|
| 593 |
+
"transfer_entropy",
|
| 594 |
+
"value_guided_planning",
|
| 595 |
+
"verifiable_dpo",
|
| 596 |
+
"verifier_rsi",
|
| 597 |
+
"virtual_ecology_v2"
|
| 598 |
+
],
|
| 599 |
+
"schema": "sonapse-compatibility-manifest-v1",
|
| 600 |
+
"test_modules": [
|
| 601 |
+
"test_12000_neurons_and_multi_connectome_fusion.py",
|
| 602 |
+
"test_9000_neurons_and_backward_compatibility.py",
|
| 603 |
+
"test_active_training.py",
|
| 604 |
+
"test_adaptation_study.py",
|
| 605 |
+
"test_advanced_frontier_features.py",
|
| 606 |
+
"test_aether_graft_master_integration.py",
|
| 607 |
+
"test_agent.py",
|
| 608 |
+
"test_antigravity_contract_regressions.py",
|
| 609 |
+
"test_apical_reservoir_hyperbolic.py",
|
| 610 |
+
"test_astrocyte.py",
|
| 611 |
+
"test_auto_programmer.py",
|
| 612 |
+
"test_bioacoustic_soundscape_and_cross_coupling.py",
|
| 613 |
+
"test_capabilities.py",
|
| 614 |
+
"test_causal_circuit_evolution.py",
|
| 615 |
+
"test_causal_mediation.py",
|
| 616 |
+
"test_circuit_atlas.py",
|
| 617 |
+
"test_cli.py",
|
| 618 |
+
"test_cli_evidence_labels.py",
|
| 619 |
+
"test_complex_environments.py",
|
| 620 |
+
"test_compute_budget.py",
|
| 621 |
+
"test_connectome_assets.py",
|
| 622 |
+
"test_connectome_authenticity.py",
|
| 623 |
+
"test_connectome_compiler.py",
|
| 624 |
+
"test_continual_probe.py",
|
| 625 |
+
"test_controlled_study.py",
|
| 626 |
+
"test_cross_graft_master.py",
|
| 627 |
+
"test_curriculum.py",
|
| 628 |
+
"test_dales_law.py",
|
| 629 |
+
"test_darwinian_tournament_and_web_audio.py",
|
| 630 |
+
"test_deep_research_upgrades.py",
|
| 631 |
+
"test_dsag.py",
|
| 632 |
+
"test_efficiency.py",
|
| 633 |
+
"test_evidence_engine.py",
|
| 634 |
+
"test_evidence_sleep_regressions.py",
|
| 635 |
+
"test_experience.py",
|
| 636 |
+
"test_experience_integration.py",
|
| 637 |
+
"test_experience_planner.py",
|
| 638 |
+
"test_experience_workbench.py",
|
| 639 |
+
"test_flagship.py",
|
| 640 |
+
"test_frontier_v2_innovations.py",
|
| 641 |
+
"test_frontier_v4_innovations.py",
|
| 642 |
+
"test_genome.py",
|
| 643 |
+
"test_graft_bus_and_aether_bridge.py",
|
| 644 |
+
"test_hypernetwork.py",
|
| 645 |
+
"test_hypernetwork_trainer.py",
|
| 646 |
+
"test_imagination_and_symbolic.py",
|
| 647 |
+
"test_kai_supermix_nexus.py",
|
| 648 |
+
"test_learning.py",
|
| 649 |
+
"test_live_programming.py",
|
| 650 |
+
"test_live_training_integration.py",
|
| 651 |
+
"test_manifold_alignment.py",
|
| 652 |
+
"test_max_mode_memory.py",
|
| 653 |
+
"test_measured_evo_and_live_audio.py",
|
| 654 |
+
"test_memory_consolidation_and_shy.py",
|
| 655 |
+
"test_metabolic.py",
|
| 656 |
+
"test_metamorphic.py",
|
| 657 |
+
"test_motivation_and_adaptive.py",
|
| 658 |
+
"test_multi_connectome_scaling.py",
|
| 659 |
+
"test_multimodal_live_and_virtual_ecology.py",
|
| 660 |
+
"test_neural_graft.py",
|
| 661 |
+
"test_neural_pulses_and_graph_waves.py",
|
| 662 |
+
"test_neuroendocrine_affective.py",
|
| 663 |
+
"test_neurogenesis_ranking_equivalence.py",
|
| 664 |
+
"test_neuromodulation.py",
|
| 665 |
+
"test_neuron_count.py",
|
| 666 |
+
"test_neurowave_x2_ablations.py",
|
| 667 |
+
"test_neurowave_x2_checkpoint.py",
|
| 668 |
+
"test_neurowave_x2_hybrid_basis.py",
|
| 669 |
+
"test_neurowave_x2_optimizer_migration.py",
|
| 670 |
+
"test_neurowave_x2_packets.py",
|
| 671 |
+
"test_neurowave_x2_phase.py",
|
| 672 |
+
"test_neurowave_x2_promotion.py",
|
| 673 |
+
"test_neurowave_x2_reference.py",
|
| 674 |
+
"test_neurowave_x2_regression.py",
|
| 675 |
+
"test_neurowave_x2_replay.py",
|
| 676 |
+
"test_neurowave_x2_resources.py",
|
| 677 |
+
"test_neurowave_x2_selector.py",
|
| 678 |
+
"test_neurowave_x2_spectral.py",
|
| 679 |
+
"test_neurowave_x2_stress.py",
|
| 680 |
+
"test_neurowave_x2_topology.py",
|
| 681 |
+
"test_neurowave_x2_transaction.py",
|
| 682 |
+
"test_neurowave_x2_transport.py",
|
| 683 |
+
"test_neuroweave_cli.py",
|
| 684 |
+
"test_neuroweave_core.py",
|
| 685 |
+
"test_neuroweave_ecology.py",
|
| 686 |
+
"test_neuroweave_engine.py",
|
| 687 |
+
"test_neuroweave_hardware_package.py",
|
| 688 |
+
"test_neuroweave_integration.py",
|
| 689 |
+
"test_neuroweave_lab.py",
|
| 690 |
+
"test_neuroweave_micro_memory.py",
|
| 691 |
+
"test_neuroweave_modulation_sensory.py",
|
| 692 |
+
"test_neuroweave_prediction_packets.py",
|
| 693 |
+
"test_neuroweave_review_fixes.py",
|
| 694 |
+
"test_neuroweave_sequence_search.py",
|
| 695 |
+
"test_neuroweave_server.py",
|
| 696 |
+
"test_neuroweave_standalone.py",
|
| 697 |
+
"test_observatory.py",
|
| 698 |
+
"test_omnibus_mode.py",
|
| 699 |
+
"test_pac_waves_epigenetics_synesthesia.py",
|
| 700 |
+
"test_parallel_pretraining.py",
|
| 701 |
+
"test_patches.py",
|
| 702 |
+
"test_planner_review_regressions.py",
|
| 703 |
+
"test_planning_study.py",
|
| 704 |
+
"test_planning_workbench.py",
|
| 705 |
+
"test_portable_export.py",
|
| 706 |
+
"test_predictive_coding.py",
|
| 707 |
+
"test_recursive_learning.py",
|
| 708 |
+
"test_research_fabric_and_plasticity.py",
|
| 709 |
+
"test_reusable_skills.py",
|
| 710 |
+
"test_rsi.py",
|
| 711 |
+
"test_runtime.py",
|
| 712 |
+
"test_runtime_contracts.py",
|
| 713 |
+
"test_sail_upgrades.py",
|
| 714 |
+
"test_sancf_and_frontier_master.py",
|
| 715 |
+
"test_self_model_efference.py",
|
| 716 |
+
"test_server.py",
|
| 717 |
+
"test_server_lock_isolation.py",
|
| 718 |
+
"test_shared_knowledge_and_exchange.py",
|
| 719 |
+
"test_sleep_replay_and_dreams.py",
|
| 720 |
+
"test_spatial_and_memory.py",
|
| 721 |
+
"test_spectral.py",
|
| 722 |
+
"test_spiking.py",
|
| 723 |
+
"test_stateio.py",
|
| 724 |
+
"test_stdp_allostasis_reconsolidation.py",
|
| 725 |
+
"test_structural_plasticity.py",
|
| 726 |
+
"test_study_isolation_regressions.py",
|
| 727 |
+
"test_supermix_advancements.py",
|
| 728 |
+
"test_surprise_memory.py",
|
| 729 |
+
"test_tandem_max_and_innovations.py",
|
| 730 |
+
"test_training_jobs.py",
|
| 731 |
+
"test_transfer.py",
|
| 732 |
+
"test_transplantation.py",
|
| 733 |
+
"test_uncertainty_calibration.py",
|
| 734 |
+
"test_uncertainty_guard.py",
|
| 735 |
+
"test_virtual_ecology.py",
|
| 736 |
+
"test_vision_and_objects.py",
|
| 737 |
+
"test_workbench_canvas_and_features.py"
|
| 738 |
+
],
|
| 739 |
+
"web_dom_ids": [
|
| 740 |
+
"aether-graft-badge",
|
| 741 |
+
"aether-graft-canvas",
|
| 742 |
+
"aether-graft-hud",
|
| 743 |
+
"allostasis-enable-btn",
|
| 744 |
+
"apical-badge",
|
| 745 |
+
"apical-canvas",
|
| 746 |
+
"apical-hud",
|
| 747 |
+
"applypatch",
|
| 748 |
+
"archimedes-badge",
|
| 749 |
+
"archimedes-canvas",
|
| 750 |
+
"archimedes-hud",
|
| 751 |
+
"atlas",
|
| 752 |
+
"atlasresult",
|
| 753 |
+
"audio-cochlea-badge",
|
| 754 |
+
"audio-harmonic-btn",
|
| 755 |
+
"audio-live-toggle-btn",
|
| 756 |
+
"audio-mic-badge",
|
| 757 |
+
"audio-mic-btn",
|
| 758 |
+
"audio-status-badge",
|
| 759 |
+
"audio-toggle-btn",
|
| 760 |
+
"auditory-canvas",
|
| 761 |
+
"auditory-hud",
|
| 762 |
+
"autoprogram",
|
| 763 |
+
"autorepairresult",
|
| 764 |
+
"bcm-badge",
|
| 765 |
+
"bcm-hud",
|
| 766 |
+
"benchmark-badge",
|
| 767 |
+
"benchmark-hud",
|
| 768 |
+
"benchmark-suite-out",
|
| 769 |
+
"btn-causal-assay",
|
| 770 |
+
"btn-checkpoint-migration",
|
| 771 |
+
"btn-meta-plasticity",
|
| 772 |
+
"btn-neurowave-modes",
|
| 773 |
+
"btn-omnibus-run",
|
| 774 |
+
"btn-run-ablation",
|
| 775 |
+
"btn-run-benchmarks",
|
| 776 |
+
"btn-run-tool-arena",
|
| 777 |
+
"btn-sancf-bench",
|
| 778 |
+
"btn-tandem-max",
|
| 779 |
+
"btn-tandem-max-toolbar",
|
| 780 |
+
"capabilities",
|
| 781 |
+
"capname",
|
| 782 |
+
"cappayload",
|
| 783 |
+
"capresult",
|
| 784 |
+
"capschema",
|
| 785 |
+
"capsweepresult",
|
| 786 |
+
"carrier-badge",
|
| 787 |
+
"carrier-canvas",
|
| 788 |
+
"carrier-hud",
|
| 789 |
+
"catalog",
|
| 790 |
+
"causal-9arm-btn",
|
| 791 |
+
"causal-assay-out",
|
| 792 |
+
"causal-entropy-canvas",
|
| 793 |
+
"causal9armresult",
|
| 794 |
+
"chat-input",
|
| 795 |
+
"chat-send-btn",
|
| 796 |
+
"chat-stream",
|
| 797 |
+
"checkpointlist",
|
| 798 |
+
"checkpointname",
|
| 799 |
+
"checkpointresult",
|
| 800 |
+
"checkpoints",
|
| 801 |
+
"cognition-hud",
|
| 802 |
+
"config",
|
| 803 |
+
"config-max-preset",
|
| 804 |
+
"connection",
|
| 805 |
+
"controlled-study-btn",
|
| 806 |
+
"controlledstudyresult",
|
| 807 |
+
"criticality-badge",
|
| 808 |
+
"criticality-canvas",
|
| 809 |
+
"criticality-hud",
|
| 810 |
+
"criticality-vsa-btn",
|
| 811 |
+
"criticalityvsaresult",
|
| 812 |
+
"cross-graft-badge",
|
| 813 |
+
"cross-graft-canvas",
|
| 814 |
+
"cross-graft-hud",
|
| 815 |
+
"darwinian-badge",
|
| 816 |
+
"darwinian-cataclysm-btn",
|
| 817 |
+
"darwinian-run-btn",
|
| 818 |
+
"dendritic-badge",
|
| 819 |
+
"dendritic-canvas",
|
| 820 |
+
"dendritic-hud",
|
| 821 |
+
"description",
|
| 822 |
+
"diffusion-dpo",
|
| 823 |
+
"diffusiondporesult",
|
| 824 |
+
"dormant-badge",
|
| 825 |
+
"dormant-hud",
|
| 826 |
+
"dsag-badge",
|
| 827 |
+
"dsag-canvas",
|
| 828 |
+
"dsag-hud",
|
| 829 |
+
"dvgem-badge",
|
| 830 |
+
"dvgem-hud",
|
| 831 |
+
"dvgem-tether-btn",
|
| 832 |
+
"dvgemtetherresult",
|
| 833 |
+
"ecology-badge",
|
| 834 |
+
"ecology-canvas",
|
| 835 |
+
"ecology-evo-toggle-btn",
|
| 836 |
+
"ecology-hud",
|
| 837 |
+
"ecology-predator-btn",
|
| 838 |
+
"ecology-seed-btn",
|
| 839 |
+
"ecology-sleep-btn",
|
| 840 |
+
"ecology-transact-btn",
|
| 841 |
+
"edits",
|
| 842 |
+
"epigenetics-enable-btn",
|
| 843 |
+
"error",
|
| 844 |
+
"evaluatepatch",
|
| 845 |
+
"experience-algorithm",
|
| 846 |
+
"experience-apply",
|
| 847 |
+
"experience-details",
|
| 848 |
+
"experience-horizon",
|
| 849 |
+
"experience-mode",
|
| 850 |
+
"experience-preview",
|
| 851 |
+
"experience-summary",
|
| 852 |
+
"experience-value-guided",
|
| 853 |
+
"experiments",
|
| 854 |
+
"export-simulation",
|
| 855 |
+
"export-status",
|
| 856 |
+
"exportpatch",
|
| 857 |
+
"flagship",
|
| 858 |
+
"flagshipresult",
|
| 859 |
+
"gauges",
|
| 860 |
+
"glands-badge",
|
| 861 |
+
"glands-canvas",
|
| 862 |
+
"glands-hud",
|
| 863 |
+
"glymphatic-badge",
|
| 864 |
+
"glymphatic-canvas",
|
| 865 |
+
"glymphatic-hud",
|
| 866 |
+
"graph",
|
| 867 |
+
"graph-activity",
|
| 868 |
+
"graph-autorotate",
|
| 869 |
+
"graph-camera-reset",
|
| 870 |
+
"graph-cluster-halos",
|
| 871 |
+
"graph-edges",
|
| 872 |
+
"graph-grafts",
|
| 873 |
+
"graph-legend",
|
| 874 |
+
"graph-neurowave",
|
| 875 |
+
"graph-nodes",
|
| 876 |
+
"graph-role",
|
| 877 |
+
"graph-selection",
|
| 878 |
+
"graph-source",
|
| 879 |
+
"graph-streamlines",
|
| 880 |
+
"graph-summary",
|
| 881 |
+
"graph-tooltip",
|
| 882 |
+
"graph-view-2d",
|
| 883 |
+
"graph-view-3d",
|
| 884 |
+
"hyperapply",
|
| 885 |
+
"hyperbolic-badge",
|
| 886 |
+
"hyperbolic-canvas",
|
| 887 |
+
"hyperbolic-hud",
|
| 888 |
+
"hyperprogram",
|
| 889 |
+
"hyperresult",
|
| 890 |
+
"importpatch",
|
| 891 |
+
"invoke",
|
| 892 |
+
"jobs",
|
| 893 |
+
"kuramoto-badge",
|
| 894 |
+
"kuramoto-canvas",
|
| 895 |
+
"kuramoto-hud",
|
| 896 |
+
"learn",
|
| 897 |
+
"learning-contract",
|
| 898 |
+
"lineage",
|
| 899 |
+
"load",
|
| 900 |
+
"makepatch",
|
| 901 |
+
"manifold",
|
| 902 |
+
"manifoldresult",
|
| 903 |
+
"metamorphic",
|
| 904 |
+
"metamorphicresult",
|
| 905 |
+
"metrics",
|
| 906 |
+
"mimomix-badge",
|
| 907 |
+
"neuroplasticity-result",
|
| 908 |
+
"neurowave-badge",
|
| 909 |
+
"neurowave-canvas",
|
| 910 |
+
"neurowave-hud",
|
| 911 |
+
"neuroweave",
|
| 912 |
+
"nwl-affect",
|
| 913 |
+
"nwl-auto",
|
| 914 |
+
"nwl-axon",
|
| 915 |
+
"nwl-channels",
|
| 916 |
+
"nwl-conn-canvas",
|
| 917 |
+
"nwl-controls",
|
| 918 |
+
"nwl-eco-canvas",
|
| 919 |
+
"nwl-eco-config",
|
| 920 |
+
"nwl-eco-refresh",
|
| 921 |
+
"nwl-eco-run",
|
| 922 |
+
"nwl-eco-steps",
|
| 923 |
+
"nwl-eco-summary",
|
| 924 |
+
"nwl-exp-background",
|
| 925 |
+
"nwl-exp-quick",
|
| 926 |
+
"nwl-exp-run",
|
| 927 |
+
"nwl-exp-seeds",
|
| 928 |
+
"nwl-exp-select",
|
| 929 |
+
"nwl-exp-status",
|
| 930 |
+
"nwl-exp-steps",
|
| 931 |
+
"nwl-expert-load",
|
| 932 |
+
"nwl-export-csv",
|
| 933 |
+
"nwl-export-fpga",
|
| 934 |
+
"nwl-export-html",
|
| 935 |
+
"nwl-export-json",
|
| 936 |
+
"nwl-export-package",
|
| 937 |
+
"nwl-export-source",
|
| 938 |
+
"nwl-external-channel",
|
| 939 |
+
"nwl-external-send",
|
| 940 |
+
"nwl-external-value",
|
| 941 |
+
"nwl-import-file",
|
| 942 |
+
"nwl-inspect-out",
|
| 943 |
+
"nwl-lab-out",
|
| 944 |
+
"nwl-ledger-body",
|
| 945 |
+
"nwl-ledger-refresh",
|
| 946 |
+
"nwl-ledger-summary",
|
| 947 |
+
"nwl-lesion-run",
|
| 948 |
+
"nwl-loss",
|
| 949 |
+
"nwl-mech-apply",
|
| 950 |
+
"nwl-mech-list",
|
| 951 |
+
"nwl-mech-none",
|
| 952 |
+
"nwl-mic-start",
|
| 953 |
+
"nwl-mic-stop",
|
| 954 |
+
"nwl-modes-apply",
|
| 955 |
+
"nwl-modulators",
|
| 956 |
+
"nwl-panel-environment",
|
| 957 |
+
"nwl-panel-lab",
|
| 958 |
+
"nwl-panel-learning",
|
| 959 |
+
"nwl-panel-neural",
|
| 960 |
+
"nwl-panel-neuromod",
|
| 961 |
+
"nwl-panel-sensory",
|
| 962 |
+
"nwl-panel-studio",
|
| 963 |
+
"nwl-plasticity",
|
| 964 |
+
"nwl-receptors",
|
| 965 |
+
"nwl-refresh",
|
| 966 |
+
"nwl-region-bars",
|
| 967 |
+
"nwl-results-body",
|
| 968 |
+
"nwl-sensory-out",
|
| 969 |
+
"nwl-sensory-pe",
|
| 970 |
+
"nwl-sensory-status",
|
| 971 |
+
"nwl-sequence-body",
|
| 972 |
+
"nwl-sequence-details",
|
| 973 |
+
"nwl-sequence-run",
|
| 974 |
+
"nwl-sequence-status",
|
| 975 |
+
"nwl-soma",
|
| 976 |
+
"nwl-source",
|
| 977 |
+
"nwl-status",
|
| 978 |
+
"nwl-step-count",
|
| 979 |
+
"nwl-step-run",
|
| 980 |
+
"nwl-studio-status",
|
| 981 |
+
"nwl-topology-run",
|
| 982 |
+
"nwl-webcam-start",
|
| 983 |
+
"nwl-webcam-stop",
|
| 984 |
+
"nwl-webcam-video",
|
| 985 |
+
"omnibus-badge",
|
| 986 |
+
"omnibus-hud",
|
| 987 |
+
"oscillatory-badge",
|
| 988 |
+
"oscillatory-canvas",
|
| 989 |
+
"oscillatory-hud",
|
| 990 |
+
"overflow-badge",
|
| 991 |
+
"overflow-hud",
|
| 992 |
+
"overview",
|
| 993 |
+
"pac-badge",
|
| 994 |
+
"pac-enable-btn",
|
| 995 |
+
"pac-synesthesia-hud",
|
| 996 |
+
"pac-waves-canvas",
|
| 997 |
+
"packet",
|
| 998 |
+
"patches",
|
| 999 |
+
"patchresult",
|
| 1000 |
+
"pause",
|
| 1001 |
+
"plan-actions",
|
| 1002 |
+
"plan-candidates",
|
| 1003 |
+
"plan-details",
|
| 1004 |
+
"plan-preview",
|
| 1005 |
+
"plan-reason",
|
| 1006 |
+
"plan-step",
|
| 1007 |
+
"planning-receipt-load",
|
| 1008 |
+
"planning-receipt-name",
|
| 1009 |
+
"planning-receipt-result",
|
| 1010 |
+
"planning-receipt-status",
|
| 1011 |
+
"plasticity-badge",
|
| 1012 |
+
"plasticity-hud",
|
| 1013 |
+
"predictive",
|
| 1014 |
+
"previewpatch",
|
| 1015 |
+
"pulses-badge",
|
| 1016 |
+
"pulses-canvas",
|
| 1017 |
+
"pulses-hud",
|
| 1018 |
+
"quicktask",
|
| 1019 |
+
"reconsolidation-reactivate-btn",
|
| 1020 |
+
"refreshcheckpoints",
|
| 1021 |
+
"reservoir-badge",
|
| 1022 |
+
"reservoir-canvas",
|
| 1023 |
+
"reservoir-hud",
|
| 1024 |
+
"rollback",
|
| 1025 |
+
"rsi-live",
|
| 1026 |
+
"rsi-receipt",
|
| 1027 |
+
"rsi-status",
|
| 1028 |
+
"run",
|
| 1029 |
+
"runstatus",
|
| 1030 |
+
"sancf-badge",
|
| 1031 |
+
"sancf-bench-out",
|
| 1032 |
+
"sancf-hud",
|
| 1033 |
+
"save",
|
| 1034 |
+
"search",
|
| 1035 |
+
"self-model-badge",
|
| 1036 |
+
"self-model-hud",
|
| 1037 |
+
"signals",
|
| 1038 |
+
"simspeed",
|
| 1039 |
+
"simsteps",
|
| 1040 |
+
"skills-refresh",
|
| 1041 |
+
"skills-result",
|
| 1042 |
+
"sleep-badge",
|
| 1043 |
+
"sleep-canvas",
|
| 1044 |
+
"sleep-hud",
|
| 1045 |
+
"snapshot",
|
| 1046 |
+
"soundscape-badge",
|
| 1047 |
+
"soundscape-canvas",
|
| 1048 |
+
"soundscape-cross-couple-btn",
|
| 1049 |
+
"soundscape-forager-call-btn",
|
| 1050 |
+
"soundscape-hud",
|
| 1051 |
+
"soundscape-sentinel-alarm-btn",
|
| 1052 |
+
"source-details",
|
| 1053 |
+
"source-inventory",
|
| 1054 |
+
"speciation-canvas",
|
| 1055 |
+
"speciation-hud",
|
| 1056 |
+
"spectral",
|
| 1057 |
+
"spectralresult",
|
| 1058 |
+
"spiking-badge",
|
| 1059 |
+
"spiking-canvas",
|
| 1060 |
+
"spiking-hud",
|
| 1061 |
+
"startstudy",
|
| 1062 |
+
"stdp-allostasis-canvas",
|
| 1063 |
+
"stdp-allostasis-hud",
|
| 1064 |
+
"stdp-badge",
|
| 1065 |
+
"stdp-enable-btn",
|
| 1066 |
+
"step",
|
| 1067 |
+
"studyconfig",
|
| 1068 |
+
"studyresult",
|
| 1069 |
+
"surfaces",
|
| 1070 |
+
"sweep-capabilities",
|
| 1071 |
+
"synesthesia-burst-btn",
|
| 1072 |
+
"tandem-banner",
|
| 1073 |
+
"tandem-receipt-out",
|
| 1074 |
+
"tandem-section-pills",
|
| 1075 |
+
"tandem-status-pill",
|
| 1076 |
+
"tandem-summary",
|
| 1077 |
+
"task-aware-route",
|
| 1078 |
+
"task-aware-status",
|
| 1079 |
+
"task-aware-support",
|
| 1080 |
+
"te-badge",
|
| 1081 |
+
"te-hud",
|
| 1082 |
+
"telemetry",
|
| 1083 |
+
"teleop-arm",
|
| 1084 |
+
"teleop-fwd",
|
| 1085 |
+
"teleop-grip",
|
| 1086 |
+
"teleop-left",
|
| 1087 |
+
"teleop-right",
|
| 1088 |
+
"tensors",
|
| 1089 |
+
"tether-badge",
|
| 1090 |
+
"tether-hud",
|
| 1091 |
+
"thermo-badge",
|
| 1092 |
+
"thermo-hud",
|
| 1093 |
+
"thrust-governor",
|
| 1094 |
+
"title",
|
| 1095 |
+
"tool-arena-out",
|
| 1096 |
+
"train",
|
| 1097 |
+
"training-active",
|
| 1098 |
+
"training-apply",
|
| 1099 |
+
"training-badge",
|
| 1100 |
+
"training-batch",
|
| 1101 |
+
"training-cancel",
|
| 1102 |
+
"training-compute",
|
| 1103 |
+
"training-intensive",
|
| 1104 |
+
"training-job-progress",
|
| 1105 |
+
"training-job-status",
|
| 1106 |
+
"training-metrics",
|
| 1107 |
+
"training-pretrain",
|
| 1108 |
+
"training-prior",
|
| 1109 |
+
"training-receipt",
|
| 1110 |
+
"training-threads",
|
| 1111 |
+
"training-workers",
|
| 1112 |
+
"transplant",
|
| 1113 |
+
"transplantresult",
|
| 1114 |
+
"trigger-threat-btn",
|
| 1115 |
+
"uncertainty-badge",
|
| 1116 |
+
"uncertainty-hud",
|
| 1117 |
+
"vitals-hud",
|
| 1118 |
+
"vsa-badge",
|
| 1119 |
+
"vsa-canvas",
|
| 1120 |
+
"vsa-hud",
|
| 1121 |
+
"world",
|
| 1122 |
+
"world-clear-trail",
|
| 1123 |
+
"world-goals",
|
| 1124 |
+
"world-legend",
|
| 1125 |
+
"world-retina-cam",
|
| 1126 |
+
"world-summary",
|
| 1127 |
+
"world-terrain-mesh",
|
| 1128 |
+
"world-tooltip",
|
| 1129 |
+
"world-trails",
|
| 1130 |
+
"world-view-iso",
|
| 1131 |
+
"world-view-top",
|
| 1132 |
+
"world-wind-streamlines",
|
| 1133 |
+
"world4d-badge",
|
| 1134 |
+
"world4d-hud",
|
| 1135 |
+
"worldtask",
|
| 1136 |
+
"wpac-badge",
|
| 1137 |
+
"wpac-canvas",
|
| 1138 |
+
"wpac-hud"
|
| 1139 |
+
]
|
| 1140 |
+
}
|
docs/frontier/CONTRACT.md
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Frontier pack: module contract (v1)
|
| 2 |
+
|
| 3 |
+
The frontier pack (`synapse/frontier/`) adds experimental modules inspired by
|
| 4 |
+
2024–2026 research and by sibling `kai9987kai` projects. This contract fixes the
|
| 5 |
+
rules every module follows so the pack stays additive, testable and honest.
|
| 6 |
+
|
| 7 |
+
Read with: `synapse/frontier/spec.py` (module registry and `FrontierSpecV1`),
|
| 8 |
+
`synapse/frontier/extension.py` (engine-extension interface v1) and
|
| 9 |
+
`synapse/frontier/harness.py` (shared experiment harness).
|
| 10 |
+
|
| 11 |
+
## Non-negotiable rules
|
| 12 |
+
|
| 13 |
+
1. **Additive and default-off.** No existing Sonapse or NEUROWEAVE default,
|
| 14 |
+
API, route, DOM id, CLI flag, checkpoint format or test changes behaviour.
|
| 15 |
+
`scripts/neuroweave_compat_manifest.py --check` keeps passing.
|
| 16 |
+
2. **Live observers are read-only.** An observer receives a *copy* of activity
|
| 17 |
+
and never writes into the brain, graft bus, actor or any shared RNG.
|
| 18 |
+
3. **Influence only by explicit attachment.** A module may change computation
|
| 19 |
+
only as an extension attached to a NEUROWEAVE engine (lab experiments), as a
|
| 20 |
+
standalone model in its own experiment, or through an explicitly selected
|
| 21 |
+
opt-in option.
|
| 22 |
+
4. **Deterministic.** All randomness from `numpy.random.default_rng(seed + offset)`
|
| 23 |
+
or a seeded `torch.Generator`; never the global RNGs. Torch code sets
|
| 24 |
+
`torch.manual_seed` only inside its own local generator usage and must not
|
| 25 |
+
change global torch state (use `torch.Generator` objects; restore
|
| 26 |
+
`torch.get_num_threads()` if changed).
|
| 27 |
+
5. **Bounded and finite.** Every buffer has a fixed maximum size; every state
|
| 28 |
+
value is finite; inputs are validated (`ValueError` on bad input) before any
|
| 29 |
+
state changes. `import_state` validates fully before mutating.
|
| 30 |
+
6. **Honest evidence.** Receipts carry `evidence_tier: 'synthetic_abstraction'`.
|
| 31 |
+
Module titles name the idea a module is *inspired by*; never claim to
|
| 32 |
+
reproduce a paper's results, biological validity, consciousness, emotion,
|
| 33 |
+
or measured hardware performance. Every citation is verified (title,
|
| 34 |
+
authors, venue, month/year, URL) before it is written down.
|
| 35 |
+
7. **Dependencies.** NumPy, SciPy and PyTorch only (already required). Any
|
| 36 |
+
other package (for example `nir`) is optional: import lazily, degrade
|
| 37 |
+
gracefully, and test the fallback.
|
| 38 |
+
|
| 39 |
+
## Module file API
|
| 40 |
+
|
| 41 |
+
Each module lives in `synapse/frontier/<file>.py` and exposes:
|
| 42 |
+
|
| 43 |
+
- `MODULE_ID: str` — the id from `spec.MODULE_IDS`.
|
| 44 |
+
- `run_experiment(*, quick: bool = False, seeds=(0, 1, 2), **overrides) -> dict`
|
| 45 |
+
returning a **sealed frontier receipt** (see below). `quick=True` must finish
|
| 46 |
+
in under ~20 s on one CPU thread; the default size should finish in a few
|
| 47 |
+
minutes at most.
|
| 48 |
+
- `EXPERIMENTS: dict[str, Callable[..., dict]]` mapping every experiment id the
|
| 49 |
+
module provides to its runner (same signature as `run_experiment`). The first
|
| 50 |
+
entry is `MODULE_ID: run_experiment`; extra ids start with `MODULE_ID + '_'`.
|
| 51 |
+
The frontier lab registry is built from these dictionaries.
|
| 52 |
+
- Observer modules (`spec.OBSERVER_MODULE_IDS`) also expose an observer class:
|
| 53 |
+
`__init__(self, n_units: int, *, seed: int = 7, history: int = 256, **params)`,
|
| 54 |
+
`observe(self, x: np.ndarray) -> None` (1-D, length `n_units`, finite),
|
| 55 |
+
`summary(self) -> dict` (JSON-safe, at most ~16 KB, no wall-clock),
|
| 56 |
+
`reset()`, `export_state() -> dict`, `import_state(state) -> None`.
|
| 57 |
+
Observer parameters come from `FrontierSpecV1` (`history`, `sync_pairs`,
|
| 58 |
+
`sae_features`, `sae_k`, `fc_window`).
|
| 59 |
+
- Engine extensions subclass `extension.EngineExtension` and follow its rules
|
| 60 |
+
(no engine reference kept, deep-copyable, frozen when `ctx['learn']` is false).
|
| 61 |
+
|
| 62 |
+
## Receipts and verdicts
|
| 63 |
+
|
| 64 |
+
Build receipts with `harness.base_receipt(experiment_id, kind, config)`, add
|
| 65 |
+
fields, and finish with `harness.seal(receipt)` (adds the SHA-256 digest; keys
|
| 66 |
+
containing `wallclock` are excluded from the digest).
|
| 67 |
+
|
| 68 |
+
- **Comparison experiments** (`kind` other than `validation`) set
|
| 69 |
+
`verdict` in `('improved', 'no_detectable_difference', 'worse')` using
|
| 70 |
+
`harness.compare` (paired 95 % t interval over seeds; `improved` only when
|
| 71 |
+
the interval excludes zero) and, when the candidate adds capacity,
|
| 72 |
+
`harness.headline_verdict` against a capacity-matched control. Report the
|
| 73 |
+
basis in `verdict_basis`. Never declare `improved` from complexity alone.
|
| 74 |
+
- **Validation experiments** (`kind: 'validation'`, e.g. interchange export,
|
| 75 |
+
biophysical reference, statistical coverage checks) set `verdict` in
|
| 76 |
+
`('pass', 'fail')` with an explicit `checks` mapping of named booleans.
|
| 77 |
+
- Always include: `config` (enough to reproduce), parameter/state budgets where
|
| 78 |
+
models are compared, `estimated_*` cost fields kept apart from
|
| 79 |
+
`measured_wallclock_s`, and `notes` stating limits.
|
| 80 |
+
|
| 81 |
+
## Tests
|
| 82 |
+
|
| 83 |
+
One test file per implementation group, `tests/test_frontier_<group>.py`, fast
|
| 84 |
+
(tiny sizes; well under a minute in total per file), covering: determinism
|
| 85 |
+
(same seed ⇒ same digest), bounds and finiteness, validation errors, state
|
| 86 |
+
round-trips, the module's core behaviour on a case with a known answer, and
|
| 87 |
+
`run_experiment(quick=True)` producing a sealed, verifiable receipt.
|
| 88 |
+
|
| 89 |
+
## Documentation
|
| 90 |
+
|
| 91 |
+
Each module gets `docs/frontier/modules/<module_id>.md`: what it does (with the
|
| 92 |
+
key equations), the verified source citation(s), what is implemented and what is
|
| 93 |
+
not, how it connects to Sonapse, and the measured quick-mode result with its
|
| 94 |
+
date and settings. No claim without a test or a recorded measurement.
|
docs/frontier/README.md
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Sonapse Frontier Pack (`synapse/frontier/`)
|
| 2 |
+
|
| 3 |
+
The **Frontier Pack** is an additive, default-off collection of experimental computational neuroscience, machine
|
| 4 |
+
learning, and methodology modules inspired by 2024–2026 research literature and by sibling `kai9987kai` repositories.
|
| 5 |
+
|
| 6 |
+
Every module follows the contract in [`CONTRACT.md`](CONTRACT.md) and carries full verified bibliography and portfolio
|
| 7 |
+
provenance in [`REFERENCES.md`](REFERENCES.md):
|
| 8 |
+
|
| 9 |
+
1. **Additive and default-off.** `SynapseConfig().frontier` defaults to `None` and is omitted from `to_dict()`.
|
| 10 |
+
No existing Sonapse or NEUROWEAVE default, route, DOM id, CLI flag, or checkpoint changes behaviour.
|
| 11 |
+
2. **Read-only live observers.** Modules marked `observer=True` can observe a deterministic unit subsample of live
|
| 12 |
+
brain activity (`FrontierObserverHub` in `synapse/frontier/runtime.py`) without ever writing back into the brain,
|
| 13 |
+
graft bus, actor, or shared RNGs.
|
| 14 |
+
3. **Capacity-matched experimental harness.** Comparison experiments run through `synapse/frontier/harness.py`,
|
| 15 |
+
reporting paired differences over seeds with a two-sided 95 % t confidence interval against both an unmodified
|
| 16 |
+
baseline and (whenever capacity is added) a capacity-matched control, sealed with a wall-clock-independent SHA-256
|
| 17 |
+
digest (`FrontierLabReceiptV1`, `evidence_tier: 'synthetic_abstraction'`).
|
| 18 |
+
|
| 19 |
+
---
|
| 20 |
+
|
| 21 |
+
## Module Catalog (`synapse/frontier/spec.py`)
|
| 22 |
+
|
| 23 |
+
| Module ID | File | Kind | Live Observer | Engine Extension | Inspiration / Source | Documentation |
|
| 24 |
+
|---|---|---|---|---|---|---|
|
| 25 |
+
| `synchrony` | `synchrony.py` | `extension` | `SynchronyObserver` | `SynchronyExtension`, `NeuronLevelExtension` | Continuous Thought Machines (Darlow et al., NeurIPS 2025) | [`modules/synchrony.md`](modules/synchrony.md) |
|
| 26 |
+
| `continuum_memory` | `continuum_memory.py` | `extension` | — | `ContinuumMemoryExtension` | Nested Learning / HOPE & Titans (Behrouz et al., NeurIPS 2025) | [`modules/continuum_memory.md`](modules/continuum_memory.md) |
|
| 27 |
+
| `btsp_memory` | `btsp.py` | `extension` | — | `BTSPExtension` | One-shot binary-synapse BTSP (Wu & Maass, *Nat. Commun.* 2025) | [`modules/btsp_memory.md`](modules/btsp_memory.md) |
|
| 28 |
+
| `kuramoto_binding` | `kuramoto.py` | `extension` | `KuramotoObserver` | `KuramotoExtension` | Artificial Kuramoto Oscillatory Neurons (Miyato et al., ICLR 2025) | [`modules/kuramoto_binding.md`](modules/kuramoto_binding.md) |
|
| 29 |
+
| `recursive_refiner` | `recursive_refiner.py` | `model` | — | — | Tiny Recursive Model (Jolicoeur-Martineau, 2025); HRM (Wang et al., 2025) | [`modules/recursive_refiner.md`](modules/recursive_refiner.md) |
|
| 30 |
+
| `dendritic_layer` | `dendritic.py` | `model` | — | — | Structured dendritic ANNs (Chavlis & Poirazi, *Nat. Commun.* 2025) | [`modules/dendritic_layer.md`](modules/dendritic_layer.md) |
|
| 31 |
+
| `muon_optimizer` | `muon.py` | `tool` | — | — | Muon orthogonalised-momentum optimiser (Jordan et al., 2024; Liu et al., 2025) | [`modules/muon_optimizer.md`](modules/muon_optimizer.md) |
|
| 32 |
+
| `rigl_sparse` | `rigl.py` | `tool` | — | — | RigL dynamic sparse training (Evci et al., ICML 2020) & `sonapse-evo` | [`modules/rigl_sparse.md`](modules/rigl_sparse.md) |
|
| 33 |
+
| `sparse_dictionary` | `sparse_dictionary.py` | `analysis` | `SparseDictionaryObserver` | — | TopK sparse autoencoders with AuxK & causal ablation (Gao et al., ICLR 2025) | [`modules/sparse_dictionary.md`](modules/sparse_dictionary.md) |
|
| 34 |
+
| `anytime_inference` | `anytime.py` | `methodology` | — | — | Betting confidence sequences & e-processes (Waudby-Smith & Ramdas, 2024; Ramdas et al., 2023) | [`modules/anytime_inference.md`](modules/anytime_inference.md) |
|
| 35 |
+
| `quality_diversity` | `quality_diversity.py` | `discovery` | — | — | Verifier-gated MAP-Elites & DGM parent selection (`SONAPSE-ORIGIN`, `sonapse-evo`; Mouret & Clune, 2015; Zhang et al., 2025) | [`modules/quality_diversity.md`](modules/quality_diversity.md) |
|
| 36 |
+
| `connectomics` | `connectomics.py` | `analysis` | `ConnectivityObserver` | — | Structural, functional, dynamic-FC, and ridge-VAR(1) effective connectivity (`SONAPSE-CONNECTOME`) | [`modules/connectomics.md`](modules/connectomics.md) |
|
| 37 |
+
| `causal_emergence` | `causal_emergence.py` | `analysis` | `CausalEmergenceObserver` | — | Effective information & macro-vs-micro causal emergence (`GhostInTheMachine`, `SONAPSE-ORIGIN`; Hoel et al., 2013) | [`modules/causal_emergence.md`](modules/causal_emergence.md) |
|
| 38 |
+
| `hh_cable` | `hh_cable.py` | `reference` | — | — | Multi-compartment Hodgkin–Huxley cable reference (`NeuroPulse-CableLab`; Hodgkin & Huxley, 1952) | [`modules/hh_cable.md`](modules/hh_cable.md) |
|
| 39 |
+
| `nir_export` | `nir_export.py` | `tool` | — | — | Neuromorphic Intermediate Representation export (Pedersen et al., *Nat. Commun.* 2024) | [`modules/nir_export.md`](modules/nir_export.md) |
|
| 40 |
+
| `joint_failure` | `joint_failure.py` | `methodology` | — | — | Condition-indexed joint-failure voting panel selection (`FAULTLINE`) | [`modules/joint_failure.md`](modules/joint_failure.md) |
|
| 41 |
+
| `experiment_design` | `experiment_design.py` | `methodology` | — | — | Decision-sensitive Bayes-risk acquisition (`COUNTERFORM`, `Mnemorph`; Lindley, 1956; Chaloner & Verdinelli, 1995) | [`modules/experiment_design.md`](modules/experiment_design.md) |
|
| 42 |
+
| `morphogenesis` | `morphogenesis.py` | `discovery` | — | — | Single-organizer connectome growth & pattern-memory regeneration (`morpheus`, `prometheus-alpha`, `GenesisEngine`, `MOLT`; Mordvintsev et al., 2020; Pezzulo & Levin, 2015) | [`modules/morphogenesis.md`](modules/morphogenesis.md) |
|
| 43 |
+
|
| 44 |
+
---
|
| 45 |
+
|
| 46 |
+
## Integration Surfaces
|
| 47 |
+
|
| 48 |
+
* **Config (`synapse/config.py`):** `SynapseConfig(frontier=FrontierSpecV1.max_preset())` (default `None`, omitted from `to_dict()`).
|
| 49 |
+
* **Live Runtime (`synapse/frontier/runtime.py`, `synapse/frontier/bridge.py`):** `FrontierObserverHub` attaches to `IntegratedAgent.frontier_hub`, steps read-only after each `act()` call, persists under `state['frontier_v1']`, and optionally enables `MuonWithAuxAdam` for `NeuralResidualGraft` (`graft_optimizer='muon'`).
|
| 50 |
+
* **CLI (`synapse/frontier/cli_commands.py`):** global `--frontier`, `--no-frontier`, `--frontier-config`, `--frontier-modules`, `--frontier-graft-optimizer`, and `python -m synapse.cli frontier {catalog,experiment,observe,laboratory}`.
|
| 51 |
+
* **Workbench HTTP API (`synapse/frontier/workbench_api.py`):** `GET /api/frontier/{catalog,status,observers,observers/lab}` and `POST /api/frontier/{configure,step,experiment}`.
|
| 52 |
+
* **Max Mode (`synapse/tandem_max.py`):** `SynapseConfig.max_tandem(...)` enables read-only `FrontierSpecV1.max_preset(seed=seed)` and records additive `section_07` (`Frontier Pack Laboratory`) in the Max Mode receipt.
|
docs/frontier/REFERENCES.md
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Frontier Pack: Verified References & Portfolio Provenance
|
| 2 |
+
|
| 3 |
+
Every module in `synapse/frontier/` is a synthetic computational abstraction (`evidence_tier: 'synthetic_abstraction'`).
|
| 4 |
+
Module titles and docstrings name the research papers or sibling `kai9987kai` projects that inspired each mechanism;
|
| 5 |
+
they do not claim to reproduce published results or biological systems.
|
| 6 |
+
|
| 7 |
+
All bibliographic details below (title, authors, venue, publication/preprint month & year, and URL/DOI) were verified
|
| 8 |
+
against publisher, arXiv, Project Euclid, PMC, or Crossref metadata on 2026-11-17 through 2026-11-19.
|
| 9 |
+
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
## 1. Literature References (by Module)
|
| 13 |
+
|
| 14 |
+
### `synchrony` (`synapse/frontier/synchrony.py`)
|
| 15 |
+
|
| 16 |
+
* Luke Darlow, Ciaran Regan, Sebastian Risi, Jeffrey Seely, and Llion Jones (Sakana AI).
|
| 17 |
+
**Continuous Thought Machines.** *Advances in Neural Information Processing Systems (NeurIPS) 2025* (Spotlight).
|
| 18 |
+
Preprint: arXiv:2505.05522 (v1 8 May 2025; v4 3 October 2025), <https://arxiv.org/abs/2505.05522>.
|
| 19 |
+
Reference code: <https://github.com/SakanaAI/continuous-thought-machines>.
|
| 20 |
+
|
| 21 |
+
### `continuum_memory` (`synapse/frontier/continuum_memory.py`)
|
| 22 |
+
|
| 23 |
+
* Ali Behrouz, Meisam Razaviyayn, Peilin Zhong, and Vahab Mirrokni.
|
| 24 |
+
**Nested Learning: The Illusion of Deep Learning Architectures.** *Advances in Neural Information Processing Systems (NeurIPS) 2025*.
|
| 25 |
+
Preprint: arXiv:2512.24695 (December 2025), <https://arxiv.org/abs/2512.24695>.
|
| 26 |
+
* Ali Behrouz, Peilin Zhong, and Vahab Mirrokni.
|
| 27 |
+
**Titans: Learning to Memorize at Test Time.** *Advances in Neural Information Processing Systems (NeurIPS) 2025*.
|
| 28 |
+
Preprint: arXiv:2501.00663 (31 December 2024), <https://arxiv.org/abs/2501.00663>.
|
| 29 |
+
|
| 30 |
+
### `btsp_memory` (`synapse/frontier/btsp.py`)
|
| 31 |
+
|
| 32 |
+
* Yujie Wu and Wolfgang Maass.
|
| 33 |
+
**A simple model for Behavioral Time Scale Synaptic Plasticity (BTSP) provides content addressable memory with binary synapses and one-shot learning.**
|
| 34 |
+
*Nature Communications* 16, 342 (published online 2 January 2025).
|
| 35 |
+
DOI [10.1038/s41467-024-55563-6](https://doi.org/10.1038/s41467-024-55563-6).
|
| 36 |
+
* David J. Willshaw, O. Peter Buneman, and Hugh C. Longuet-Higgins.
|
| 37 |
+
**Non-Holographic Associative Memory.** *Nature* 222(5197), 960–962 (7 June 1969).
|
| 38 |
+
DOI [10.1038/222960a0](https://doi.org/10.1038/222960a0).
|
| 39 |
+
|
| 40 |
+
### `kuramoto_binding` (`synapse/frontier/kuramoto.py`)
|
| 41 |
+
|
| 42 |
+
* Takeru Miyato, Sindy Löwe, Andreas Geiger, and Max Welling.
|
| 43 |
+
**Artificial Kuramoto Oscillatory Neurons.** *International Conference on Learning Representations (ICLR) 2025* (Oral, April 2025).
|
| 44 |
+
Preprint: arXiv:2410.13821 (v1 17 October 2024; v3 16 May 2025), <https://arxiv.org/abs/2410.13821>.
|
| 45 |
+
* Murray Shanahan.
|
| 46 |
+
**Metastable chimera states in community-structured oscillator networks.** *Chaos* 20(1), 013108 (March 2010; published online 22 February 2010).
|
| 47 |
+
DOI [10.1063/1.3305451](https://doi.org/10.1063/1.3305451); arXiv:0908.3881.
|
| 48 |
+
|
| 49 |
+
### `recursive_refiner` (`synapse/frontier/recursive_refiner.py`)
|
| 50 |
+
|
| 51 |
+
* Alexia Jolicoeur-Martineau.
|
| 52 |
+
**Less is More: Recursive Reasoning with Tiny Networks.**
|
| 53 |
+
Preprint: arXiv:2510.04871 (October 2025), <https://arxiv.org/abs/2510.04871>.
|
| 54 |
+
* Guan Wang, Jin Li, Yuhao Sun, Xing Chen, Changling Liu, Yue Wu, Meng Lu, Sen Song, and Yasin Abbasi Yadkori.
|
| 55 |
+
**Hierarchical Reasoning Model.**
|
| 56 |
+
Preprint: arXiv:2506.21734 (June 2025), <https://arxiv.org/abs/2506.21734>.
|
| 57 |
+
|
| 58 |
+
### `dendritic_layer` (`synapse/frontier/dendritic.py`)
|
| 59 |
+
|
| 60 |
+
* Spyridon Chavlis and Panayiota Poirazi.
|
| 61 |
+
**Dendrites endow artificial neural networks with accurate, robust and parameter-efficient learning.**
|
| 62 |
+
*Nature Communications* 16, 943 (published 22 January 2025).
|
| 63 |
+
DOI [10.1038/s41467-025-56297-9](https://doi.org/10.1038/s41467-025-56297-9); PMC11754790; arXiv:2404.03708.
|
| 64 |
+
Reference code: <https://github.com/Poirazi-Lab/dendritic_anns>.
|
| 65 |
+
|
| 66 |
+
### `muon_optimizer` (`synapse/frontier/muon.py`)
|
| 67 |
+
|
| 68 |
+
* Keller Jordan, Yuchen Jin, Vlado Boza, Jiacheng You, Franz Cesista, Laker Newhouse, and Jeremy Bernstein.
|
| 69 |
+
**Muon: An optimizer for hidden layers in neural networks.** Blog post (8 December 2024),
|
| 70 |
+
<https://kellerjordan.github.io/posts/muon/>.
|
| 71 |
+
* Jingyuan Liu, Jianlin Su, Xingcheng Yao, Zhejun Jiang, Guokun Lai, Yulun Du, Yidao Qin, Weixin Xu, Enzhe Lu, Junjie Yan, Yanru Chen, Huabin Zheng, Yibo Liu, Shaowei Liu, Bohong Yin, Weiran He, Han Zhu, Yuzhi Wang, Jianzhou Wang, Mengnan Dong, Zheng Zhang, Yongsheng Kang, Hao Zhang, Xinran Xu, Yutao Zhang, Yuxin Wu, Xinyu Zhou, and Zhilin Yang (Moonshot AI).
|
| 72 |
+
**Muon is Scalable for LLM Training.**
|
| 73 |
+
Preprint: arXiv:2502.16982 (24 February 2025), <https://arxiv.org/abs/2502.16982>.
|
| 74 |
+
|
| 75 |
+
### `rigl_sparse` (`synapse/frontier/rigl.py`)
|
| 76 |
+
|
| 77 |
+
* Utku Evci, Trevor Gale, Jacob Menick, Pablo Samuel Castro, and Erich Elsen.
|
| 78 |
+
**Rigging the Lottery: Making All Tickets Winners.** *Proceedings of the 37th International Conference on Machine Learning (ICML 2020)*, PMLR 119, 2943–2952 (July 2020).
|
| 79 |
+
Preprint: arXiv:1911.11134 (25 November 2019), <https://arxiv.org/abs/1911.11134>.
|
| 80 |
+
|
| 81 |
+
### `sparse_dictionary` (`synapse/frontier/sparse_dictionary.py`)
|
| 82 |
+
|
| 83 |
+
* Leo Gao, Tom Dupré la Tour, Henk Tillman, Gabriel Goh, Rajan Troll, Alec Radford, Ilya Sutskever, Jan Leike, and Jeffrey Wu.
|
| 84 |
+
**Scaling and evaluating sparse autoencoders.** *International Conference on Learning Representations (ICLR) 2025*.
|
| 85 |
+
Preprint: arXiv:2406.04093 (6 June 2024), <https://arxiv.org/abs/2406.04093>.
|
| 86 |
+
* Alireza Makhzani and Brendan Frey.
|
| 87 |
+
**k-Sparse Autoencoders.** *International Conference on Learning Representations (ICLR) 2014*.
|
| 88 |
+
Preprint: arXiv:1312.5663 (19 December 2013), <https://arxiv.org/abs/1312.5663>.
|
| 89 |
+
|
| 90 |
+
### `anytime_inference` (`synapse/frontier/anytime.py`)
|
| 91 |
+
|
| 92 |
+
* Ian Waudby-Smith and Aaditya Ramdas.
|
| 93 |
+
**Estimating means of bounded random variables by betting.** *Journal of the Royal Statistical Society Series B: Statistical Methodology* 86(1), 1–27 (February 2024; discussion paper).
|
| 94 |
+
DOI [10.1093/jrsssb/qkad009](https://doi.org/10.1093/jrsssb/qkad009); arXiv:2010.09686.
|
| 95 |
+
* Aaditya Ramdas, Peter Grünwald, Vladimir Vovk, and Glenn Shafer.
|
| 96 |
+
**Game-Theoretic Statistics and Safe Anytime-Valid Inference.** *Statistical Science* 38(4), 576–601 (November 2023).
|
| 97 |
+
DOI [10.1214/23-STS894](https://doi.org/10.1214/23-STS894); arXiv:2210.01948.
|
| 98 |
+
|
| 99 |
+
### `experiment_design` (add-on)
|
| 100 |
+
|
| 101 |
+
* Dennis V. Lindley.
|
| 102 |
+
**On a Measure of the Information Provided by an Experiment.** *The Annals of Mathematical Statistics* 27(4), 986–1005 (December 1956).
|
| 103 |
+
DOI [10.1214/aoms/1177728069](https://doi.org/10.1214/aoms/1177728069).
|
| 104 |
+
* Kathryn Chaloner and Isabella Verdinelli.
|
| 105 |
+
**Bayesian Experimental Design: A Review.** *Statistical Science* 10(3), 273–304 (August 1995).
|
| 106 |
+
DOI [10.1214/ss/1177009939](https://doi.org/10.1214/ss/1177009939).
|
| 107 |
+
|
| 108 |
+
### `quality_diversity` (`synapse/frontier/quality_diversity.py`)
|
| 109 |
+
|
| 110 |
+
* Jean-Baptiste Mouret and Jeff Clune.
|
| 111 |
+
**Illuminating search spaces by mapping elites.**
|
| 112 |
+
Preprint: arXiv:1504.04909 (20 April 2015), <https://arxiv.org/abs/1504.04909>.
|
| 113 |
+
* Jenny Zhang, Shengran Hu, Cong Lu, Robert Lange, and Jeff Clune (Sakana AI / UBC).
|
| 114 |
+
**Darwin Gödel Machine: Open-Ended Evolution of Self-Improving Agents.**
|
| 115 |
+
Preprint: arXiv:2505.22954 (29 May 2025), <https://arxiv.org/abs/2505.22954>.
|
| 116 |
+
|
| 117 |
+
### `morphogenesis` (add-on)
|
| 118 |
+
|
| 119 |
+
* Alexander Mordvintsev, Ettore Randazzo, Eyvind Niklasson, and Michael Levin.
|
| 120 |
+
**Growing Neural Cellular Automata.** *Distill* (11 February 2020).
|
| 121 |
+
DOI [10.23915/distill.00023](https://doi.org/10.23915/distill.00023), <https://distill.pub/2020/growing-ca/>.
|
| 122 |
+
* Giovanni Pezzulo and Michael Levin.
|
| 123 |
+
**Re-membering the body: applications of computational neuroscience to the top-down control of regeneration of limbs and other complex organs.**
|
| 124 |
+
*Integrative Biology* 7(12), 1487–1517 (December 2015).
|
| 125 |
+
DOI [10.1039/c5ib00221d](https://doi.org/10.1039/c5ib00221d); PMC4700597.
|
| 126 |
+
|
| 127 |
+
### `connectomics` (`synapse/frontier/connectomics.py`)
|
| 128 |
+
|
| 129 |
+
* Christopher J. Honey, Olaf Sporns, Leila Cammoun, Xavier Gigandet, Jean-Philippe Thiran, Reto Meuli, and Patric Hagmann.
|
| 130 |
+
**Predicting human resting-state functional connectivity from structural connectivity.** *Proceedings of the National Academy of Sciences (PNAS)* 106(6), 2035–2040 (10 February 2009).
|
| 131 |
+
DOI [10.1073/pnas.0811168106](https://doi.org/10.1073/pnas.0811168106).
|
| 132 |
+
* Elena A. Allen, Eswar Damaraju, Sergey M. Plis, Erik B. Erhardt, Tom Eichele, and Vince D. Calhoun.
|
| 133 |
+
**Tracking Whole-Brain Connectivity Dynamics in the Resting State.** *Cerebral Cortex* 24(3), 663–676 (March 2014; published online 11 November 2012).
|
| 134 |
+
DOI [10.1093/cercor/bhs352](https://doi.org/10.1093/cercor/bhs352).
|
| 135 |
+
* Ernesto Estrada and Naomichi Hatano.
|
| 136 |
+
**Communicability in complex networks.** *Physical Review E* 77(3), 036111 (March 2008).
|
| 137 |
+
DOI [10.1103/PhysRevE.77.036111](https://doi.org/10.1103/PhysRevE.77.036111).
|
| 138 |
+
|
| 139 |
+
### `causal_emergence` (`synapse/frontier/causal_emergence.py`)
|
| 140 |
+
|
| 141 |
+
* Erik P. Hoel, Larissa Albantakis, and Giulio Tononi.
|
| 142 |
+
**Quantifying causal emergence shows that macro can beat micro.** *Proceedings of the National Academy of Sciences (PNAS)* 110(49), 19790–19795 (3 December 2013).
|
| 143 |
+
DOI [10.1073/pnas.1314922110](https://doi.org/10.1073/pnas.1314922110).
|
| 144 |
+
* Erik P. Hoel.
|
| 145 |
+
**When the Map Is Better Than the Territory.** *Entropy* 19(5), 188 (May 2017).
|
| 146 |
+
DOI [10.3390/e19050188](https://doi.org/10.3390/e19050188).
|
| 147 |
+
|
| 148 |
+
### `hh_cable` (`synapse/frontier/hh_cable.py`)
|
| 149 |
+
|
| 150 |
+
* Alan L. Hodgkin and Andrew F. Huxley.
|
| 151 |
+
**A quantitative description of membrane current and its application to conduction and excitation in nerve.**
|
| 152 |
+
*The Journal of Physiology* 117(4), 500–544 (28 August 1952).
|
| 153 |
+
DOI [10.1113/jphysiol.1952.sp004764](https://doi.org/10.1113/jphysiol.1952.sp004764); PMC1392413.
|
| 154 |
+
|
| 155 |
+
### `nir_export` (`synapse/frontier/nir_export.py`)
|
| 156 |
+
|
| 157 |
+
* Jens E. Pedersen, Steven Abreu, Melika Payvand, Sadique Sheik, Gregor Lenz, Felix Bauer, Yigit Demirag, et al.
|
| 158 |
+
**Neuromorphic intermediate representation: A unified instruction set for interoperable brain-inspired computing.**
|
| 159 |
+
*Nature Communications* 15, 8122 (17 September 2024).
|
| 160 |
+
DOI [10.1038/s41467-024-52259-9](https://doi.org/10.1038/s41467-024-52259-9).
|
| 161 |
+
Repository: <https://github.com/neuromorphs/NIR>.
|
| 162 |
+
|
| 163 |
+
---
|
| 164 |
+
|
| 165 |
+
## 2. Portfolio Provenance (`kai9987kai` Sibling Repositories)
|
| 166 |
+
|
| 167 |
+
| Frontier Module | Sibling Repository (`kai9987kai`) | Core Concept Adapted |
|
| 168 |
+
|---|---|---|
|
| 169 |
+
| `rigl_sparse` | `sonapse-evo` | Dynamic sparse topology pruning and gradient-magnitude regrowth at a fixed synapse budget |
|
| 170 |
+
| `experiment_design` | `COUNTERFORM`, `Mnemorph` | One-step expected downstream decision-risk acquisition with explicit abstention |
|
| 171 |
+
| `quality_diversity` | `SONAPSE-ORIGIN`, `sonapse-evo` | MAP-Elites illumination archive with verifier-gated admission and lineage tracking |
|
| 172 |
+
| `morphogenesis` | `morpheus`, `prometheus-alpha`, `GenesisEngine`, `MOLT` | Single-organizer developmental growth into a regional connectome and setpoint-guided regeneration after lesions |
|
| 173 |
+
| `connectomics` | `SONAPSE-CONNECTOME` | Separation of structural, functional (Pearson/Spearman/partial), dynamic-functional, and ridge-VAR(1) effective connectivity |
|
| 174 |
+
| `causal_emergence` | `GhostInTheMachine`, `SONAPSE-ORIGIN` | Effective information of micro vs coarse-grained transition probability matrices with determinism/degeneracy decomposition |
|
| 175 |
+
| `hh_cable` | `NeuroPulse-CableLab` | Multi-compartment Hodgkin–Huxley squid-axon cable integrator and electrophysiological assay protocol |
|
| 176 |
+
| `joint_failure` | `FAULTLINE` | Condition-indexed joint-failure signature accounting and worst-condition majority-vote panel selection |
|
docs/frontier/modules/anytime_inference.md
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `anytime_inference`: anytime-valid inference
|
| 2 |
+
|
| 3 |
+
Module file: `synapse/frontier/anytime.py` · tests: `tests/test_frontier_methodology.py` ·
|
| 4 |
+
experiment id: `anytime_inference` (kind `validation`, verdict `pass`/`fail`) · no live observer ·
|
| 5 |
+
evidence tier: `synthetic_abstraction`.
|
| 6 |
+
|
| 7 |
+
The module provides two betting-based tools that stay valid when you look at the data after every
|
| 8 |
+
observation and stop whenever you like:
|
| 9 |
+
|
| 10 |
+
* a **confidence sequence** for the mean of a bounded stream;
|
| 11 |
+
* a two-sided **e-process** for a zero mean of bounded paired differences.
|
| 12 |
+
|
| 13 |
+
Both are combined into `anytime_compare`, a paired comparison that returns the lab's verdict vocabulary.
|
| 14 |
+
The constructions are *inspired by* Waudby-Smith & Ramdas (2024), and the framing follows Ramdas, Grünwald,
|
| 15 |
+
Vovk & Shafer (2023). The module re-implements the constructions in NumPy and checks their guarantees in
|
| 16 |
+
seeded simulations. It reproduces none of the papers' experiments or figures.
|
| 17 |
+
|
| 18 |
+
## What it computes
|
| 19 |
+
|
| 20 |
+
### Betting confidence sequence (`betting_confidence_sequence`)
|
| 21 |
+
|
| 22 |
+
Observations `x_t` in `[lo, hi]` are rescaled to `X_t = (x_t - lo) / (hi - lo)` in `[0, 1]`. For a candidate
|
| 23 |
+
mean `m` (paper Sec. 4.4, Eqs. 24-26):
|
| 24 |
+
|
| 25 |
+
```
|
| 26 |
+
K+_t(m) = prod_{i<=t} (1 + lam+_i(m) (X_i - m)) K-_t(m) = prod_{i<=t} (1 - lam-_i(m) (X_i - m))
|
| 27 |
+
K±_t(m) = max{ theta K+_t(m), (1 - theta) K-_t(m) } (hedged capital, Eq. 24)
|
| 28 |
+
lam+_t(m) = min(lam_t, c / m) lam-_t(m) = min(lam_t, c / (1 - m)) (truncation, Eq. 25)
|
| 29 |
+
lam_t = sqrt( 2 log(2/alpha) / (sigma2_{t-1} t log(1 + t)) ) (plug-in bet, Eq. 26)
|
| 30 |
+
mu_t = (1/2 + sum_{i<=t} X_i) / (t + 1)
|
| 31 |
+
sigma2_t = (1/4 + sum_{i<=t} (X_i - mu_i)^2) / (t + 1), sigma2_0 = 1/4
|
| 32 |
+
CS_t = intersection_{i<=t} { m in [0, 1] : K±_i(m) < 1/alpha } (Theorem 3)
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
* **Validity.** Theorem 3 of the paper: for each fixed `m = mu` the capital processes are nonnegative
|
| 36 |
+
martingales, so by Ville's inequality the true mean leaves the set at *some* time with probability at
|
| 37 |
+
most `alpha`. The running intersection keeps the same guarantee.
|
| 38 |
+
* **Grid search.** The set at each time is an interval (Theorem 3), so the module evaluates `K±` on the grid
|
| 39 |
+
`m = 0, 1/g, ..., 1` (`g = grid_size`, default 1000), as the paper suggests. Each bound is the first
|
| 40 |
+
*excluded* grid point outside the run of included points. The result is a superset of the exact set,
|
| 41 |
+
conservative by at most one grid step `(hi - lo) / g`.
|
| 42 |
+
* **No grid point inside.** If no grid point is inside, the bounds bracket the grid minimisers of `K±`.
|
| 43 |
+
`K+` is non-increasing and `K-` non-decreasing in `m`, so `K±` is quasiconvex and the exact set lies in
|
| 44 |
+
that bracket.
|
| 45 |
+
* **Returns.** `lower` and `upper` (running intersection), `lower_raw` and `upper_raw` (the per-time set),
|
| 46 |
+
`final` and `empty`. The intersection is empty with probability at most `alpha`.
|
| 47 |
+
|
| 48 |
+
### Paired e-process (`paired_e_process`)
|
| 49 |
+
|
| 50 |
+
The null hypothesis is `H0: E[D_t | D_1..D_{t-1}] = 0`, for differences with `|D_t| <= B`. Map each
|
| 51 |
+
difference to `X_t = (1 + D_t / B) / 2` in `[0, 1]` and test `m = 1/2`:
|
| 52 |
+
|
| 53 |
+
```
|
| 54 |
+
lam_t = clip( (mu_{t-1} - m) / (sigma2_{t-1} + (mu_{t-1} - m)^2), -c/(1-m), c/m ) (aGRAPA, paper App. B.3)
|
| 55 |
+
lam+_t = max(lam_t, 0) lam-_t = max(-lam_t, 0)
|
| 56 |
+
E_t = (K+_t(m) + K-_t(m)) / 2 (the paper's mixture M±_t with theta = 1/2, Sec. 4.4)
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
* **Estimators.** `mu` and `sigma2` are the Eq. 26 estimators. App. B.3 writes the bet with `mu_{t-1}` and
|
| 60 |
+
`sigma2_{t-1}` without restating them; the paper defines that notation only in Eq. 26, which the module
|
| 61 |
+
follows.
|
| 62 |
+
* **Sign split.** The bet is split by sign: `K+` gathers evidence for a positive mean, `K-` for a negative
|
| 63 |
+
one.
|
| 64 |
+
* **Validity.** Every factor is at least `1 - c > 0` and the bets are predictable. Under `H0`, `K+`, `K-`
|
| 65 |
+
and `E` are therefore nonnegative martingales that start at 1. Ville's inequality then gives
|
| 66 |
+
`P(exists t: E_t >= 1/alpha) <= alpha` at every stopping time, so optional stopping does not break it.
|
| 67 |
+
* **Finite outputs.** Reported values are capped at `exp(690)` so they stay finite. `log_e_process` is
|
| 68 |
+
uncapped.
|
| 69 |
+
|
| 70 |
+
### Paired comparison (`anytime_compare`)
|
| 71 |
+
|
| 72 |
+
`D_t = candidate_t - reference_t` with a known bound `|D_t| <= bound`. The e-process is checked after every
|
| 73 |
+
observation.
|
| 74 |
+
|
| 75 |
+
* **Rejection.** `rejected` is true at the first time `E_t >= 1/alpha`. `stopped_at` is that time (1-based)
|
| 76 |
+
and `e_value` is the stopped value. `e_value_final` is the value at the last observation.
|
| 77 |
+
* **Direction.** The direction comes from the larger one-sided process at the stopping time. Declaring
|
| 78 |
+
`positive` needs `K+_tau >= E_tau >= 1/alpha`. When the true conditional mean is `<= 0`, `K+` is a
|
| 79 |
+
nonnegative supermartingale (`lam+ >= 0`), so a wrong-direction declaration also has probability at most
|
| 80 |
+
`alpha`.
|
| 81 |
+
* **Verdict.** `improved` or `worse` depends on the direction and `higher_is_better`. Without a rejection
|
| 82 |
+
the verdict is `no_detectable_difference`.
|
| 83 |
+
* **CS bounds.** `cs_lower` and `cs_upper` are the hedged betting CS for the mean difference on
|
| 84 |
+
`[-bound, bound]` at the last observation, at level `1 - alpha`. The verdict comes from the e-process
|
| 85 |
+
only. The CS is reported beside it, with `cs_excludes_zero`, and the two can disagree near the threshold.
|
| 86 |
+
|
| 87 |
+
### Invalid baseline (`naive_peeking_t_test`)
|
| 88 |
+
|
| 89 |
+
A two-sided one-sample t-test of mean 0 repeated at every look `n >= min_n`. It reports whether *any* look
|
| 90 |
+
rejected and whether the single final look rejected. The tests check it against `scipy.stats.ttest_1samp`
|
| 91 |
+
at every look.
|
| 92 |
+
|
| 93 |
+
## Validation experiment (`run_experiment`, `EXPERIMENTS = {'anytime_inference': run_experiment}`)
|
| 94 |
+
|
| 95 |
+
For every seed the experiment draws `replicates` independent sequences of length `horizon` per scenario.
|
| 96 |
+
Every statistic is evaluated after every observation. Each scenario has its own generator,
|
| 97 |
+
`np.random.default_rng(seed + offset)`.
|
| 98 |
+
|
| 99 |
+
| scenario | data | used for |
|
| 100 |
+
|---|---|---|
|
| 101 |
+
| `null_paired_bernoulli` | `D = Bern(0.6) - Bern(0.6)`, independent, bound 1 | type-I error under optional stopping |
|
| 102 |
+
| `null_skewed_continuous` | `D = Beta(0.5, 4) - 1/9` (mean exactly 0, skewed), bound 1 | type-I error under optional stopping |
|
| 103 |
+
| `effect` | `D = Bern(0.75) - Bern(0.5)` (mean 0.25), bound 1 | power, stopping time, wrong-direction rate |
|
| 104 |
+
| `cover_beta` | `X ~ Beta(2, 5)` on `[0, 1]` (mean 2/7) | time-uniform CS coverage and width |
|
| 105 |
+
| `cover_bernoulli` | `X ~ Bern(0.3)` | time-uniform CS coverage and width |
|
| 106 |
+
|
| 107 |
+
The checks are pooled over seeds. Monte-Carlo slack is `mc_z = 3` standard errors. The verdict is `pass`
|
| 108 |
+
only if all 12 checks hold:
|
| 109 |
+
|
| 110 |
+
* `e_process_type1_le_alpha_{null}`: the rate of `sup_t E_t >= 1/alpha` is at most `alpha + 3 se`.
|
| 111 |
+
* `naive_peeking_t_exceeds_alpha_{null}`: the repeated t-test (looks from `n = 10`) rejects more often than
|
| 112 |
+
`alpha` by more than 3 se.
|
| 113 |
+
* `mean_final_e_value_le_1_{null}`: the sample mean of `E_horizon` is at most `1 + 3 se`.
|
| 114 |
+
* The expectation is exactly 1, but the terminal value is heavy-tailed.
|
| 115 |
+
* Rare large values carry the mean, so the sample mean usually falls below 1, and the check is one-sided.
|
| 116 |
+
* A 200,000-path run of the paired-Bernoulli null (the experiment's generator, `D = Bern(0.6) - Bern(0.6)`,
|
| 117 |
+
`np.random.default_rng(12345)`, `c = 0.5`, horizon 200; measured 2026-11-20) gave sample means 1.000,
|
| 118 |
+
0.9996, 1.0006, 1.007, 1.339 and 0.763 at `t = 5, 10, 20, 50, 100, 200`.
|
| 119 |
+
* The `t = 100` mean is above 1 only because one path reached `E_100 ≈ 82,000`, which alone adds 0.41 to
|
| 120 |
+
the mean. No path came close to that at `t = 200` (largest value about 16,000), and the mean fell to 0.763.
|
| 121 |
+
* The tests check that the expectation is exactly 1 by enumerating every path of short sequences instead.
|
| 122 |
+
* `power_on_clear_effect`: the rejection rate under `effect` is at least `power_min = 0.8`.
|
| 123 |
+
* `wrong_direction_rate_le_alpha`: wrong-direction rejections under `effect` are at most `alpha`.
|
| 124 |
+
* `cs_uniform_coverage_ge_1_minus_alpha_{beta,bernoulli}`: the true mean stays inside the
|
| 125 |
+
running-intersection CS at every one of the `horizon` times with frequency at least `1 - alpha - 3 se`.
|
| 126 |
+
* `cs_shrinks_{beta,bernoulli}`: the mean final width is below the mean width at `t = 20`.
|
| 127 |
+
|
| 128 |
+
Defaults: `alpha = 0.05`, `replicates = 400`, `horizon = 500`, `grid_size = 400`, `c = 0.5`, `theta = 0.5`,
|
| 129 |
+
`naive_min_n = 10`, seeds `(0, 1, 2)`. `quick=True` uses `replicates = 100`, `horizon = 200` and
|
| 130 |
+
`grid_size = 200`. Unknown overrides raise `ValueError`, and so do sizes above the memory bounds
|
| 131 |
+
(`replicates × horizon <= 4,000,000`, `replicates × (grid_size + 1) <= 20,000,000`).
|
| 132 |
+
|
| 133 |
+
## Public API
|
| 134 |
+
|
| 135 |
+
```python
|
| 136 |
+
betting_confidence_sequence(x, lo, hi, alpha=0.05, *, grid_size=1000, c=0.5, theta=0.5) -> dict
|
| 137 |
+
paired_e_process(differences, bound, *, c=0.5) -> dict
|
| 138 |
+
anytime_compare(candidate, reference, *, bound, alpha=0.05, higher_is_better=True, c=0.5, grid_size=1000) -> dict
|
| 139 |
+
# keys: e_value, e_value_final, rejected, stopped_at, direction, cs_lower, cs_upper, cs_excludes_zero,
|
| 140 |
+
# cs_empty, mean_difference, verdict in ('improved', 'no_detectable_difference', 'worse'), ...
|
| 141 |
+
naive_peeking_t_test(differences, alpha=0.05, *, min_n=2) -> dict
|
| 142 |
+
run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> sealed receipt
|
| 143 |
+
EXPERIMENTS = {'anytime_inference': run_experiment}
|
| 144 |
+
```
|
| 145 |
+
|
| 146 |
+
* **Input validation.** Inputs are validated before any computation, and bad input raises `ValueError`.
|
| 147 |
+
This covers non-finite or out-of-range values, `alpha`, `c` or `theta` outside `(0, 1)`, a mismatched
|
| 148 |
+
length and `|difference| > bound`.
|
| 149 |
+
* **Determinism.** Everything is deterministic. The module uses NumPy, plus `scipy.special.stdtrit` for the
|
| 150 |
+
t-test baseline. It never touches the global NumPy RNG and never imports torch.
|
| 151 |
+
|
| 152 |
+
## Connection to Sonapse
|
| 153 |
+
|
| 154 |
+
* **Not wired in.** `harness.compare` decides lab verdicts with a paired 95 % t interval over a fixed set of
|
| 155 |
+
seeds. That interval is valid only at a sample size fixed in advance.
|
| 156 |
+
* **When to use it.** `anytime_compare` is the anytime-valid alternative for studies that add seeds or
|
| 157 |
+
evaluation episodes and check results as they arrive. Examples are held-out correctness streams of two
|
| 158 |
+
NEUROWEAVE arms, or paired per-seed scores with a known range.
|
| 159 |
+
* **How to use it.** The caller supplies the bound on `|candidate - reference|`. For 0/1 correctness or
|
| 160 |
+
accuracies it is 1.
|
| 161 |
+
* **Scope.** The module does not change `harness.compare` or any other module's verdict. Using it there
|
| 162 |
+
would mean editing the shared harness.
|
| 163 |
+
|
| 164 |
+
## Not implemented
|
| 165 |
+
|
| 166 |
+
* **From Waudby-Smith & Ramdas (2024).**
|
| 167 |
+
* The other betting strategies: GRAPA root-finding, LBOW, ONS-m, dKelly, ConBo and SRP (App. B).
|
| 168 |
+
* Sampling without replacement (Sec. 5.2).
|
| 169 |
+
* The fixed-sample-size CI tuning of Remark 3 / Eq. 27.
|
| 170 |
+
* The closed-form predictable plug-in Hoeffding and empirical-Bernstein CSs (Sec. 3).
|
| 171 |
+
* Root-finding in place of the grid.
|
| 172 |
+
* The point estimator `argmin_m K±_t(m)`.
|
| 173 |
+
* **Not covered by the guarantees.**
|
| 174 |
+
* The CS assumes a constant conditional mean.
|
| 175 |
+
* Streams whose conditional mean drifts are not covered (the paper's Sec. E.5).
|
| 176 |
+
* The e-process needs `E[D_t | past] = 0` under the null.
|
| 177 |
+
* **From Ramdas et al. (2023).**
|
| 178 |
+
* Composite nulls beyond a zero mean.
|
| 179 |
+
* Universal inference, e-value merging and p-to-e calibration.
|
| 180 |
+
|
| 181 |
+
## Verified references
|
| 182 |
+
|
| 183 |
+
* Ian Waudby-Smith and Aaditya Ramdas. **Estimating means of bounded random variables by betting.**
|
| 184 |
+
*Journal of the Royal Statistical Society Series B: Statistical Methodology* 86(1):1–27, February 2024
|
| 185 |
+
(read before the Royal Statistical Society, with discussion on pp. 28–61). doi:10.1093/jrsssb/qkad009.
|
| 186 |
+
<https://academic.oup.com/jrsssb/article/86/1/1/7043257> · preprint arXiv:2010.09686 (v1 19 October 2020;
|
| 187 |
+
v7 25 August 2022), <https://arxiv.org/abs/2010.09686>.
|
| 188 |
+
* Bibliographic data checked against the publisher and arXiv pages on 2026-11-20.
|
| 189 |
+
* The following were checked against the text of arXiv v7 the same day; section, equation and appendix
|
| 190 |
+
numbers in this document follow v7:
|
| 191 |
+
* the hedged capital process, Sec. 4.4, Eq. 24, and the mixture `M±`;
|
| 192 |
+
* the truncation `|lam~| ∧ c/m`, `∧ c/(1-m)` with `c = 1/2` or `3/4`, Eq. 25;
|
| 193 |
+
* Theorem 3 (valid CS, interval for each `t`, running intersection);
|
| 194 |
+
* the plug-in bet and estimators, Eq. 26;
|
| 195 |
+
* the grid-search remark, Sec. 4.4;
|
| 196 |
+
* quasiconvexity, Remark 2;
|
| 197 |
+
* aGRAPA, App. B.3, truncated to `[-c/(1-m), c/m]`.
|
| 198 |
+
* Aaditya Ramdas, Peter Grünwald, Vladimir Vovk and Glenn Shafer. **Game-theoretic statistics and safe
|
| 199 |
+
anytime-valid inference.** *Statistical Science* 38(4):576–601, November 2023. doi:10.1214/23-STS894.
|
| 200 |
+
<https://projecteuclid.org/journals/statistical-science/volume-38/issue-4/Game-Theoretic-Statistics-and-Safe-Anytime-Valid-Inference/10.1214/23-STS894.full>
|
| 201 |
+
· preprint arXiv:2210.01948. Bibliographic data was checked against Project Euclid and the Royal Holloway
|
| 202 |
+
repository on 2026-11-20. The CWI repository lists the page range as 576–597, and Project Euclid gives
|
| 203 |
+
576–601.
|
| 204 |
+
|
| 205 |
+
## Measured results
|
| 206 |
+
|
| 207 |
+
All numbers were measured on 2026-11-20 (UTC) on Windows 11 ARM64 with Python 3.12.10 and NumPy 2.4.3, with
|
| 208 |
+
`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1`. Other agents shared the CPU, so wall-clock is
|
| 209 |
+
indicative only. Rates are pooled over seeds `(0, 1, 2)`. `se` is the binomial Monte-Carlo standard error.
|
| 210 |
+
|
| 211 |
+
**Quick mode** (`run_experiment(quick=True)`): 3 × 100 sequences per scenario, horizon 200, grid 200,
|
| 212 |
+
`alpha = 0.05`, `c = theta = 0.5`.
|
| 213 |
+
|
| 214 |
+
| | value |
|
| 215 |
+
|---|---|
|
| 216 |
+
| verdict | **pass** (12 of 12 checks) |
|
| 217 |
+
| paired-Bernoulli null: e-process / repeated t-test / single final t-test type-I | 0.020 (6/300) / 0.360 (108/300) / 0.033 (10/300) |
|
| 218 |
+
| skewed null: e-process / repeated t-test / single final t-test type-I | 0.000 (0/300) / 0.410 (123/300) / 0.057 (17/300) |
|
| 219 |
+
| mean final e-value (paired Bernoulli / skewed) | 0.52 (max 4.56) / 1.00 (max 4.89) |
|
| 220 |
+
| effect (mean difference 0.25): power, wrong direction, median stopping time | 0.98 (294/300), 0, 59 observations |
|
| 221 |
+
| CS uniform coverage, Beta(2, 5) / Bernoulli(0.3) | 0.990 (297/300) / 0.957 (287/300) |
|
| 222 |
+
| CS mean width at t = 20 → t = 200, Beta / Bernoulli | 0.323 → 0.072 / 0.515 → 0.212 |
|
| 223 |
+
| digest (prefix) | `a07208ae621e340b` (identical across separate processes) |
|
| 224 |
+
| measured wall-clock | 3.1–3.9 s |
|
| 225 |
+
|
| 226 |
+
**Default size** (`run_experiment()`): 3 × 400 sequences per scenario, horizon 500, grid 400, same `alpha`,
|
| 227 |
+
`c` and `theta`.
|
| 228 |
+
|
| 229 |
+
| | value |
|
| 230 |
+
|---|---|
|
| 231 |
+
| verdict | **pass** (12 of 12 checks) |
|
| 232 |
+
| paired-Bernoulli null: e-process / repeated t-test / single final t-test type-I | 0.018 (22/1200, se 0.004) / 0.409 (491/1200) / 0.058 (69/1200) |
|
| 233 |
+
| skewed null: e-process / repeated t-test / single final t-test type-I | 0.001 (1/1200) / 0.457 (548/1200) / 0.047 (56/1200) |
|
| 234 |
+
| mean final e-value (paired Bernoulli / skewed) | 0.49 (max 19.5) / 0.96 (max 14.9) |
|
| 235 |
+
| effect (mean difference 0.25): power, wrong direction, median stopping time | 1.00 (1200/1200), 0, 57.5 observations |
|
| 236 |
+
| CS uniform coverage, Beta(2, 5) / Bernoulli(0.3) | 0.985 (1182/1200) / 0.966 (1159/1200) |
|
| 237 |
+
| CS mean width at t = 20 → t = 500, Beta / Bernoulli | 0.319 → 0.045 / 0.510 → 0.148 |
|
| 238 |
+
| running intersection empty at t = 500 | 0 / 1 of 1200 (counted as a coverage miss) |
|
| 239 |
+
| digest (prefix) | `7b05678cbd3aa5b7` (identical in two separate runs) |
|
| 240 |
+
| measured wall-clock | 81.9–94.1 s, almost all of it in the 401-point grid search |
|
| 241 |
+
|
| 242 |
+
Reading:
|
| 243 |
+
|
| 244 |
+
* **Peeking breaks the t-test.** At default size the repeated t-test rejects a true null in 41–46 % of
|
| 245 |
+
sequences when it looks after every observation. A single t-test at the final time stays near the nominal
|
| 246 |
+
5 %.
|
| 247 |
+
* **The e-process stays valid.** It rejected at most 1.8 % of null sequences under the same monitoring, and
|
| 248 |
+
it still detected the 0.25 mean difference in every sequence (median 57.5 paired observations).
|
| 249 |
+
* **The betting CS covers the mean.** It covered the true mean at all 500 times in 98.5 % and 96.6 % of
|
| 250 |
+
sequences. That is above the stated 95 %, as expected from a conservative construction.
|
| 251 |
+
* **Limits of these checks.** They test the stated guarantees on these generators only. They say nothing
|
| 252 |
+
about data that violate the assumptions.
|
docs/frontier/modules/btsp_memory.md
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `btsp_memory`: one-shot BTSP memory with binary synapses
|
| 2 |
+
|
| 3 |
+
Module file: `synapse/frontier/btsp.py` · tests: `tests/test_frontier_memory.py` ·
|
| 4 |
+
experiment ids: `btsp_memory`, `btsp_memory_capacity` · engine extension: `BTSPExtension` (id `btsp_memory`) ·
|
| 5 |
+
baselines: `WillshawMemory`, `RandomRecallControl` · evidence tier: `synthetic_abstraction`.
|
| 6 |
+
|
| 7 |
+
The module implements the binary-weight rule for **behavioural time-scale synaptic plasticity** (BTSP) of
|
| 8 |
+
Wu & Maass (*Nature Communications*, 2025). In this rule, random plateau potentials gate stochastic flips of
|
| 9 |
+
binary synapses, so a pattern is stored after a single presentation. The module also implements the paper's
|
| 10 |
+
feedback pathway for completing a pattern from a partial cue. It uses the memory in three settings:
|
| 11 |
+
|
| 12 |
+
* a capacity benchmark against a classic Willshaw memory with the same number of synapses,
|
| 13 |
+
* a NEUROWEAVE engine extension that adds familiarity features to the readout,
|
| 14 |
+
* direct use as a content-addressable memory (`BTSPMemory`).
|
| 15 |
+
|
| 16 |
+
It is *inspired by* the paper and does not reproduce it. The paper's default network has 25,000 input and
|
| 17 |
+
39,000 memory neurons, while this module's largest benchmark uses 1,000 inputs and 833 memory units. Thresholds
|
| 18 |
+
are set more simply here (see below). None of the paper's figures or results are attempted. The model says nothing about
|
| 19 |
+
hippocampal biology.
|
| 20 |
+
|
| 21 |
+
## What it computes
|
| 22 |
+
|
| 23 |
+
`BTSPMemory(input_dim, memory_dim, *, density=0.6, plateau_prob=0.02, flip_prob=0.5, threshold=0.35,
|
| 24 |
+
feedback_threshold=0.5, seed=0)` has `m = input_dim` binary input units and `n = memory_dim` binary memory
|
| 25 |
+
units.
|
| 26 |
+
|
| 27 |
+
```
|
| 28 |
+
masks C (n x m) forward, D (m x n) feedback: independent Bernoulli(density) connections, fixed by the seed
|
| 29 |
+
weights W (n x m) forward, B (m x n) feedback: binary, initially all 0
|
| 30 |
+
|
| 31 |
+
store x plateau set Q: every memory unit independently with probability plateau_prob (firing is irrelevant)
|
| 32 |
+
for j in Q and every input i with x_i = 1 and C_ji = 1:
|
| 33 |
+
W_ji: 0 -> 1 with probability p_ltp, 1 -> 0 with probability p_ltd (paper Eq. 1: both 0.5)
|
| 34 |
+
then, with the updated W: B_ij <- B_ij OR (D_ij AND x_i AND z_j(x)) (one-shot Hebbian, saturating)
|
| 35 |
+
|
| 36 |
+
trace z_j(c) = 1[ (W c)_j > threshold * density * |c| ] (McCulloch-Pitts memory units)
|
| 37 |
+
recall r_i(c) = 1[ (B z(c))_i > feedback_threshold * density * |z(c)| ] (McCulloch-Pitts input units)
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
`|c|` is the number of ones. `flip_prob` is one number (`p_ltp = p_ltd`) or a `(p_ltp, p_ltd)` pair. Masks come
|
| 41 |
+
from `default_rng(seed + 61403)`. Plateau and flip draws come from `default_rng(seed + 61417)`, so the same seed
|
| 42 |
+
and store sequence give identical weights. Weights are boolean arrays. Only existing synapses ever change.
|
| 43 |
+
|
| 44 |
+
How this maps onto the paper:
|
| 45 |
+
|
| 46 |
+
* **Plasticity (Eq. 1).** The binary-weight rule flips a weight from an active input to a memory neuron with
|
| 47 |
+
a plateau, with probability 0.5: 0 becomes 1 and 1 becomes 0. The paper derives the 0.5 from the plateau's
|
| 48 |
+
time window: input in the inner part of the window potentiates a weight that is not yet at its maximum,
|
| 49 |
+
input in the outer part depresses a weight that is not yet at its minimum, and both parts are taken as
|
| 50 |
+
equally likely, so with probability 0.5 a weight is not updated.
|
| 51 |
+
* Every memory neuron receives a plateau independently with probability `f_q` for each new item. The default
|
| 52 |
+
`f_q` is 0.005.
|
| 53 |
+
* The paper notes that "BTSP does not depend on the firing of the postsynaptic neuron".
|
| 54 |
+
* Initial weights are a zero matrix, and each item is presented once.
|
| 55 |
+
* The paper also varies the LTD probability, which `flip_prob=(p_ltp, p_ltd)` allows.
|
| 56 |
+
* **Neurons.** Memory and input neurons are McCulloch-Pitts units. They fire when the weighted sum *exceeds* the
|
| 57 |
+
threshold, as here.
|
| 58 |
+
* **Thresholds (simplified here).** The paper uses grid search to set one absolute memory threshold for its
|
| 59 |
+
memory-trace experiments. For input completion, it sets both layers' thresholds by linear functions of the
|
| 60 |
+
average fraction of ones in the input, fitted in preliminary simulations. This module sets the memory
|
| 61 |
+
threshold proportional to the number of ones in the cue (within one cue condition every cue has the same
|
| 62 |
+
number of ones, so this is a linear function of that fraction with zero intercept) and the input-layer
|
| 63 |
+
threshold proportional to the number of active units in the memory trace.
|
| 64 |
+
* **Feedback.** Random feedback connections from memory to input units have the same density as the forward
|
| 65 |
+
ones (0.6 in the paper). They are trained in one step by a Hebbian-like rule: a weight is incremented when
|
| 66 |
+
both its memory unit and its input unit are 1, and saturates at one. Here the memory units' activity is the
|
| 67 |
+
trace of the stored pattern under the updated forward weights.
|
| 68 |
+
* **Recall.** As in the paper, input completion is one forward and one feedback pass with no iteration (the
|
| 69 |
+
paper produces it at the next time step after the cue; only its Hopfield comparison networks iterate).
|
| 70 |
+
|
| 71 |
+
Metrics:
|
| 72 |
+
|
| 73 |
+
* `overlap(a, b) = |a & b| / sqrt(|a| |b|)` is this module's recall metric, a cosine similarity. It is not the
|
| 74 |
+
paper's "overlap ratio" of two memory traces, which divides the common ones by the average number of ones
|
| 75 |
+
in a trace.
|
| 76 |
+
* `reconstruction_error(x, x', r) = HD(r, x) / HD(x, x')` is the paper's scaled reconstruction error. 0 is
|
| 77 |
+
perfect, and 1 is no better than the cue.
|
| 78 |
+
* `make_cue` deletes a fraction of the active bits. With `kind='flip'`, it also turns on the same number of
|
| 79 |
+
inactive bits.
|
| 80 |
+
|
| 81 |
+
Tests check these properties on cases with a known answer:
|
| 82 |
+
|
| 83 |
+
* With `plateau_prob = 1` and `flip_prob = 1`, a store sets exactly the connected synapses from active inputs.
|
| 84 |
+
The trace and the feedback weights equal a hand computation. Storing the same pattern again is then pure
|
| 85 |
+
depression and returns every forward weight to 0, while feedback weights never decrease.
|
| 86 |
+
* Without a plateau nothing changes, and synapses from inactive inputs never change. Weights stay boolean and
|
| 87 |
+
stay on existing synapses.
|
| 88 |
+
* On a 200 x 200 network, the measured flip rates match `p_ltp = 0.3` and `p_ltd = 0.8` to within ±0.02.
|
| 89 |
+
* **One-shot storage.** 10 patterns are each stored once (200 inputs, 20 active, 200 memory units, plateau
|
| 90 |
+
probability 0.1; means over 3 seeds and the 10 patterns).
|
| 91 |
+
* Every stored pattern evokes a non-empty memory trace, and a full cue reconstructs the pattern with overlap
|
| 92 |
+
above 0.95.
|
| 93 |
+
* With 20 %, 40 % and 60 % of the active bits deleted, the overlap degrades gradually (never rising by more
|
| 94 |
+
than 0.01 from one level to the next) and stays above 0.8.
|
| 95 |
+
* At every deletion level the mean reconstruction overlap beats the mean overlap of the degraded cue, and
|
| 96 |
+
cues with 30 % of their bits moved are also cleaned up.
|
| 97 |
+
* Storing 40 patterns instead of 10 lowers recall from 40 %-deleted cues by more than 0.1 (interference grows
|
| 98 |
+
with load). Cues that were never stored retrieve little: on average their reconstruction overlaps neither
|
| 99 |
+
the cue nor the closest stored pattern by more than 0.5.
|
| 100 |
+
* Each parameter (plateau probability, LTP and LTD probabilities, both thresholds, density, seed) changes what
|
| 101 |
+
is recalled.
|
| 102 |
+
|
| 103 |
+
## Baselines
|
| 104 |
+
|
| 105 |
+
* `WillshawMemory(input_dim, *, threshold=1.0)` is the auto-associative form of the clipped-Hebbian binary
|
| 106 |
+
memory of Willshaw, Buneman & Longuet-Higgins (1969).
|
| 107 |
+
* Storing sets `A_ii' = 1` for every pair of co-active units, including `i = i'`.
|
| 108 |
+
* Recall is `r_i = 1[(A c)_i >= threshold * |c|]`. `threshold = 1`, where every cue unit must agree, is the
|
| 109 |
+
classic rule as usually described.
|
| 110 |
+
* Tests: exact completion of half-deleted cues at threshold 1, tolerance of a wrong bit at threshold 0.8, and
|
| 111 |
+
saturation after an all-ones pattern.
|
| 112 |
+
* `RandomRecallControl(input_dim, active, seed=0)` ignores the cue and returns a seeded random pattern with
|
| 113 |
+
`active` ones. That is chance level, with expected overlap `active / input_dim`, which a test checks.
|
| 114 |
+
|
| 115 |
+
## Engine extension (`BTSPExtension`, id `btsp_memory`)
|
| 116 |
+
|
| 117 |
+
`BTSPExtension(memory_dim=64, *, active_fraction=0.25, density=0.6, plateau_prob=0.1, flip_prob=0.5,
|
| 118 |
+
threshold=0.35, feedback_threshold=0.5, gate=0.5, projection_dim=6, seed=0)` is a readout-only extension over
|
| 119 |
+
the binarised brain output.
|
| 120 |
+
|
| 121 |
+
* **Size.** `bind(engine)` copies `engine.n`, an integer up to 4096, and builds an empty `BTSPMemory` with that
|
| 122 |
+
many inputs. Units born later are ignored.
|
| 123 |
+
* **Binarising.** After each engine step, the output is turned into a pattern `x_t` with the top
|
| 124 |
+
`k = max(1, round(active_fraction * n))` units set (ties go to the lower index).
|
| 125 |
+
* **Features.** Recall happens *before* any store and gives three kinds of feature:
|
| 126 |
+
* `recall_overlap = overlap(x_t, r(z(x_t)))`, how familiar the current state is;
|
| 127 |
+
* `recall_confidence = min(1, |z(x_t)| / max(1, plateau_prob * memory_dim))`, the trace size relative to the
|
| 128 |
+
expected trace size;
|
| 129 |
+
* `projection_dim` fixed `+-1` projections of the trace, `P z / sqrt(max(1, |z|))`.
|
| 130 |
+
|
| 131 |
+
In total `feature_dim = 2 + projection_dim` (8 by default).
|
| 132 |
+
* **Storing.** Only when `ctx['learn']` is true, the pattern is stored one-shot when its salience
|
| 133 |
+
`max(min(|reward|, 1), 1 - recall_overlap)` exceeds `gate`. The plateau probability is scaled by that
|
| 134 |
+
salience. This novelty-and-reward gate is this module's design, not the paper's, whose plateaus are random.
|
| 135 |
+
* **What it does not touch.** The extension never changes the drive. It keeps no engine reference, and
|
| 136 |
+
`copy.deepcopy` gives an independent clone, including the plasticity random generator. With `ctx['learn']`
|
| 137 |
+
false it never stores; it counts `frozen_steps` instead. `reset()` clears the features and keeps the stored
|
| 138 |
+
memories.
|
| 139 |
+
* **Budget.** `parameter_count()` is the number of existing plastic synapses, forward plus feedback.
|
| 140 |
+
|
| 141 |
+
## Capacity benchmark (`run_capacity_benchmark`, id `btsp_memory_capacity`)
|
| 142 |
+
|
| 143 |
+
* **Patterns.** `patterns` random binary patterns with exactly `active` ones are stored once each, in order.
|
| 144 |
+
At `checkpoints` evenly spaced loads, `test_per_checkpoint` stored patterns are recalled from degraded cues
|
| 145 |
+
under every condition in `cue_kinds x cue_fractions` (delete and flip, 30 % and 50 %). Every arm sees the
|
| 146 |
+
same cues.
|
| 147 |
+
* **Metric.** The metric is the normalised overlap between the stored pattern and its reconstruction,
|
| 148 |
+
averaged over checkpoints and conditions (the mean of the capacity curve). Receipts also give the
|
| 149 |
+
reconstruction error per checkpoint and condition.
|
| 150 |
+
* **Arms.**
|
| 151 |
+
* `btsp`: `BTSPMemory` with `memory_dim = round(input_dim / (2 * density))`. Its forward plus feedback
|
| 152 |
+
synapses then match the Willshaw matrix's `input_dim**2` in expectation; receipts report the exact counts.
|
| 153 |
+
* `willshaw`: `WillshawMemory`.
|
| 154 |
+
* `random_recall`: chance level.
|
| 155 |
+
* `cue_only`: no memory; the degraded cue is its own reconstruction. This shows whether a memory improves on
|
| 156 |
+
the cue at all.
|
| 157 |
+
* **Fair tuning.** Free parameters are tuned per arm on separate seeds (1000 and 1001; 1000 in quick mode) by
|
| 158 |
+
the same metric. For BTSP these are the plateau probability, the threshold and the feedback threshold. For
|
| 159 |
+
Willshaw it is the threshold. BTSP gets the larger grid because it has three free parameters.
|
| 160 |
+
`tuning.<arm>.chosen_on_grid_edge` names any chosen value on a grid edge.
|
| 161 |
+
* **Verdict.** The verdict is a paired 95 % t interval over seeds, BTSP against Willshaw (higher is better).
|
| 162 |
+
Receipts also report each memory against `random_recall` and against `cue_only`. Per-seed diagnostics give
|
| 163 |
+
BTSP's fraction of forward weights at 1 and its mean trace size at each load.
|
| 164 |
+
* **Sizes.** The default uses 1,000 inputs with 50 active, 400 patterns, loads of 100, 200, 300 and 400, 64
|
| 165 |
+
tested patterns per load, and 833 memory units at density 0.6. Quick mode uses 400 inputs with 20 active,
|
| 166 |
+
120 patterns, loads of 30, 60, 90 and 120, 24 tested patterns per load, and 333 memory units.
|
| 167 |
+
|
| 168 |
+
## Lab experiment (`run_experiment`, id `btsp_memory`)
|
| 169 |
+
|
| 170 |
+
`harness.run_extension_experiment('btsp_memory', ...)` runs the NEUROWEAVE `delayed_recall` task (the target
|
| 171 |
+
is the input bit from two steps ago) with three arms:
|
| 172 |
+
|
| 173 |
+
* `baseline`: the unmodified engine and readout.
|
| 174 |
+
* `candidate`: the baseline plus `BTSPExtension` features.
|
| 175 |
+
* `control`: the baseline plus the same number of random leaky-trace features (the harness's capacity-matched
|
| 176 |
+
`random_trace` control).
|
| 177 |
+
|
| 178 |
+
All arms share seeds, streams and the readout protocol, and held-out streams are evaluated frozen. The headline
|
| 179 |
+
verdict is `improved` only if the candidate beats both the baseline and the control. The control matches the
|
| 180 |
+
candidate's readout feature count (8), not its stored numbers: for seed 0 the measured receipts report 6,544
|
| 181 |
+
(quick) or 12,688 (default size) extension state numbers for the candidate and 208 or 400 for the control.
|
| 182 |
+
|
| 183 |
+
The defaults are the harness's: seeds 0, 1, 2; held-out seeds 100, 101; 300 steps; 48 neurons; clustered
|
| 184 |
+
topology; no extra mechanisms. The extension uses its defaults. Quick mode uses the harness `QUICK_ARGS` sizes
|
| 185 |
+
(24 neurons, 24 steps, one 12-step held-out stream) with the caller's seeds. The extension keys and the harness
|
| 186 |
+
keys (`task`, `heldout_seeds`, `steps`, `heldout_steps`, `neurons`, `topology`, `mechanisms`) can be
|
| 187 |
+
overridden.
|
| 188 |
+
|
| 189 |
+
## Public API
|
| 190 |
+
|
| 191 |
+
```python
|
| 192 |
+
MODULE_ID = 'btsp_memory'; CAPACITY_ID = 'btsp_memory_capacity'
|
| 193 |
+
EXPERIMENTS = {'btsp_memory': run_experiment, 'btsp_memory_capacity': run_capacity_benchmark}
|
| 194 |
+
run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed receipt
|
| 195 |
+
run_capacity_benchmark(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed receipt
|
| 196 |
+
BTSPMemory(input_dim, memory_dim, *, density=0.6, plateau_prob=0.02, flip_prob=0.5, threshold=0.35,
|
| 197 |
+
feedback_threshold=0.5, seed=0)
|
| 198 |
+
.store(pattern, *, plateau_prob=None) -> {'plateau_units', 'ltp_flips', 'ltd_flips', 'trace_size',
|
| 199 |
+
'new_feedback_synapses'}
|
| 200 |
+
.drive(cue); .code(cue); .reconstruct(code); .recall(cue) -> {'code', 'reconstruction'}
|
| 201 |
+
.forward_mask; .feedback_mask; .synapse_count; .state_numbers; .weight_fractions(); .config()
|
| 202 |
+
.reset(); .export_state(); .import_state(state)
|
| 203 |
+
WillshawMemory(input_dim, *, threshold=1.0) # .store, .recall, .synapse_count, .export_state, .import_state
|
| 204 |
+
RandomRecallControl(input_dim, active, seed=0) # .store, .recall
|
| 205 |
+
BTSPExtension(memory_dim=64, *, active_fraction=0.25, density=0.6, plateau_prob=0.1, flip_prob=0.5,
|
| 206 |
+
threshold=0.35, feedback_threshold=0.5, gate=0.5, projection_dim=6, seed=0)
|
| 207 |
+
.binarise(output); .after_step(output, ctx); .features(); .telemetry(); .config(); .export_state(); .import_state(state)
|
| 208 |
+
overlap(a, b); hamming(a, b); reconstruction_error(target, cue, reconstruction)
|
| 209 |
+
make_cue(pattern, fraction, kind, rng); random_patterns(count, size, active, rng)
|
| 210 |
+
CAPACITY_DEFAULTS, CAPACITY_QUICK, CUE_KINDS, SOURCE
|
| 211 |
+
```
|
| 212 |
+
|
| 213 |
+
Every public function and constructor validates its input and raises `ValueError` before any state changes.
|
| 214 |
+
`export_state()` is JSON-safe: weights on existing synapses are stored as packed bits in base64, together with
|
| 215 |
+
the counters and the PCG64 state of the plasticity generator. `import_state` checks the configuration, the
|
| 216 |
+
exact bit lengths, the zero padding, the counters and the generator state before replacing anything, so a
|
| 217 |
+
failed import leaves the memory unchanged. After an import, further stores continue exactly as they would have
|
| 218 |
+
without the export. No global NumPy or torch random or thread state is touched.
|
| 219 |
+
|
| 220 |
+
## Connection to Sonapse
|
| 221 |
+
|
| 222 |
+
* **Not a live observer.** `btsp_memory` is not in `spec.OBSERVER_MODULE_IDS`.
|
| 223 |
+
* **Engine extension.** It influences nothing unless it is attached to a NEUROWEAVE engine with
|
| 224 |
+
`attach_extension`, as in the lab experiment. Even when attached, it only adds readout features. It never
|
| 225 |
+
changes the drive.
|
| 226 |
+
* **Standalone benchmark.** `run_capacity_benchmark` uses only the memories and synthetic patterns.
|
| 227 |
+
* **Defaults.** No Sonapse or NEUROWEAVE default, API or checkpoint format changes.
|
| 228 |
+
|
| 229 |
+
## Not implemented, and differences from the paper
|
| 230 |
+
|
| 231 |
+
* The paper's network sizes and sparsity. Its default is 25,000 inputs, 39,000 memory neurons, 0.5 % active
|
| 232 |
+
bits and a plateau probability of 0.005, so about 195 memory neurons receive a plateau for each item. In the
|
| 233 |
+
capacity benchmark, the tuned plateau probabilities give an expected 8.3 (default size) and 13.3 (quick mode)
|
| 234 |
+
plateau units per stored pattern, and the measured mean traces hold about 8–15 units.
|
| 235 |
+
* The paper's threshold procedures: grid search for an absolute memory threshold, and fitted linear functions
|
| 236 |
+
of the input's fraction of ones for input completion. Thresholds here are proportional to the active count.
|
| 237 |
+
* The time course of plateau potentials and the asymmetric time window. As in the paper's simplified rule, they
|
| 238 |
+
are summarised by the flip probability.
|
| 239 |
+
* The paper's analyses and comparisons: random projections, Hopfield networks, the earlier
|
| 240 |
+
postsynaptic-firing-dependent one-shot rule, repulsion of similar memory traces, and the line-drawing task.
|
| 241 |
+
The paper does not compare BTSP with a Willshaw memory; this module does.
|
| 242 |
+
* Forgetting in the feedback pathway. As in the paper, feedback weights only saturate, so under a long store
|
| 243 |
+
sequence they fill up (see the measured weight fractions below).
|
| 244 |
+
* The extension's salience gate and the plateau probability scaled by salience are this module's own design.
|
| 245 |
+
|
| 246 |
+
## Verified references
|
| 247 |
+
|
| 248 |
+
Each reference was checked on 2026-11-20.
|
| 249 |
+
|
| 250 |
+
1. Yujie Wu, Wolfgang Maass. **A simple model for Behavioral Time Scale Synaptic Plasticity (BTSP) provides
|
| 251 |
+
content addressable memory with binary synapses and one-shot learning.** *Nature Communications* 16, 342
|
| 252 |
+
(2025), published online 2 January 2025 (PMC record). doi:10.1038/s41467-024-55563-6,
|
| 253 |
+
https://doi.org/10.1038/s41467-024-55563-6 · PMC11695864 · PMID 39747916 (the identifiers were matched with
|
| 254 |
+
the PMC ID converter). The PMC record says the article was corrected, *Nat. Commun.* 16, 1150 (29 January
|
| 255 |
+
2025). The following were checked in the PMC full text:
|
| 256 |
+
* Eq. 1, applied "with probability 0.5" to inputs that arrive within the plateau's time window.
|
| 257 |
+
* The per-neuron, per-item plateau probability `f_q` (default 0.005), and that BTSP does not depend on
|
| 258 |
+
postsynaptic firing.
|
| 259 |
+
* The zero initial weights and the strict firing threshold.
|
| 260 |
+
* The grid-searched memory threshold, and the fitted linear threshold functions for input completion.
|
| 261 |
+
* The Hebbian-like, saturating feedback learning at density 0.6.
|
| 262 |
+
* The scaled reconstruction error `HD(r(x'), x) / HD(x, x')` and the overlap-ratio definition.
|
| 263 |
+
* The default sizes: m = 25,000, n = 39,000, f_w = 0.6, f_p = 0.005.
|
| 264 |
+
* Input completion is produced at the next time step after the cue (one pass); the Hopfield comparison
|
| 265 |
+
networks are iterated 100 times.
|
| 266 |
+
* Fig. 6D varies the LTD probability, and the main text points to Figs. S4–S5 for variants with a higher
|
| 267 |
+
LTD and a lower LTP probability.
|
| 268 |
+
|
| 269 |
+
The paper compares BTSP with random projections, Hopfield networks and an earlier one-shot rule that depends
|
| 270 |
+
on postsynaptic firing. Neither its text nor its reference list mentions Willshaw. The supplementary
|
| 271 |
+
material itself was not checked.
|
| 272 |
+
2. D. J. Willshaw, O. P. Buneman, H. C. Longuet-Higgins. **Non-Holographic Associative Memory.** *Nature*
|
| 273 |
+
222(5197), 960–962, June 1969 (Crossref). doi:10.1038/222960a0. Only the bibliographic record was verified;
|
| 274 |
+
the full text could not be opened in this build. The all-cue-units retrieval threshold (`threshold = 1`) is
|
| 275 |
+
taken from later descriptions of the Willshaw model and was not checked against the 1969 text.
|
| 276 |
+
|
| 277 |
+
## Measured results
|
| 278 |
+
|
| 279 |
+
All runs were measured on 2026-11-20 on Windows 11 on ARM64, with Python 3.12.10, NumPy 2.4 and one BLAS/OpenMP
|
| 280 |
+
thread (`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1`). Every call used its defaults apart from
|
| 281 |
+
`quick`, with seeds 0, 1, 2. Each quick run was made three times and gave the same receipt digest every time;
|
| 282 |
+
each default-size run was made once (earlier runs on the same day gave the same numbers). The tests also check
|
| 283 |
+
that a second run gives the same digest. The digest prefix is listed so a rerun on this setup can be compared;
|
| 284 |
+
another platform may round floating-point results differently. Wall-clock covers the whole call and is given
|
| 285 |
+
as the range over the runs. The machine was shared with other jobs, so wall-clock is only indicative.
|
| 286 |
+
|
| 287 |
+
| Run | Verdict | Key numbers | Digest | Wall-clock |
|
| 288 |
+
|---|---|---|---|---|
|
| 289 |
+
| `run_capacity_benchmark(quick=True)` | `worse` | Curve-mean overlap: btsp 0.693 / willshaw 0.873 / random 0.050 / cue only 0.686. btsp − willshaw −0.180, CI [−0.255, −0.105]; btsp − cue only +0.007, CI [−0.063, 0.078]. BTSP by load (30, 60, 90, 120): 0.794, 0.749, 0.656, 0.574; Willshaw: 0.848, 0.889, 0.899, 0.858. Chosen: BTSP plateau 0.04, threshold 0.4, feedback 0.65; Willshaw threshold 0.6; no grid-edge flags; synapse ratio 0.999. Mean trace size 9.5–15.1 units over seeds and loads | `6fc711b5` | 2.07–2.67 s |
|
| 290 |
+
| `run_experiment(quick=True)` | `no_detectable_difference` | Held-out accuracy 0.500 in all three arms (chance 0.500). The CI is degenerate. Seed 0: 20 stores in 24 steps | `7ff1f576` | 1.62–2.03 s |
|
| 291 |
+
| `run_capacity_benchmark()` | `worse` | Curve-mean overlap: btsp 0.666 / willshaw 0.703 / random 0.050 / cue only 0.686. btsp − willshaw −0.038, CI [−0.052, −0.023]; btsp − cue only −0.020, CI [−0.038, −0.003]; willshaw − cue only +0.017, CI [0.014, 0.020]. BTSP by load (100, 200, 300, 400): 0.813, 0.729, 0.622, 0.499; Willshaw: 0.626, 0.769, 0.799, 0.619. Chosen: BTSP plateau 0.01, threshold 0.3, feedback 0.65; Willshaw threshold 0.8; no grid-edge flags; synapse ratio 0.999. Seed 0: forward weights at 1 rise from 2.4 % to 9.1 % of synapses, and the mean trace grows from 7.7 to 10.7 units (7.6–11.5 over all seeds and loads) | `9f015b29` | 53.1 s |
|
| 292 |
+
| `run_experiment()` | `no_detectable_difference` | Held-out accuracy: baseline 0.558 / candidate 0.549 / control 0.561 (chance 0.517). Candidate − baseline −0.009, CI [−0.028, 0.010]; candidate − control −0.012, CI [−0.039, 0.014]. Seed 0: 202 stores in 300 steps; 36 % of forward and 81 % of feedback synapses at weight 1 | `3abe23be` | 20.0 s |
|
| 293 |
+
|
| 294 |
+
At the same synapse count and at these toy sizes, the BTSP memory recalled worse than a tuned Willshaw memory
|
| 295 |
+
on average over the capacity curve.
|
| 296 |
+
|
| 297 |
+
* **Reconstruction against the cue.** Averaged over loads, BTSP's reconstruction did not improve on the
|
| 298 |
+
degraded cue: no detectable difference in quick mode, and slightly worse at default size.
|
| 299 |
+
* **By load.** At the lowest default load, its mean overlap (0.813) was above both the cue (0.686) and
|
| 300 |
+
Willshaw (0.626), whose single threshold is tuned for the whole curve. At higher loads it fell below both.
|
| 301 |
+
Over the same loads the fraction of forward weights at 1 and the trace size grew (seed 0 above), which is
|
| 302 |
+
consistent with growing interference between stored patterns; this was not tested further.
|
| 303 |
+
* **Engine extension.** On `delayed_recall`, the BTSP familiarity features made no detectable difference to
|
| 304 |
+
the NEUROWEAVE readout. In the quick run every arm stays at chance, so it only checks that the pipeline runs.
|
| 305 |
+
In the default run the feedback pathway filled up: 81 % of feedback synapses were at weight 1 on seed 0.
|
| 306 |
+
|
| 307 |
+
A possible reason for the gap to the paper is scale. Here an expected 8.3 (default size) or 13.3 (quick mode)
|
| 308 |
+
memory units receive a plateau for each stored pattern, and the measured mean traces hold about 8–15 units. In
|
| 309 |
+
the paper's default network about 195 neurons receive a plateau for each item. This explanation was not
|
| 310 |
+
tested. These results are statements about this toy only. They do not test the paper's network sizes or
|
| 311 |
+
claims.
|
docs/frontier/modules/causal_emergence.md
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `causal_emergence`: effective information and causal emergence
|
| 2 |
+
|
| 3 |
+
Module file: `synapse/frontier/causal_emergence.py` · tests: `tests/test_frontier_causal_emergence.py` ·
|
| 4 |
+
experiment id: `causal_emergence` · live observer: `CausalEmergenceObserver` · kind: `analysis` ·
|
| 5 |
+
evidence tier: `synthetic_abstraction`.
|
| 6 |
+
|
| 7 |
+
The module computes **effective information** (EI) of transition probability matrices (TPMs), its
|
| 8 |
+
determinism/degeneracy decomposition, and **causal emergence** (CE): whether a coarse-grained (macro) description
|
| 9 |
+
of a system has more EI than the micro description. It is inspired by Hoel, Albantakis & Tononi (PNAS 2013) and
|
| 10 |
+
Hoel (Entropy 2017), and by the macro-vs-micro EI experiment of the sibling project `kai9987kai/SONAPSE-ORIGIN`
|
| 11 |
+
(`sonapse_origin/theories/causal_emergence.py`, which builds a TPM from a weight matrix and compares one fixed
|
| 12 |
+
pairing of states against a 0.05-bit threshold). The sibling project `kai9987kai/GhostInTheMachine` measures
|
| 13 |
+
emergence with the Psi criterion of Rosas et al. (2020) instead; its practice of reading an emergence statistic
|
| 14 |
+
against a matched null is what the nulls here follow. Nothing here measures consciousness, agency or biological
|
| 15 |
+
causation, and no claim is made that NEUROWEAVE brains "have" causal emergence.
|
| 16 |
+
|
| 17 |
+
## What it computes
|
| 18 |
+
|
| 19 |
+
**Effective information.** For a row-stochastic TPM `T` over `n` states and maximum-entropy (uniform)
|
| 20 |
+
interventions on the current state:
|
| 21 |
+
|
| 22 |
+
```
|
| 23 |
+
E_D = (1/n) sum_i T_i (effect distribution)
|
| 24 |
+
EI(T) = (1/n) sum_i D_KL(T_i || E_D) = H(E_D) - (1/n) sum_i H(T_i) [bits]
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
i.e. the mutual information between uniform interventions and their effects. Identity and permutation TPMs give
|
| 28 |
+
`EI = log2 n`; a TPM with identical rows gives `EI = 0`.
|
| 29 |
+
|
| 30 |
+
**Decomposition** (formulas as printed in Hoel 2017; Hoel et al. 2013 introduce the determinism and degeneracy
|
| 31 |
+
components of effectiveness), with `U` the uniform distribution:
|
| 32 |
+
|
| 33 |
+
```
|
| 34 |
+
determinism = (1/n) sum_i D_KL(T_i || U) / log2 n = (log2 n - mean_i H(T_i)) / log2 n
|
| 35 |
+
degeneracy = D_KL(E_D || U) / log2 n = (log2 n - H(E_D)) / log2 n
|
| 36 |
+
effectiveness = determinism - degeneracy, EI = log2(n) * effectiveness
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
The normalised terms are `None` for a one-state TPM.
|
| 40 |
+
|
| 41 |
+
**Estimation from data.** `transition_counts(states, n)` counts consecutive pairs of a state sequence, or, with
|
| 42 |
+
`next_states=`, interventional pairs `(s_t, s'_t)`. `estimate_tpm(C, alpha=1)` is additive smoothing
|
| 43 |
+
`T_ij = (C_ij + alpha) / (sum_k C_ik + alpha n)` (`alpha = 1`: Laplace). Every row receives `alpha n`
|
| 44 |
+
pseudo-counts, so with few transitions per state the estimate is pulled towards uniform rows and EI is shrunk,
|
| 45 |
+
more for a many-state micro TPM than for a few-state macro TPM.
|
| 46 |
+
|
| 47 |
+
**Coarse-graining.** A partition of the micro states into macro states (`labels`, one per micro state). The macro
|
| 48 |
+
TPM is the effect of intervening uniformly on the micro states of each macro state (Hoel et al. 2013):
|
| 49 |
+
|
| 50 |
+
```
|
| 51 |
+
T_M[A, B] = (1/|A|) sum_{i in A} sum_{j in B} T[i, j]
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
Two candidate families are searched exhaustively, with the micro description itself excluded (so CE can be
|
| 55 |
+
negative):
|
| 56 |
+
|
| 57 |
+
* `state_partition_candidates(n)` / `best_state_partition(T)`: every set partition of `3 <= n <= 10` states with
|
| 58 |
+
`2 <= m < n` blocks (restricted-growth strings; 4138 candidates for `n = 8`).
|
| 59 |
+
* `unit_sum_candidates(u)` / `best_unit_coarse_graining(T, u)`: for `2^u` binary micro states (`2 <= u <= 6`),
|
| 60 |
+
every partition of the `u` units into groups except all-singletons; each group's macro variable is its number
|
| 61 |
+
of active units (`m = prod_g (|g| + 1)` macro states; 202 candidates for `u = 6`).
|
| 62 |
+
|
| 63 |
+
All candidates of a family are evaluated in one sparse matrix product (`macro_ei_batch`), checked against a
|
| 64 |
+
direct `scipy.stats.entropy` computation in the tests.
|
| 65 |
+
|
| 66 |
+
**Causal emergence.** `CE = max_M EI(T_M) - EI(T)` over the candidates.
|
| 67 |
+
|
| 68 |
+
**Nulls.** Both nulls re-run the search for the best coarse-graining in every draw, so the selection of the
|
| 69 |
+
maximum is part of the null. Each reports `z = (CE - mean_null) / sd_null` and the one-sided rank p-value
|
| 70 |
+
`(1 + #{CE_null >= CE}) / (1 + draws)`.
|
| 71 |
+
|
| 72 |
+
* *Successor block permutation* (`successor_block_null`): the successor sequence `s_{1..T}` is block-permuted
|
| 73 |
+
(blocks of `round(T^(1/3))` steps by default) against the unchanged `s_{0..T-1}`. Visit counts and the successor
|
| 74 |
+
marginal are kept; lag-1 dependence is broken.
|
| 75 |
+
* *Independent units* (`independent_units_null`, binary-unit data only): each unit's bit sequence is circularly
|
| 76 |
+
shifted by its own random offset, which keeps each unit's occupancy and autocorrelation but makes the units
|
| 77 |
+
independent.
|
| 78 |
+
|
| 79 |
+
Neither null tests "the true macro EI exceeds the true micro EI". Because smoothing shrinks the micro TPM more
|
| 80 |
+
than a macro TPM, the estimated CE of *any* temporally dependent sequence with few transitions per micro state
|
| 81 |
+
lies above the successor null, including independent slow units whose exact CE is negative (measured below).
|
| 82 |
+
Against the independent-units null, a large `z` says that the coarse-graining gains from coordination between
|
| 83 |
+
units beyond what the units' own dynamics give.
|
| 84 |
+
|
| 85 |
+
## Live observer (`CausalEmergenceObserver`)
|
| 86 |
+
|
| 87 |
+
`CausalEmergenceObserver(n_units, *, seed=7, history=256, units=6, alpha=1.0, null_draws=19, block=None,
|
| 88 |
+
min_transitions=None, **params)`; `CausalEmergenceObserver.from_spec(n_units, spec, **params)` takes `seed`
|
| 89 |
+
and `history` from a `FrontierSpecV1`. The spec parameters of other observers (`sync_pairs`, `sae_features`,
|
| 90 |
+
`sae_k`, `fc_window`, `max_observed_units`, `observe_every`) are accepted and ignored; any other keyword, and
|
| 91 |
+
any out-of-range value, raises `ValueError`.
|
| 92 |
+
|
| 93 |
+
* `u = min(units, n_units)` units (a seeded, sorted sample when `n_units > units`) are binarised online: a value
|
| 94 |
+
is on when it is above the median of that unit's last `history` raw values (including the new one). A value
|
| 95 |
+
tied with the median is on when more of the window lies strictly below the median than above it, so a
|
| 96 |
+
discrete 0/1 unit that is on most of the time is binarised as itself rather than as constant 0 (a constant unit
|
| 97 |
+
is off). The `2^u` micro states of the last `history` observations are kept in a ring buffer, so transition
|
| 98 |
+
counts are bounded.
|
| 99 |
+
* `summary()` estimates the micro TPM from the buffered transitions (smoothing `alpha`) and reports micro EI with
|
| 100 |
+
determinism/degeneracy/effectiveness, the best count-per-group coarse-graining, its macro EI and
|
| 101 |
+
determinism/degeneracy, and `ce`. Once `min_transitions` transitions exist (default `min(32, history - 1)`) it
|
| 102 |
+
adds both nulls with `null_draws` draws each, seeded by `(seed, observed steps)`; the smallest attainable p is
|
| 103 |
+
`1 / (null_draws + 1)`. Results are a pure function of the buffered state and are cached per step, so they do
|
| 104 |
+
not depend on how often `summary()` is called.
|
| 105 |
+
* `summary()` keys: `module`, `evidence_tier`, `n_units`, `analysed_units`, `unit_sample`, `history`,
|
| 106 |
+
`micro_states`, `alpha`, `null_draws`, `min_transitions`, `observed_steps`, `buffered`, `transitions`,
|
| 107 |
+
`transitions_per_micro_state`, `visited_states`, `ei_micro`, `determinism_micro`, `degeneracy_micro`,
|
| 108 |
+
`effectiveness_micro`, `ei_macro`, `determinism_macro`, `degeneracy_macro`, `macro_partition` (groups of
|
| 109 |
+
observed-unit indices), `macro_states`, `ce`, `null_ready`, `null_block`, successor null `null_ce_mean`,
|
| 110 |
+
`null_ce_sd`, `ce_excess`, `ce_z`, `ce_p`, and independent-units null `indep_ce_mean`, `indep_ce_sd`,
|
| 111 |
+
`ce_excess_indep`, `ce_z_indep`, `ce_p_indep`. Metric values are `None` before the first transition and the
|
| 112 |
+
null fields are `None` until `null_ready`.
|
| 113 |
+
* `export_state()` / `import_state(state)` round-trip through JSON; `import_state` checks the schema, the
|
| 114 |
+
configuration, the unit sample, buffer shapes and finiteness, the counters and ring position, that nothing is
|
| 115 |
+
stored beyond the observed steps, and that stored states are the median-binarisation of the stored raw values
|
| 116 |
+
(all of them while every raw value is still buffered, the newest one afterwards) before replacing anything.
|
| 117 |
+
`reset()` returns to the empty state.
|
| 118 |
+
* Cost: one `summary()` with nulls evaluates `2 * null_draws + 1` TPMs against 202 candidates at `u = 6`
|
| 119 |
+
(about 0.4–0.9 s measured on 2026-11-20 at history 256–2048); `observe()` costs one median per unit. In its
|
| 120 |
+
per-step telemetry the frontier hub (`runtime.py`) runs full `causal_emergence` summaries only for the first
|
| 121 |
+
`heavy_every` (32) observed steps and on multiples of it.
|
| 122 |
+
|
| 123 |
+
**Reading the observer.** At the defaults (6 units, 64 micro states, history 256) there are about 4
|
| 124 |
+
transitions per micro state against 64 Laplace pseudo-counts per row: measured EI values are a small fraction of
|
| 125 |
+
the exact ones and the best grouping is not stable across seeds (on a six-unit pair-count copy ring, measured
|
| 126 |
+
2026-11-20: micro EI 0.03–0.05 bits against an exact 3.29 bits, best grouping varying with the seed at history
|
| 127 |
+
256, the pair grouping found for 6 of 6 seeds at history 1024 with `ce_z_indep` 16.6–23.3). Use fewer units, a
|
| 128 |
+
longer history or a smaller `alpha` when the estimate matters, and read `ce` against `ce_z_indep`.
|
| 129 |
+
|
| 130 |
+
## Lab experiment (`run_experiment`, `EXPERIMENTS = {'causal_emergence': run_experiment}`)
|
| 131 |
+
|
| 132 |
+
`run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides)` returns a sealed `kind: 'validation'` receipt
|
| 133 |
+
with `verdict` in `('pass', 'fail')` and 22 named checks.
|
| 134 |
+
|
| 135 |
+
Exact checks (no sampling):
|
| 136 |
+
|
| 137 |
+
| Check | Known answer |
|
| 138 |
+
|---|---|
|
| 139 |
+
| `identity_ei_equals_log2_n`, `permutation_ei_equals_log2_n`, `uniform_ei_is_zero` | `n` in `sizes` (2–32): `EI = log2 n`, determinism 1, degeneracy 0; uniform rows: EI, determinism and degeneracy 0 |
|
| 140 |
+
| `ei_equals_size_times_effectiveness` | `EI = log2(n) * effectiveness` on every example TPM |
|
| 141 |
+
| `hoel2017_M1_M2_M3_exact` | Hoel (2017) M1, M2, M3: 2, 1, 0 bits |
|
| 142 |
+
| `hoel2017_chain8_micro_closed_form` | 8-state chain (seven states mix uniformly, one absorbing): `EI = 3 - (7/8) log2 7 = 0.5436` bits |
|
| 143 |
+
| `hoel2017_chain8_matches_printed` | Printed EI 0.55 bits, effectiveness 0.18, CE 0.45 bits, within 0.01 / 0.005 / 0.01 (the closed form gives 0.5436 and 0.4564 bits, so two-decimal equality is not expected) |
|
| 144 |
+
| `hoel2017_chain8_search_finds_1_bit_seven_plus_one` | Exhaustive search over 4138 partitions finds the macro `{s1..s7}, {s8}` with 1 bit |
|
| 145 |
+
| `hoel2017_chain8_varied_matches_printed` | Unequal-row variant: printed 0.81 bits micro, 1 bit macro, same partition |
|
| 146 |
+
| `hoel2017_channel4_matches_printed` | 4-state channel: printed EI 0.81 bits, `H(X|Y)` 1.19 bits, macro code 1 bit with `{x1, x2, x3}, {x4}` |
|
| 147 |
+
| `and_gate_network_matches_printed` | Six AND gates in three pairs, each pair reading the next (wiring reconstructed from the text of Hoel et al. 2013 / Hoel 2017): micro EI 2.43 bits (closed form `3 H(1/4, 3/4)`), determinism 1, degeneracy 0.59, effectiveness 0.41; the pair-AND macro is three COPY elements with 3 bits; CE 0.57 bits |
|
| 148 |
+
| `weakly_symmetric_tpm_has_no_emergence` | Noisy permutations `(1 - e) P + e / n` (n = 5, 8): no partition has CE > 0 (uniform inputs achieve the capacity of a weakly symmetric channel) |
|
| 149 |
+
| `unit_pair_copy_exact_ce_positive_for_pair_counts` | Constructed six-unit ring whose pair *counts* copy the next pair's count (noise 0.1, count 1 realised by either unit): best count-per-group grouping is the three pairs, exact CE > 0 |
|
| 150 |
+
| `unit_independent_exact_ce_negative` | Six independent units that keep their state with probability 0.9: micro EI `6 (1 - H(0.9))`, every grouping has CE < 0 |
|
| 151 |
+
|
| 152 |
+
Sampled checks (every seed):
|
| 153 |
+
|
| 154 |
+
| Check | Criterion |
|
| 155 |
+
|---|---|
|
| 156 |
+
| `estimated_tpm_recovers_ei_and_ce` | Laplace-smoothed TPM from `estimation_samples` interventional samples of the 8-state chain: micro EI and CE (seven-plus-one) within `estimation_tolerance` (0.05) |
|
| 157 |
+
| `iid_null_false_positive_rate_at_most_0.25`, `iid_null_mean_z_within_1` | i.i.d. 8-state sequences: successor-null `p <= 0.05` in at most 25 % of replicates, mean `z` within ±1 (CE relative to the null is about 0) |
|
| 158 |
+
| `noisy_chain_ce_positive_and_above_successor_null` | Ergodic noisy version of the 8-state chain (noise 0.1, exact CE 0.278 bits for seven-plus-one): estimated CE > 0, `z > 3`, `p <= 0.05` |
|
| 159 |
+
| `permutation_control_ce_negative_and_not_above_successor_null` | Noisy 8-state permutation of the same length (temporally dependent, exact CE ≤ 0): estimated CE < 0, `p > 0.05` |
|
| 160 |
+
| `unit_pair_copy_above_independent_units_null_with_pairs_recovered` | Six units sampled from the pair-count ring: independent-units `z > 3`, `p <= 0.05`, pair grouping recovered |
|
| 161 |
+
| `unit_independent_units_null_calibrated` | Independent slow units: independent-units null flags at most half of the replicates, mean `z` within ±2 |
|
| 162 |
+
| `neuroweave_values_finite` | The descriptive part is finite |
|
| 163 |
+
|
| 164 |
+
How often the successor null flags the independent slow units is reported (`independent_successor_null_*`),
|
| 165 |
+
not checked: it is the documented bias above.
|
| 166 |
+
|
| 167 |
+
**NEUROWEAVE report (descriptive).** For each mechanism set (default `baseline = ()` and
|
| 168 |
+
`dynamics = (sparse_code, synaptic_delays, membrane_dynamics)`) and seed, a frozen engine (`learn=False`,
|
| 169 |
+
`clustered` topology) runs on the task stream; after burn-in a `CausalEmergenceObserver` over `units = 4` output
|
| 170 |
+
units (16 micro states, chosen so the run gives about 11 (quick) or 34 (default) transitions per micro state)
|
| 171 |
+
reports EI, CE and both nulls. No verdict is drawn from these values.
|
| 172 |
+
|
| 173 |
+
The receipt also holds `config`, `estimated_cost` (TPM evaluations of each part, engine steps),
|
| 174 |
+
`measured_wallclock_s` (excluded from the digest) and `notes`.
|
| 175 |
+
|
| 176 |
+
## Public API
|
| 177 |
+
|
| 178 |
+
`MODULE_ID`, `CausalEmergenceObserver`, `entropy_bits`, `as_tpm`, `effective_information`, `ei_decomposition`,
|
| 179 |
+
`transition_counts`, `estimate_tpm`, `median_binarize`, `encode_bits`, `decode_states`, `coarse_grain_tpm`,
|
| 180 |
+
`set_partitions`, `unit_sum_labels`, `unit_sum_candidates`, `state_partition_candidates`, `macro_ei_batch`,
|
| 181 |
+
`best_state_partition`, `best_unit_coarse_graining`, `causal_emergence`, `successor_block_null`,
|
| 182 |
+
`independent_units_null`, `hoel2017_examples`, `and_gate_network`, `pair_count_copy_tpm`,
|
| 183 |
+
`noisy_permutation_tpm`, `independent_flip_tpm`, `PRINTED_VALUES`, `run_experiment`, `EXPERIMENTS`.
|
| 184 |
+
All randomness uses `numpy.random.default_rng(seed + offset)`; no global NumPy or torch state is touched
|
| 185 |
+
(tested).
|
| 186 |
+
|
| 187 |
+
## Connection to Sonapse
|
| 188 |
+
|
| 189 |
+
* The live observer reports EI/CE of a few units of the running brain without touching it (frontier observer
|
| 190 |
+
hub, `causal_emergence` in `FrontierSpecV1.modules`).
|
| 191 |
+
* The lab experiment runs NEUROWEAVE engines through `neuroweave.experiments.make_spec` and
|
| 192 |
+
`neuroweave.tasks.make_stream`; the successor null reuses `connectomics.block_permutation`.
|
| 193 |
+
|
| 194 |
+
## Not implemented
|
| 195 |
+
|
| 196 |
+
* Only uniform (maximum-entropy) interventions; no other intervention distributions, no "black-boxing" or
|
| 197 |
+
removal of units, no temporal coarse-graining, no search over partitions of more than 10 states or of more
|
| 198 |
+
than 6 binary units.
|
| 199 |
+
* No integrated information (Phi) and no Rosas et al. Psi / synergy-based emergence measures.
|
| 200 |
+
* TPMs are estimated from observational sequences with additive smoothing; there is no bias correction of EI.
|
| 201 |
+
* The six-AND-gate wiring is reconstructed from the papers' text; the figure itself was not used.
|
| 202 |
+
|
| 203 |
+
## Verified references
|
| 204 |
+
|
| 205 |
+
Checked on 2026-11-20 (Crossref metadata; PMC full text for the 2013 paper; the arXiv v1 text of the 2017 paper
|
| 206 |
+
for every printed value used above).
|
| 207 |
+
|
| 208 |
+
* Erik P. Hoel, Larissa Albantakis, Giulio Tononi. **Quantifying causal emergence shows that macro can beat
|
| 209 |
+
micro.** *Proceedings of the National Academy of Sciences* 110(49), 19790–19795, issue of 3 December 2013
|
| 210 |
+
(online 18 November 2013). <https://doi.org/10.1073/pnas.1314922110> — EI as the mutual information between
|
| 211 |
+
uniform interventions and effects, macro interventions by averaging over grouped micro states; Fig. 4 values:
|
| 212 |
+
micro EI 2.43 bits, effectiveness 0.4, determinism coefficient 1, degeneracy coefficient 0.6, macro 3 bits,
|
| 213 |
+
CE 0.57 bits.
|
| 214 |
+
* Erik P. Hoel. **When the Map Is Better Than the Territory.** *Entropy* 19(5), 188, 26 April 2017.
|
| 215 |
+
<https://doi.org/10.3390/e19050188> (preprint arXiv:1612.09592, v1 of 30 December 2016) — determinism,
|
| 216 |
+
degeneracy, effectiveness and `EI = size * eff`; M1/M2/M3 (2, 1, 0 bits); the 8-state chain (eff 0.18,
|
| 217 |
+
0.55 bits, macro 1 bit, CE 0.45 bits); its unequal-row variant (0.81 bits); the AND-gate network (2.43 bits,
|
| 218 |
+
eff 0.41, degeneracy 0.59, macro 3 bits); the channel example (`H(X|Y)` 1.19 bits, EI 0.81 bits, macro 1 bit).
|
| 219 |
+
* Fernando E. Rosas, Pedro A. M. Mediano, Henrik J. Jensen, Anil K. Seth, Adam B. Barrett, Robin L.
|
| 220 |
+
Carhart-Harris, Daniel Bor. **Reconciling emergences: An information-theoretic approach to identify causal
|
| 221 |
+
emergence in multivariate data.** *PLOS Computational Biology* 16(12), e1008289, 21 December 2020.
|
| 222 |
+
<https://doi.org/10.1371/journal.pcbi.1008289> — the Psi criterion used by GhostInTheMachine; not implemented
|
| 223 |
+
here.
|
| 224 |
+
* Sibling projects: `kai9987kai/SONAPSE-ORIGIN` and `kai9987kai/GhostInTheMachine` (read-only clones; ideas,
|
| 225 |
+
not code, reused).
|
| 226 |
+
|
| 227 |
+
## Measured results
|
| 228 |
+
|
| 229 |
+
Measured on 2026-11-20, Windows 11 on ARM64, Python 3.12, NumPy 2.4, one BLAS thread
|
| 230 |
+
(`OPENBLAS_NUM_THREADS=1`), seeds 0, 1, 2, on a machine shared with other jobs (wall-clock varies with load).
|
| 231 |
+
|
| 232 |
+
| Run | Verdict | Key numbers | Wall-clock |
|
| 233 |
+
|---|---|---|---|
|
| 234 |
+
| `run_experiment(quick=True)` | `pass` (22/22) | Exact: chain8 0.5436 → 1.000 bits (CE 0.4564, 4138 partitions), variant 0.8059 → 1.000, channel 0.8113 → 1.000 (`H(X|Y)` 1.1887), AND gates 2.4338 → 3.000 (CE 0.5662, degeneracy 0.5944); noisy permutations best CE −0.162 (n = 5) and −0.103 (n = 8); pair-count ring exact CE +0.207 with the pairs, independent units −0.280. Estimation (4000 samples): EI error 0.023–0.027, CE error 0.035–0.039. i.i.d. null: 0 of 6 replicates flagged, mean z −0.34. Noisy chain (384 steps): CE 0.151 / 0.159 / 0.212 (exact 0.278), z 38.7–67.9, p 0.025 (39 draws). Permutation control: CE −0.102 to −0.143, p 1.0. Units (512 steps, 19 draws): pairs recovered 3/3, min independent-units z 11.2; independent units flagged 0/3 by the independent-units null (mean z −0.69) but 3/3 by the successor null (mean z 8.26) | 7.3 s (validation 4.2 s, NEUROWEAVE 3.0 s) on a lighter-loaded re-run; 14.4 s (pytest) to 24.6 s (standalone; validation 14.7 s, NEUROWEAVE 9.8 s) under load. Two runs in one process gave the same digest |
|
| 235 |
+
| `run_experiment()` | `pass` (22/22) | Estimation (16000 samples): EI error 0.008–0.009, CE error 0.012. i.i.d. null: 1 of 30 replicates flagged, mean z 0.003. Noisy chain (512 steps): CE 0.151 / 0.169 / 0.223, z 47.7–79.6, p 0.005 (199 draws). Permutation control: CE −0.090 to −0.160, p 1.0. Units (1024 steps, 49 draws, 4 replicates): pairs recovered 12/12, min z 19.6; independent units flagged 2/12 by the independent-units null (mean z 0.33), 12/12 by the successor null (mean z 7.87) | 133.5 s (validation 111.7 s, NEUROWEAVE 21.8 s) |
|
| 236 |
+
|
| 237 |
+
NEUROWEAVE (descriptive; 4 units, `clustered`, means over seeds):
|
| 238 |
+
|
| 239 |
+
* quick (24 neurons, 200 steps, 24 burn-in, 175 transitions): `baseline` micro EI 0.257, macro 0.308, CE 0.051,
|
| 240 |
+
independent-units z 4.96 (per-seed p 0.05 / 0.10 / 0.15); `dynamics` micro EI 0.223, macro 0.236, CE 0.013,
|
| 241 |
+
z 2.53 (p 0.05 / 0.30 / 0.05).
|
| 242 |
+
* default (32 neurons, 600 steps, 50 burn-in, 549 transitions): `baseline` micro EI 0.745, macro 0.764,
|
| 243 |
+
CE 0.019, independent-units z 2.45; `dynamics` micro EI 0.684, macro 0.665, CE −0.019, z 1.13.
|
| 244 |
+
|
| 245 |
+
The sign of the NEUROWEAVE CE changes between the quick and default sizes, and per-seed p-values are mostly at
|
| 246 |
+
or above the smallest attainable value; these numbers do not show causal emergence in NEUROWEAVE brains or a
|
| 247 |
+
difference between the mechanism sets.
|
docs/frontier/modules/connectomics.md
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `connectomics`: structural, functional and effective connectivity
|
| 2 |
+
|
| 3 |
+
Module file: `synapse/frontier/connectomics.py` · tests: `tests/test_frontier_connectomics.py` ·
|
| 4 |
+
experiment id: `connectomics` · live observer: `ConnectivityObserver` · kind: `analysis` ·
|
| 5 |
+
evidence tier: `synthetic_abstraction`.
|
| 6 |
+
|
| 7 |
+
The module keeps three kinds of connectivity apart, as the sibling project `kai9987kai/SONAPSE-CONNECTOME`
|
| 8 |
+
does (`sonapse_connectome/connectome/functional.py`, `effective.py`): **structure** (the synapse table of a
|
| 9 |
+
NEUROWEAVE brain), **function** (statistical dependence between unit activities) and **effective connectivity**
|
| 10 |
+
(lagged, directed, predictive influence). It re-implements those ideas for NEUROWEAVE activity and checks every
|
| 11 |
+
estimator on a synthetic process whose answer is known before it is applied to a brain. It is a computational
|
| 12 |
+
abstraction: the "structure" is a toy synapse table and the "function" is the activity of abstract units, not
|
| 13 |
+
imaging data, and nothing here is evidence of biological fidelity.
|
| 14 |
+
|
| 15 |
+
## What it computes
|
| 16 |
+
|
| 17 |
+
**Functional connectivity (FC).** For a `(T, n)` activity array:
|
| 18 |
+
|
| 19 |
+
* Pearson FC `R_ij = corr(x_i, x_j)` and Spearman FC (Pearson correlation of per-unit ranks, average ranks for
|
| 20 |
+
ties). Zero-variance units get zero rows/columns and a zero diagonal entry. Rescaling each channel into
|
| 21 |
+
different measurement units preserves its Pearson and partial correlations.
|
| 22 |
+
* Partial correlation from the ridge-regularised precision of the correlation matrix,
|
| 23 |
+
`Omega = (R + ridge I)^-1`, `P_ij = -Omega_ij / sqrt(Omega_ii Omega_jj)` (unit diagonal).
|
| 24 |
+
`partial_from_covariance(cov, ridge=0)` is exact and raises `ValueError` on a singular matrix;
|
| 25 |
+
`partial_correlation(X, ridge=1e-2)` is the sample version.
|
| 26 |
+
|
| 27 |
+
For a Gaussian chain `x -> y -> z` (`y = a x + e`, `z = a y + e`, unit noise) the precision matrix is
|
| 28 |
+
`[[1 + a^2, -a, 0], [-a, 1 + a^2, -a], [0, -a, 1]]`, so the exact partial correlations are
|
| 29 |
+
`P_xy = a / (1 + a^2)`, `P_yz = a / sqrt(1 + a^2)` and `P_xz = 0`, while the Pearson correlation
|
| 30 |
+
`R_xz = a^2 / sqrt(a^2 (a^2 + 1) + 1)` is not zero. The tests and the lab use this as the known answer.
|
| 31 |
+
|
| 32 |
+
**Dynamic FC (dFC).** Pearson FC in sliding rectangular windows (`window`, `step`); the upper triangles of the
|
| 33 |
+
window matrices are clustered with a deterministic k-means (Lloyd iterations, D²-weighted seeding,
|
| 34 |
+
`n_init` restarts, empty clusters re-seeded, labels in order of first appearance) for `k = 2 .. k_max`, and the
|
| 35 |
+
`k` with the largest mean silhouette width (Rousseeuw, 1987) wins. If no `k` reaches `min_silhouette`
|
| 36 |
+
(a heuristic default of 0.25) or there are fewer than three windows, the series is reported as one FC state.
|
| 37 |
+
Dwell times are run lengths of the window-state sequence (in windows and in samples, `x step`), with occupancy
|
| 38 |
+
and the number of state transitions.
|
| 39 |
+
|
| 40 |
+
**Effective connectivity (EC).** A ridge VAR(1) with intercepts,
|
| 41 |
+
`A = argmin_A sum_t ||x_{t+1} - A x_t||^2 + lambda ||A||_F^2`, `lambda = ridge * (T - 1)`, on (optionally z-scored)
|
| 42 |
+
series; `A[target, source]`. Significance comes from a **per-target conditional block-permutation null**: for
|
| 43 |
+
each draw, the past of all sources is block-permuted jointly in time (blocks of `round((T-1)^(1/3))` steps by
|
| 44 |
+
default, at least 2), except that each target keeps its own unpermuted past; every target's ridge regression is
|
| 45 |
+
refit (all targets in one batched solve). Each edge gets `z = (A - mean_null) / sd_null`, a two-sided normal
|
| 46 |
+
p-value and a rank p-value `(1 + #{|null - mean| >= |A - mean|}) / (1 + draws)`; the mask is
|
| 47 |
+
Benjamini-Hochberg at FDR `alpha` over the off-diagonal edges. This is lagged predictive (Granger-style)
|
| 48 |
+
influence, not an interventional effect.
|
| 49 |
+
|
| 50 |
+
**Structure and coupling.**
|
| 51 |
+
|
| 52 |
+
* `structural_matrix(n, src, dst, weight)`: dense `W[src, dst]` from an edge list (duplicates summed, `|w|` by
|
| 53 |
+
default, diagonal zeroed).
|
| 54 |
+
* `weighted_communicability(S) = exp(D^-1/2 S D^-1/2)`, `D = diag(sum_k S_ik)`, the weighted communicability
|
| 55 |
+
of Crofts & Higham (2009) (Estrada & Hatano, 2008, for the unweighted version); isolated nodes keep zero rows.
|
| 56 |
+
* `structure_function_coupling(S, FC)`: Spearman correlation over node pairs `i < j` between symmetrised
|
| 57 |
+
structure and FC (all pairs and structurally connected pairs, signed and absolute FC), and the same for
|
| 58 |
+
communicability, which also credits indirect walks; in the spirit of Honey et al. (2009).
|
| 59 |
+
* `modularity(W, labels)`: Newman-Girvan `Q = (1/2m) sum_ij (W_ij - k_i k_j / 2m) [c_i = c_j]`.
|
| 60 |
+
* `fc_communities(FC)`: leading-eigenvector communities (Newman, 2006) of the positive part of FC by
|
| 61 |
+
recursive bisection with the generalised modularity matrix `B^(g)_ij = B_ij - delta_ij sum_{l in g} B_il`,
|
| 62 |
+
without vertex-moving refinement, so the reported modularity is a proxy (a lower bound on the maximum).
|
| 63 |
+
|
| 64 |
+
## Live observer (`ConnectivityObserver`)
|
| 65 |
+
|
| 66 |
+
`ConnectivityObserver(n_units, *, seed=7, history=256, window=None, max_units=32, k_max=4, ec_null_draws=31,
|
| 67 |
+
ridge=0.05, alpha=0.05, min_silhouette=0.25, **params)`; `ConnectivityObserver.from_spec(n_units, spec)` takes
|
| 68 |
+
`seed`, `history` and `fc_window` (clipped to `history`) from a `FrontierSpecV1`. `window` defaults to 128; the
|
| 69 |
+
spec name `fc_window` is accepted as the same parameter (a conflicting pair raises `ValueError`), and the spec
|
| 70 |
+
parameters of other observers (`sync_pairs`, `sae_features`, `sae_k`, `max_observed_units`, `observe_every`)
|
| 71 |
+
are accepted and ignored; any other keyword raises `ValueError`.
|
| 72 |
+
|
| 73 |
+
* A seeded, sorted subset of at most `max_units` units is copied into a ring buffer of `history` rows;
|
| 74 |
+
`observe(x)` validates `x` (1-D, length `n_units`, finite) before touching any state and never writes to it.
|
| 75 |
+
* Metrics are recomputed once `window` rows exist and then every `max(8, window // 4)` observations: static FC
|
| 76 |
+
and EC on the last `window` rows (non-constant units only), dFC on the whole buffer with windows of
|
| 77 |
+
`max(8, window // 4)` rows and half-window steps. The EC null is seeded by `(seed, observed steps)`, so results
|
| 78 |
+
do not depend on how often `summary()` is called.
|
| 79 |
+
* `summary()` keys: `module`, `evidence_tier`, `n_units`, `analysed_units`, `unit_sample`, `history`, `window`,
|
| 80 |
+
`recompute_every`, `observed_steps`, `buffered`, `ready`, `computed_at`, `rows`, `constant_units`,
|
| 81 |
+
`mean_abs_fc`, `fc_modularity`, `fc_communities`, `dfc_window`, `dfc_windows`, `dfc_states`,
|
| 82 |
+
`dfc_silhouette`, `dfc_mean_dwell_windows`, `dfc_mean_dwell_steps`, `dfc_transitions`, `ec_density`,
|
| 83 |
+
`ec_significant` and `ec_top_edges` (at most five `{source, target, weight, z, significant}` records, by
|
| 84 |
+
`|z|`). Values are `None` until the first recompute. Unit indices refer to positions in the observed vector.
|
| 85 |
+
* `export_state()` / `import_state(state)` round-trip through JSON; `import_state` validates the schema, the
|
| 86 |
+
configuration, the unit sample, the buffer (shape, finiteness, zeros beyond the observed steps), the recompute
|
| 87 |
+
schedule and every cached metric before replacing anything. `reset()` returns to the empty state.
|
| 88 |
+
|
| 89 |
+
The observer runs inside the frontier observer hub (`synapse/frontier/runtime.py`) when `connectomics` is in
|
| 90 |
+
`FrontierSpecV1.modules`; it is read-only and never writes into the brain or any shared RNG.
|
| 91 |
+
|
| 92 |
+
## Lab experiment (`run_experiment`, `EXPERIMENTS = {'connectomics': run_experiment}`)
|
| 93 |
+
|
| 94 |
+
`run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides)` returns a sealed `kind: 'validation'` receipt
|
| 95 |
+
with `verdict` in `('pass', 'fail')` and nine named checks, each required for every seed:
|
| 96 |
+
|
| 97 |
+
| Check | Known answer |
|
| 98 |
+
|---|---|
|
| 99 |
+
| `var_support_auroc_above_0.9` | Sparse stable VAR(1) (`var_units = 8`, edge probability 0.15, off-diagonal weights `±U(0.25, 0.5)`, self-coupling `U(0.2, 0.5)`, spectral radius ≤ 0.8): AUROC of `|A_hat|` for the true support > 0.9 |
|
| 100 |
+
| `var_sign_accuracy_at_least_0.9` | Signs of the estimated true edges |
|
| 101 |
+
| `var_mask_pooled_precision_at_least_0.8` | Precision of the BH mask pooled over seeds |
|
| 102 |
+
| `chain_partials_match_exact_values` | Gaussian chain `x -> y -> z` (`a = 0.8`): partials within `4 / sqrt(T)` of the exact values above, `P_xz` = 0 |
|
| 103 |
+
| `chain_fc_xz_clearly_nonzero` | `|R_xz| > 0.3` (the indirect link FC cannot remove) |
|
| 104 |
+
| `switching_two_states_recovered` | Six units alternating between two covariance states (blocks of 150 samples, within-state correlation 0.8 in one half of the units): dFC finds 2 states |
|
| 105 |
+
| `switching_pure_window_accuracy_at_least_0.9` | Label accuracy on windows that lie inside one block (up to label swap) |
|
| 106 |
+
| `stationary_control_single_state` | Same length, stationary, with the averaged covariance: dFC reports 1 state |
|
| 107 |
+
| `neuroweave_values_finite` | The descriptive part below is finite |
|
| 108 |
+
|
| 109 |
+
Then, for each topology (quick: `clustered`, `ring_lattice`, `hub_skewed`; default adds `multi_region`) and
|
| 110 |
+
seed, a frozen NEUROWEAVE engine (`learn=False`, so the synapse table that generates the activity stays fixed)
|
| 111 |
+
runs on the task stream; after burn-in the module reports structure metrics, mean |FC| and |partial|, the FC
|
| 112 |
+
modularity proxy, structure-function and communicability-function coupling, EC density, the AUROC of `|A_hat|`
|
| 113 |
+
against the synapse table, the fraction of significant EC edges that sit on a synapse, sign agreement, and the
|
| 114 |
+
dFC state count. This part is descriptive: no verdict is drawn from it beyond finiteness.
|
| 115 |
+
|
| 116 |
+
The receipt also holds `config`, `estimated_cost` (engine steps, ridge solves of the nulls, FC windows),
|
| 117 |
+
`measured_wallclock_s` (excluded from the digest) and `notes`.
|
| 118 |
+
|
| 119 |
+
## Public API
|
| 120 |
+
|
| 121 |
+
`MODULE_ID`, `ConnectivityObserver`, `pearson_fc`, `spearman_fc`, `partial_correlation`,
|
| 122 |
+
`partial_from_covariance`, `precision_to_partial`, `sliding_window_fc`, `kmeans`, `silhouette_score`,
|
| 123 |
+
`dwell_statistics`, `dynamic_fc_states`, `var1_fit`, `block_permutation`, `var1_permutation_null`,
|
| 124 |
+
`benjamini_hochberg`, `effective_connectivity`, `auroc`, `structural_matrix`, `weighted_communicability`,
|
| 125 |
+
`structure_function_coupling`, `modularity`, `fc_communities`, `run_experiment`, `EXPERIMENTS`.
|
| 126 |
+
All randomness uses `numpy.random.default_rng(seed + offset)`; inputs are validated with `ValueError`.
|
| 127 |
+
`block_permutation` is shared with `causal_emergence`.
|
| 128 |
+
|
| 129 |
+
## Connection to Sonapse
|
| 130 |
+
|
| 131 |
+
* The live observer gives the workbench FC, dFC and EC summaries of the running brain without touching it.
|
| 132 |
+
* The lab experiment uses `neuroweave.experiments.make_spec` / `engine_topology` and
|
| 133 |
+
`neuroweave.topology.topology_metrics`, so the structural side is the engine's own synapse table.
|
| 134 |
+
|
| 135 |
+
Differences from SONAPSE-CONNECTOME: that project computes partial correlation from a shrinkage covariance,
|
| 136 |
+
labels dFC "states" by quantile bins of the mean |FC| of each window, and fits a ridge lagged regression without
|
| 137 |
+
intercepts or a significance test. Here dFC states are clustered with k-means and a silhouette criterion, EC has
|
| 138 |
+
intercepts, a conditional permutation null and FDR control, and every estimator has a known-answer check.
|
| 139 |
+
|
| 140 |
+
## Not implemented
|
| 141 |
+
|
| 142 |
+
* No imaging data, haemodynamic model or parcellation; no dynamic causal modelling; EC is a single-lag linear
|
| 143 |
+
model (no higher-order lags, no nonlinear or interventional EC).
|
| 144 |
+
* The dFC pipeline is in the spirit of Allen et al. (2014) but simpler: they used tapered windows (a 22-TR
|
| 145 |
+
rectangle convolved with a Gaussian), graphical-LASSO regularised covariance per window, k-means with the L1
|
| 146 |
+
distance and the elbow criterion for k (k = 7); here windows are rectangular, FC is plain Pearson, k-means is
|
| 147 |
+
Euclidean and k is chosen by the mean silhouette with a 0.25 floor (a heuristic, not a test).
|
| 148 |
+
* The FC community split has no vertex-moving refinement (a modularity proxy).
|
| 149 |
+
* The observer only analyses up to `max_units` units and recomputes on a fixed schedule.
|
| 150 |
+
|
| 151 |
+
## Verified references
|
| 152 |
+
|
| 153 |
+
Checked on 2026-11-20 (Crossref metadata and the publishers' or PMC pages).
|
| 154 |
+
|
| 155 |
+
* Christopher J. Honey, Olaf Sporns, Leila Cammoun, Xavier Gigandet, Jean-Philippe Thiran, Reto Meuli, Patric
|
| 156 |
+
Hagmann. **Predicting human resting-state functional connectivity from structural connectivity.**
|
| 157 |
+
*PNAS* 106(6), 2035–2040, 10 February 2009. <https://doi.org/10.1073/pnas.0811168106>
|
| 158 |
+
* Elena A. Allen, Eswar Damaraju, Sergey M. Plis, Erik B. Erhardt, Tom Eichele, Vince D. Calhoun. **Tracking
|
| 159 |
+
Whole-Brain Connectivity Dynamics in the Resting State.** *Cerebral Cortex* 24(3), 663–676, March 2014
|
| 160 |
+
(online 11 November 2012). <https://doi.org/10.1093/cercor/bhs352>
|
| 161 |
+
* Ernesto Estrada, Naomichi Hatano. **Communicability in complex networks.** *Physical Review E* 77(3), 036111,
|
| 162 |
+
March 2008. <https://doi.org/10.1103/PhysRevE.77.036111>
|
| 163 |
+
* Jonathan J. Crofts, Desmond J. Higham. **A weighted communicability measure applied to complex brain
|
| 164 |
+
networks.** *Journal of the Royal Society Interface* 6(33), 411–414, April 2009 (online 13 January 2009).
|
| 165 |
+
<https://doi.org/10.1098/rsif.2008.0484>
|
| 166 |
+
* M. E. J. Newman. **Modularity and community structure in networks.** *PNAS* 103(23), 8577–8582, June 2006.
|
| 167 |
+
<https://doi.org/10.1073/pnas.0601602103>
|
| 168 |
+
* C. W. J. Granger. **Investigating Causal Relations by Econometric Models and Cross-spectral Methods.**
|
| 169 |
+
*Econometrica* 37(3), 424–438, August 1969. <https://doi.org/10.2307/1912791>
|
| 170 |
+
* Yoav Benjamini, Yosef Hochberg. **Controlling the False Discovery Rate: A Practical and Powerful Approach to
|
| 171 |
+
Multiple Testing.** *Journal of the Royal Statistical Society, Series B* 57(1), 289–300, 1995.
|
| 172 |
+
<https://doi.org/10.1111/j.2517-6161.1995.tb02031.x>
|
| 173 |
+
* Peter J. Rousseeuw. **Silhouettes: a graphical aid to the interpretation and validation of cluster
|
| 174 |
+
analysis.** *Journal of Computational and Applied Mathematics* 20, 53–65, November 1987.
|
| 175 |
+
<https://doi.org/10.1016/0377-0427(87)90125-7>
|
| 176 |
+
* Sibling project: `kai9987kai/SONAPSE-CONNECTOME` (read-only clone; ideas, not code, reused).
|
| 177 |
+
|
| 178 |
+
## Measured results
|
| 179 |
+
|
| 180 |
+
Measured on 2026-11-20, Windows 11 on ARM64, Python 3.12, NumPy 2.4, one BLAS thread
|
| 181 |
+
(`OPENBLAS_NUM_THREADS=1`), seeds 0, 1, 2, on a machine shared with other jobs (wall-clock is indicative).
|
| 182 |
+
|
| 183 |
+
| Run | Verdict | Key numbers | Wall-clock |
|
| 184 |
+
|---|---|---|---|
|
| 185 |
+
| `run_experiment(quick=True)` | `pass` (9/9 checks) | VAR(1) (8 units, 1500 steps, 99 null draws): support AUROC 1.000 / 1.000 / 1.000, sign accuracy 1.0, BH mask 24 true and 0 false positives (pooled precision 1.0), max coefficient error 0.052–0.056. Chain (2000 steps): `P_xz` 0.0085 / 0.0166 / −0.0042 (exact 0), max partial error 0.012–0.018 (tolerance 0.089), `R_xz` 0.42–0.47 (exact 0.447). Switching (6 blocks of 150): 2 states, silhouette 0.55–0.56 (k = 2) against 0.15–0.19 for the stationary control (1 state), pure-window accuracy 1.0 | 9.4 s (validation 3.0 s, NEUROWEAVE 6.4 s) on a lighter-loaded re-run; 16.3 s (validation 5.5 s, NEUROWEAVE 10.8 s) under load. Two runs in one process gave the same digest |
|
| 186 |
+
| `run_experiment()` | `pass` (9/9 checks) | VAR(1) (3000 steps, 199 null draws): support AUROC 1.000 for every seed, sign accuracy 1.0, mask 24 true and 2 false positives (pooled precision 0.92), max coefficient error 0.045–0.055. Chain (4000 steps): `P_xz` −0.016 / −0.014 / 0.011, max partial error 0.016–0.025 (tolerance 0.063), `R_xz` 0.45–0.46. Switching (8 blocks): 2 states, silhouette 0.55–0.57 against best 0.16–0.18 for the stationary control (1 state), pure-window accuracy 1.0 | 59.6 s (validation 4.0 s, NEUROWEAVE 55.6 s, four topologies × 32 neurons × 600 steps) |
|
| 187 |
+
|
| 188 |
+
NEUROWEAVE (quick, 24 neurons, 240 steps, 40 burn-in; descriptive, means over seeds): structure-FC Spearman
|
| 189 |
+
0.21 (`clustered`), 0.46 (`ring_lattice`), 0.15 (`hub_skewed`); communicability-FC Spearman 0.23 / 0.52 / 0.15;
|
| 190 |
+
EC-structure AUROC 0.62 / 0.71 / 0.58; EC density 0.10 / 0.17 / 0.09; dFC states 2.3 / 2.3 / 1.0.
|
| 191 |
+
Default size (32 neurons, 600 steps, 50 burn-in), `clustered` / `ring_lattice` / `hub_skewed` / `multi_region`:
|
| 192 |
+
structure-FC Spearman 0.16 / 0.23 / 0.15 / 0.12, communicability-FC Spearman 0.18 / 0.18 / 0.19 / 0.18,
|
| 193 |
+
EC-structure AUROC 0.73 / 0.76 / 0.63 / 0.69, dFC states 1.0 / 1.0 / 1.0 / 1.3. The quick and default numbers
|
| 194 |
+
differ (network size, run length), so neither is a stable property of a topology; these are small runs of a toy
|
| 195 |
+
model, reported, not tested.
|
docs/frontier/modules/continuum_memory.md
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `continuum_memory`: continuum memory system
|
| 2 |
+
|
| 3 |
+
Module file: `synapse/frontier/continuum_memory.py` · tests: `tests/test_frontier_memory.py` ·
|
| 4 |
+
experiment ids: `continuum_memory`, `continuum_memory_recall` · engine extension: `ContinuumMemoryExtension`
|
| 5 |
+
(id `continuum_memory`) · evidence tier: `synthetic_abstraction`.
|
| 6 |
+
|
| 7 |
+
The module combines two ideas from Behrouz and colleagues and uses them at toy scale:
|
| 8 |
+
|
| 9 |
+
* the **continuum memory system** (CMS) of *Nested Learning*: several memories, each updated at its own
|
| 10 |
+
frequency, so fast levels adapt quickly and slow levels keep information longer (the paper's Hope module is
|
| 11 |
+
a self-modifying Titans followed by a CMS);
|
| 12 |
+
* the **neural long-term memory update** of *Titans*: a gradient step on an associative loss, accumulated
|
| 13 |
+
with momentum ("surprise") and shrunk by a forgetting gate.
|
| 14 |
+
|
| 15 |
+
It is *inspired by* these papers and does not reproduce either. The memories are linear maps, not MLP blocks.
|
| 16 |
+
Momentum, learning rate and forgetting are fixed numbers, not learned functions of the input. There is no
|
| 17 |
+
attention, no self-modifying Titans, no meta-learned initial state and no language modelling. None of the
|
| 18 |
+
papers' results are attempted.
|
| 19 |
+
|
| 20 |
+
## What it computes
|
| 21 |
+
|
| 22 |
+
`ContinuumMemory(key_dim, value_dim, levels=4, base_period=1, lr=0.5, momentum=0.0, forget=0.01, *,
|
| 23 |
+
surprise_forget=0.0, max_forget=0.5, chunk_reduce='sum', bound=100.0)` holds `L = levels` linear memories
|
| 24 |
+
`M_l` (`value_dim x key_dim`), one momentum buffer `S_l` per level, and one gradient accumulator per level.
|
| 25 |
+
Level `l` has period `P_l = base_period * 2**l` (1, 2, 4, 8 with the defaults). A key is either one
|
| 26 |
+
`(key_dim,)` vector shared by every level or a `(levels, key_dim)` array with one key block per level.
|
| 27 |
+
|
| 28 |
+
```
|
| 29 |
+
read r_l = M_l k_l y = sum_l r_l (read / predict)
|
| 30 |
+
loss L_t = ||y_t - v_t||^2 g_{l,t} = dL_t/dM_l = 2 (y_t - v_t) k_{l,t}^T
|
| 31 |
+
chunk G_l = sum of g_{l,t} over the P_l writes of the chunk ('sum') or G_l / P_l ('mean')
|
| 32 |
+
when the write count is a multiple of P_l:
|
| 33 |
+
S_l <- clip(momentum * S_l - lr * G_l)
|
| 34 |
+
M_l <- clip((1 - alpha_l) * M_l + S_l)
|
| 35 |
+
alpha_l = min(max_forget, forget + surprise_forget * (mean surprise of the chunk))
|
| 36 |
+
surprise s_t = e_t / (e_t + ||v_t||^2), e_t = ||y_t - v_t||^2 (s_t = 0 when e_t = 0)
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
Every gradient is taken from the joint read `y_t` with the memories as they are at that write, so a slow
|
| 40 |
+
level accumulates the errors left after the fast levels have adapted. `clip` bounds `M` and `S` to
|
| 41 |
+
`[-bound, bound]`. Every array has a fixed shape, so the state stays finite and bounded. The memory has no
|
| 42 |
+
randomness.
|
| 43 |
+
|
| 44 |
+
How this maps onto the sources:
|
| 45 |
+
|
| 46 |
+
* **Nested Learning, Eq. 71.** The parameters of level `l` change only once every `C(l)` steps, by the sum of
|
| 47 |
+
`eta_t f(theta_t; x_t)` over the chunk, where `f` is the optimiser's error term. Here `f` is the gradient of
|
| 48 |
+
`L_t` with respect to `M_l`. `chunk_reduce='sum'` is a constant `eta`, and `'mean'` is `eta = lr / P_l`.
|
| 49 |
+
* **Nested Learning, Eq. 74.** This is the independent ("head-wise") CMS: the levels read the input
|
| 50 |
+
independently and an aggregation combines their outputs. The paper suggests a learnable weighted sum. This
|
| 51 |
+
module uses a fixed, unweighted sum.
|
| 52 |
+
* **Titans, Eqs. 10, 12 and 13.** The associative loss is `||M(k) - v||^2`. The surprise recurrence is
|
| 53 |
+
`S_t = eta_t S_{t-1} - theta_t grad`, and the forgetting gate gives `M_t = (1 - alpha_t) M_{t-1} + S_t`. Here
|
| 54 |
+
`momentum` is `eta`, `lr` is `theta`, and `alpha` is a fixed number (`forget`), optionally raised by the
|
| 55 |
+
chunk's surprise. In Titans' experiments `eta_t`, `theta_t` and `alpha_t` are functions of the token.
|
| 56 |
+
* **Surprise score.** `s_t` is this module's own bounded score. It is 0 for a perfect read, 1/2 for an empty
|
| 57 |
+
memory, and approaches 1 for a confidently wrong read. Titans calls the gradient term itself the "momentary
|
| 58 |
+
surprise". `s_t` only feeds the optional surprise-raised forgetting (`surprise_forget > 0`, off by default).
|
| 59 |
+
|
| 60 |
+
Tests check these properties on cases with a known answer:
|
| 61 |
+
|
| 62 |
+
* One write with `lr = 1/2` on a unit key stores exactly `v k^T`. The value reads back, and an orthogonal key
|
| 63 |
+
reads zero.
|
| 64 |
+
* Level `l` changes exactly on the writes divisible by `P_l`. This was checked over 48 writes with periods
|
| 65 |
+
3, 6, 12 and 24.
|
| 66 |
+
* The chunk update equals a hand computation (sum of per-write gradients, or their mean).
|
| 67 |
+
* Momentum and forgetting follow the Titans recurrences step by step.
|
| 68 |
+
* With zero gradient, level `l` decays by `(1 - forget)` per own update, so it decays at its own rate. A stored
|
| 69 |
+
association fades as `(1 - forget)^n`.
|
| 70 |
+
* Surprise raises `alpha` up to `max_forget`.
|
| 71 |
+
* The state stays within `bound` under extreme inputs.
|
| 72 |
+
* Each mechanism (momentum, forgetting, surprise forgetting, chunk mean, base period, level count, learning
|
| 73 |
+
rate) changes the predictions when toggled.
|
| 74 |
+
|
| 75 |
+
## Engine extension (`ContinuumMemoryExtension`, id `continuum_memory`)
|
| 76 |
+
|
| 77 |
+
`ContinuumMemoryExtension(levels=4, key_dim=8, base_period=1, lr=0.25, momentum=0.0, forget=0.01, *,
|
| 78 |
+
features_per_level=2, surprise_forget=0.0, max_forget=0.5, chunk_reduce='sum', seed=0)` is a readout-only
|
| 79 |
+
extension.
|
| 80 |
+
|
| 81 |
+
* **Context.** `c_t` is the task input (zero-padded or truncated to `TASK_INPUT_DIM = 8`; zeros when absent)
|
| 82 |
+
followed by the 16-channel fused sensory frame from the step context (24 numbers).
|
| 83 |
+
* **Key.** The key is a fixed binary random-feature map, `k(c) = sign(R c + b) / sqrt(levels * key_dim)`, with
|
| 84 |
+
`R` and `b` drawn from `default_rng(seed + 51407)`. It is split into one `key_dim` block per level and has
|
| 85 |
+
unit norm overall.
|
| 86 |
+
* **Write.** After every engine step, and only when `ctx['learn']` is true, the extension writes the
|
| 87 |
+
association `k(c_{t-1}) -> sensory_t`, so the memory learns to forecast the next sensory frame from the
|
| 88 |
+
current context. Nothing is written before a previous context exists, for example right after `reset()`.
|
| 89 |
+
* **Features.** The extension reads every level with `k(c_t)`. Each level's 16-channel read is projected onto
|
| 90 |
+
`features_per_level` fixed unit-norm directions (from `default_rng(seed + 51419)`) and clipped to
|
| 91 |
+
`[-10, 10]`. The result is `feature_dim = levels * features_per_level` features (8 by default).
|
| 92 |
+
* **What it does not touch.** The extension never changes the drive and does not read the brain output. It
|
| 93 |
+
keeps no engine reference, and `copy.deepcopy` gives an independent clone. With `ctx['learn']` false it does
|
| 94 |
+
not write; it counts `frozen_steps` instead. `reset()` forgets the previous context and the features, and
|
| 95 |
+
keeps the memory.
|
| 96 |
+
* **Budget.** `parameter_count()` is the number of memory entries, `levels * 16 * key_dim` (512 by default).
|
| 97 |
+
`state_numbers()` adds the momentum buffers, accumulators, random features, projections and counters.
|
| 98 |
+
|
| 99 |
+
A test feeds a period-3 sequence of sensory frames. Within 60 steps, the forecast error falls below 1 % of its
|
| 100 |
+
initial value.
|
| 101 |
+
|
| 102 |
+
## Recall benchmark (`run_recall_benchmark`, id `continuum_memory_recall`)
|
| 103 |
+
|
| 104 |
+
The benchmark tests the CMS schedule on a task with a known structure. It does not use the NEUROWEAVE engine.
|
| 105 |
+
|
| 106 |
+
* **Stream** (`make_recall_stream`). Keys are random unit vectors in `levels * key_dim` dimensions (128 by
|
| 107 |
+
default). Values are standard normal (8 dimensions).
|
| 108 |
+
* 4 short-gap items recur after gaps of 3–10 steps, and 8 long-gap items recur after gaps of 40–80 steps.
|
| 109 |
+
When several items are due, the earliest-due one is shown and the others wait, so a realised gap can be
|
| 110 |
+
longer than the drawn one.
|
| 111 |
+
* Every step without a due item shows a fresh one-off association, which acts as interference.
|
| 112 |
+
* An optional `remap_prob` gives a short-gap item a new value at a recurrence. This is off in the experiment.
|
| 113 |
+
* **Scoring.** Scoring is prequential: predict the value from the key, score the squared error at short-gap
|
| 114 |
+
and long-gap recurrences, then write.
|
| 115 |
+
* **Arms.**
|
| 116 |
+
* `cms`: 4 levels with periods 1, 2, 4 and 8. Level `l` reads block `l` of the key.
|
| 117 |
+
* `single`: one Titans-style memory (momentum and forgetting) that reads the whole key with period 1.
|
| 118 |
+
* `none`: the running mean of the values seen so far.
|
| 119 |
+
|
| 120 |
+
The two memory arms read the same keys and hold the same number of entries (`8 x 128 = 1024`). If every
|
| 121 |
+
CMS level had period 1, the two arms would compute the same thing. The difference between them is therefore
|
| 122 |
+
the update schedule, including how often forgetting acts.
|
| 123 |
+
* **Fair tuning.** For each memory arm, `(lr, momentum, forget)` is chosen from the same grid on separate
|
| 124 |
+
tuning seeds (1000 and 1001; 1000 in quick mode). The objective is the mean of short-gap and long-gap MSE.
|
| 125 |
+
`tuning.<arm>.chosen_on_grid_edge` names any chosen value that sits on a grid edge, where the optimum may lie
|
| 126 |
+
outside the grid. A value of 0 is treated as a natural bound, not an edge.
|
| 127 |
+
* **Verdict.** The verdict is a paired 95 % t interval over seeds on long-gap MSE (lower is better), `cms`
|
| 128 |
+
against `single`. Receipts also report the short-gap comparison and both memories against `none`.
|
| 129 |
+
* **Sizes.** The default uses 800 steps, `lr` in {1/64, …, 1/2} (6 values), `momentum` in
|
| 130 |
+
{0, 0.5, 0.75, 0.875, 0.9375} and `forget` in {0, 0.01}. Quick mode uses 240 steps, `lr` in
|
| 131 |
+
{0.125, 0.25, 0.5}, `momentum` in {0, 0.25, 0.5} and `forget` in {0, 0.02}.
|
| 132 |
+
|
| 133 |
+
## Lab experiment (`run_experiment`, id `continuum_memory`)
|
| 134 |
+
|
| 135 |
+
`harness.run_extension_experiment('continuum_memory', ...)` runs the NEUROWEAVE `delayed_recall` task (the
|
| 136 |
+
target is the input bit from two steps ago) with three arms:
|
| 137 |
+
|
| 138 |
+
* `baseline`: the unmodified engine and readout.
|
| 139 |
+
* `candidate`: the baseline plus `ContinuumMemoryExtension` features.
|
| 140 |
+
* `control`: the baseline plus the same number of random leaky-trace features of the brain output (the
|
| 141 |
+
harness's capacity-matched `random_trace` control).
|
| 142 |
+
|
| 143 |
+
All arms share seeds, streams and the readout protocol, and held-out streams are evaluated frozen. The headline
|
| 144 |
+
verdict is `improved` only if the candidate beats both the baseline and the control. The control matches the
|
| 145 |
+
candidate's readout feature count (8), not its stored numbers: the measured receipts report 2,525 extension
|
| 146 |
+
state numbers for the candidate and 208 (quick) or 400 (default size) for the control.
|
| 147 |
+
|
| 148 |
+
The defaults are the harness's: seeds 0, 1, 2; held-out seeds 100, 101; 300 steps; 48 neurons; clustered
|
| 149 |
+
topology; no extra NEUROWEAVE mechanisms. The extension uses its defaults. Quick mode uses the harness
|
| 150 |
+
`QUICK_ARGS` sizes (24 neurons, 24 steps, one 12-step held-out stream) with the caller's seeds. The extension
|
| 151 |
+
keys (`levels`, `key_dim`, `base_period`, `lr`, `momentum`, `forget`, `features_per_level`,
|
| 152 |
+
`surprise_forget`, `max_forget`, `chunk_reduce`) and the harness keys (`task`, `heldout_seeds`, `steps`,
|
| 153 |
+
`heldout_steps`, `neurons`, `topology`, `mechanisms`) can be overridden.
|
| 154 |
+
|
| 155 |
+
## Public API
|
| 156 |
+
|
| 157 |
+
```python
|
| 158 |
+
MODULE_ID = 'continuum_memory'; RECALL_ID = 'continuum_memory_recall'
|
| 159 |
+
EXPERIMENTS = {'continuum_memory': run_experiment, 'continuum_memory_recall': run_recall_benchmark}
|
| 160 |
+
run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed receipt
|
| 161 |
+
run_recall_benchmark(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed receipt
|
| 162 |
+
ContinuumMemory(key_dim, value_dim, levels=4, base_period=1, lr=0.5, momentum=0.0, forget=0.01, *,
|
| 163 |
+
surprise_forget=0.0, max_forget=0.5, chunk_reduce='sum', bound=100.0)
|
| 164 |
+
.read(query) -> (levels, value_dim); .predict(query) -> (value_dim,)
|
| 165 |
+
.write(key, value) -> {'error', 'surprise', 'updated_levels'}
|
| 166 |
+
.periods; .parameter_count; .state_numbers; .config(); .reset(); .export_state(); .import_state(state)
|
| 167 |
+
ContinuumMemoryExtension(levels=4, key_dim=8, base_period=1, lr=0.25, momentum=0.0, forget=0.01, *,
|
| 168 |
+
features_per_level=2, surprise_forget=0.0, max_forget=0.5, chunk_reduce='sum', seed=0)
|
| 169 |
+
.key(context); .after_step(output, ctx); .features(); .telemetry(); .export_state(); .import_state(state)
|
| 170 |
+
make_recall_stream(seed, steps, *, key_dim=128, value_dim=8, n_short=4, n_long=8, short_gap=(3, 10),
|
| 171 |
+
long_gap=(40, 80), remap_prob=0.0) -> {'keys', 'values', 'kind', 'item', 'gap'}
|
| 172 |
+
RECALL_DEFAULTS, RECALL_QUICK, KIND_CODES, CHUNK_REDUCTIONS, SOURCE
|
| 173 |
+
```
|
| 174 |
+
|
| 175 |
+
Every public function and constructor validates its input and raises `ValueError` before any state changes.
|
| 176 |
+
`import_state` validates the whole state before replacing anything. It checks the configuration, shapes,
|
| 177 |
+
finiteness, the bound, and that the chunk and update counters are consistent with the write count. A failed
|
| 178 |
+
import leaves the memory unchanged. No global NumPy or torch random or thread state is touched.
|
| 179 |
+
|
| 180 |
+
## Connection to Sonapse
|
| 181 |
+
|
| 182 |
+
* **Not a live observer.** `continuum_memory` is not in `spec.OBSERVER_MODULE_IDS`.
|
| 183 |
+
* **Engine extension.** It influences nothing unless it is attached to a NEUROWEAVE engine with
|
| 184 |
+
`attach_extension`, as in the lab experiment. Even when attached, it only adds readout features. It never
|
| 185 |
+
changes the drive.
|
| 186 |
+
* **Standalone benchmark.** `run_recall_benchmark` uses only `ContinuumMemory` and synthetic streams.
|
| 187 |
+
* **Defaults.** No Sonapse or NEUROWEAVE default, API or checkpoint format changes.
|
| 188 |
+
|
| 189 |
+
## Not implemented, and differences from the papers
|
| 190 |
+
|
| 191 |
+
* MLP memory blocks (Titans uses MLPs with `L_M >= 1` layers; Hope's CMS uses MLP blocks). Here every level is
|
| 192 |
+
one linear map.
|
| 193 |
+
* Learned, input-dependent `eta_t`, `theta_t` and `alpha_t`, and learned key, value and query projections.
|
| 194 |
+
The extension uses a fixed random binary key map.
|
| 195 |
+
* The learnable aggregation weights of the independent CMS, and the nested and sequential CMS variants
|
| 196 |
+
(Nested Learning Eqs. 72 and 73), including meta-learned initial states.
|
| 197 |
+
* Hope's self-modifying Titans module (and the softmax attention of the paper's Hope-Attention variant), the
|
| 198 |
+
parallel chunk-wise training of Titans (mini-batch gradients with a parallel associative scan for the
|
| 199 |
+
surprise terms), and every language-modelling, continual-learning and long-context result.
|
| 200 |
+
* Per-level momentum and forgetting applied at chunk boundaries. This combination of the two papers' update
|
| 201 |
+
rules is this module's own design.
|
| 202 |
+
* Periods on a fixed geometric ladder (`base_period * 2**l`). Nested Learning defines each level's chunk size
|
| 203 |
+
from its update frequency, `C(l) = max_i C(i) / f_l`; the geometric ladder is this module's choice.
|
| 204 |
+
* The surprise score `s_t` (see above).
|
| 205 |
+
|
| 206 |
+
## Verified references
|
| 207 |
+
|
| 208 |
+
Each reference was checked on 2026-11-20 against its arXiv listing and arXiv HTML full text, and against the
|
| 209 |
+
NeurIPS 2025 virtual-conference pages.
|
| 210 |
+
|
| 211 |
+
1. Ali Behrouz, Meisam Razaviyayn, Peilin Zhong, Vahab Mirrokni. **Nested Learning: The Illusion of Deep
|
| 212 |
+
Learning Architectures.** *Advances in Neural Information Processing Systems (NeurIPS) 2025*, poster
|
| 213 |
+
(https://neurips.cc/virtual/2025/poster/116123). arXiv:2512.24695, v1 submitted 31 December 2025 (the only
|
| 214 |
+
version listed on 2026-11-20); the arXiv comment says a version of the work is published at NeurIPS 2025.
|
| 215 |
+
https://arxiv.org/abs/2512.24695. Checked in the arXiv HTML of v1:
|
| 216 |
+
* Section 7.1, Eq. 70: the CMS chain of MLP blocks.
|
| 217 |
+
* Eq. 71: level `l` is updated every `C(l)` steps with the summed error terms of its chunk, and
|
| 218 |
+
`C(l) = max_i C(i) / f_l`.
|
| 219 |
+
* Eqs. 72–73: the nested and sequential variants.
|
| 220 |
+
* Eq. 74: the independent ("head-wise") variant with an aggregation function; the text suggests "a learnable
|
| 221 |
+
weighted sum".
|
| 222 |
+
* Definition 2: the update frequency is the "number of updates per unit of time".
|
| 223 |
+
* Section 8.3: Hope is self-modifying Titans followed by a CMS; the Hope-Attention variant replaces the
|
| 224 |
+
self-modifying Titans with softmax attention.
|
| 225 |
+
2. Ali Behrouz, Peilin Zhong, Vahab Mirrokni. **Titans: Learning to Memorize at Test Time.** *Advances in
|
| 226 |
+
Neural Information Processing Systems (NeurIPS) 2025*, poster
|
| 227 |
+
(https://neurips.cc/virtual/2025/loc/san-diego/poster/119639). arXiv:2501.00663, v1 submitted
|
| 228 |
+
31 December 2024. https://arxiv.org/abs/2501.00663. Checked in the arXiv HTML:
|
| 229 |
+
* Eqs. 9–10: surprise with momentum, with the "past surprise" and "momentary surprise" terms.
|
| 230 |
+
* Eqs. 11–12: keys and values, and the loss `||M_{t-1}(k_t) - v_t||^2`.
|
| 231 |
+
* Eqs. 13–14: the forgetting gate `alpha_t` in `[0, 1]`.
|
| 232 |
+
* Eq. 15: retrieval without a weight update.
|
| 233 |
+
* Section 3.1: the memory is an MLP with `L_M >= 1` layers.
|
| 234 |
+
* Section 3.2: chunk-wise mini-batch training, a parallel associative scan for the surprise terms, and the
|
| 235 |
+
statement that, in their experiments, `alpha_t`, `theta_t` and `eta_t` are functions of the tokens.
|
| 236 |
+
|
| 237 |
+
## Measured results
|
| 238 |
+
|
| 239 |
+
All runs were measured on 2026-11-20 on Windows 11 on ARM64, with Python 3.12.10, NumPy 2.4 and one BLAS/OpenMP
|
| 240 |
+
thread (`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1`). Every call used its defaults apart from
|
| 241 |
+
`quick`, with seeds 0, 1, 2. Each quick run was made three times and gave the same receipt digest every time;
|
| 242 |
+
each default-size run was made once (an earlier run on the same day gave the same numbers). The tests also
|
| 243 |
+
check that a second run gives the same digest. The digest prefix is listed so a rerun on this setup can be
|
| 244 |
+
compared; another platform may round floating-point results differently. Wall-clock covers the whole call
|
| 245 |
+
and is given as the range over the runs. The machine was shared with other jobs, so wall-clock is only
|
| 246 |
+
indicative.
|
| 247 |
+
|
| 248 |
+
| Run | Verdict | Key numbers | Digest | Wall-clock |
|
| 249 |
+
|---|---|---|---|---|
|
| 250 |
+
| `run_recall_benchmark(quick=True)` | `no_detectable_difference` | Long-gap MSE: cms 0.192 / single 0.194 / none 1.149. cms − single −0.0016, CI [−0.0089, 0.0058]. Short-gap MSE: cms 0.0156 / single 0.0146 / none 0.664; cms − single +0.0010, CI [−0.0007, 0.0028]. Both memories beat `none` (cms − none −0.957, CI [−1.228, −0.687]). Both arms chose `lr` 0.25, `momentum` 0.25, `forget` 0; no grid-edge flags. Seed 0 scores 133 short-gap and 24 long-gap recurrences | `cb276e79` | 1.98–3.14 s |
|
| 251 |
+
| `run_experiment(quick=True)` | `no_detectable_difference` | Held-out accuracy 0.500 in all three arms (chance 0.500). The CI is degenerate (all paired differences 0). Seed 0 telemetry: 23 writes; level update counts 23, 11, 5, 2 | `2bea12ce` | 1.57–2.07 s |
|
| 252 |
+
| `run_recall_benchmark()` | `no_detectable_difference` | Long-gap MSE: cms 0.111 / single 0.112 / none 1.142. cms − single −0.0015, CI [−0.0048, 0.0019]. Short-gap MSE: cms 0.0119 / single 0.0105 / none 0.652; cms − single +0.0014, CI [0.0006, 0.0021], so cms is `worse` on short gaps. Chosen: cms `lr` 1/16, `momentum` 0.75; single `lr` 1/32, `momentum` 0.875; both `forget` 0; no grid-edge flags. Seed 0 scores 463 short-gap and 99 long-gap recurrences | `e736bf69` | 43.7 s |
|
| 253 |
+
| `run_experiment()` | `no_detectable_difference` | Held-out accuracy: baseline 0.558 / candidate 0.559 / control 0.561 (chance 0.517). Candidate − baseline +0.001, CI [−0.004, 0.006]; candidate − control −0.002, CI [−0.015, 0.010]. Seed 0 telemetry: 299 writes; level update counts 299, 149, 74, 37 | `b26b9c5f` | 18.1 s |
|
| 254 |
+
|
| 255 |
+
At equal entries and equal keys, with each arm tuned on the same grid, the multi-period schedule did not
|
| 256 |
+
detectably improve long-gap recall over a single Titans-style memory at these sizes, and it was slightly worse
|
| 257 |
+
on short gaps in the default run. Tuning gave both arms no forgetting and the same effective step
|
| 258 |
+
`lr / (1 - momentum)`: 0.25 in the default run, and 1/3 in quick mode, where both chose the same grid point.
|
| 259 |
+
Both memories beat the no-memory predictor by a wide margin. On `delayed_recall` the sensory-forecast
|
| 260 |
+
features made no detectable difference to the NEUROWEAVE readout. In the quick run every arm stays at chance,
|
| 261 |
+
so it only checks that the pipeline runs.
|
| 262 |
+
|
| 263 |
+
These are statements about a linear toy on synthetic streams. They say nothing about language modelling or
|
| 264 |
+
about the published results.
|
docs/frontier/modules/dendritic_layer.md
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `dendritic_layer`: structured dendritic layer
|
| 2 |
+
|
| 3 |
+
Module file: `synapse/frontier/dendritic.py` · tests: `tests/test_frontier_models.py` ·
|
| 4 |
+
experiment id: `dendritic_layer` · kind: standalone model (no engine extension, no live observer) ·
|
| 5 |
+
evidence tier: `synthetic_abstraction`.
|
| 6 |
+
|
| 7 |
+
The module implements a **dendritic artificial neural network** (dANN) layer inspired by Chavlis & Poirazi (2025).
|
| 8 |
+
Each dendrite receives a small, fixed subset of the inputs, which gives the layer structured sparsity through a
|
| 9 |
+
fixed binary mask. Each dendrite applies a nonlinearity, and each soma sums only its own dendrites through
|
| 10 |
+
trainable cable weights. The lab experiment compares dANNs with three input-sampling rules against a dense MLP at
|
| 11 |
+
matched trainable parameters, on a procedurally generated glyph dataset.
|
| 12 |
+
|
| 13 |
+
This is not a reproduction. The paper's datasets (MNIST variants, CIFAR-10), sizes, efficiency scores and
|
| 14 |
+
sparse-ANN controls are not used. The units are abstract nodes, not models of real dendrites.
|
| 15 |
+
|
| 16 |
+
## What it computes
|
| 17 |
+
|
| 18 |
+
**Layer (`DendriticLayer`).** There are `somas` somata, each with `dendrites_per_soma` dendrites (`D` dendrites
|
| 19 |
+
in total). Dendrite `k` has exactly `S = synapses_per_dendrite` synapses:
|
| 20 |
+
|
| 21 |
+
```
|
| 22 |
+
d_k = lrelu( sum_i M_ki W_ki x_i + b_k ) # dendrite k; M is a fixed 0/1 mask, S ones per row
|
| 23 |
+
s_j = lrelu( sum_{k in dendrites(j)} c_jk d_k + a_j ) # soma j sums only its own dendrites
|
| 24 |
+
lrelu(u) = max(u, 0.1 u) # leaky ReLU, slope 0.1, as in the paper
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
* **Masking.**
|
| 28 |
+
* The weights are multiplied by the mask in the forward pass, so masked weights get exactly zero gradient.
|
| 29 |
+
This is the paper's Eq. 3, gradient masking.
|
| 30 |
+
* `W <- W ⊙ M` is re-applied after every optimiser step (`enforce_mask`, Eq. 1).
|
| 31 |
+
* The mask is a registered buffer. It never changes and travels with `state_dict()`.
|
| 32 |
+
* **Tree structure.** Every dendrite connects to exactly one soma. `cable_weight` therefore has shape
|
| 33 |
+
`(somas, dendrites_per_soma)`; `cable_mask()` shows the equivalent dense 0/1 soma-by-dendrite matrix.
|
| 34 |
+
* **Initialisation** uses a `torch.Generator`. Synapses and dendritic biases are uniform in
|
| 35 |
+
±1/√S, the dendrite's own fan-in. Cable weights and somatic biases are uniform in ±1/√`dendrites_per_soma`.
|
| 36 |
+
* **`parameter_count()`** counts only parameters that exist: unmasked synapses, dendritic biases, cable weights
|
| 37 |
+
and somatic biases. The weight tensor is stored densely, but masked entries are not counted. `macs()` gives the
|
| 38 |
+
multiply-accumulates a sparse implementation would need.
|
| 39 |
+
|
| 40 |
+
**Input sampling (`sample_receptive_fields`).** The mask is fixed at construction from
|
| 41 |
+
`default_rng(seed + 41011)`:
|
| 42 |
+
|
| 43 |
+
* **`random`** (dANN-R): each dendrite samples `S` distinct inputs uniformly.
|
| 44 |
+
* **`local`** (dANN-LRF): each dendrite gets a uniformly drawn centre pixel and takes the `S` pixels nearest to it.
|
| 45 |
+
It starts from the centre's 3×3 block (a random subset when `S < 9`). It then adds Chebyshev rings of radius 2,
|
| 46 |
+
3, … and takes a random subset of the last ring it needs. Blocks are clipped at the image border.
|
| 47 |
+
* **`global`** (dANN-GRF): each soma gets a uniformly drawn centre. Its dendrites' centres are
|
| 48 |
+
`dendrites_per_soma` distinct pixels nearest that centre, chosen by the same rule. Each dendrite then samples
|
| 49 |
+
locally around its own centre.
|
| 50 |
+
|
| 51 |
+
The paper's Methods text says each dendrite takes 16 pixels from "the 4 × 4 neighbourhood" of its centre. The
|
| 52 |
+
authors' released `receptive_fields.py` instead builds the 3 × 3 block and grows it ring by ring, as described
|
| 53 |
+
above, and that is what this module follows. The default here is `S = 9`, a full 3 × 3 block.
|
| 54 |
+
|
| 55 |
+
In the released somatic (GRF) mode, dendrite centres are drawn without replacement from the 3 × 3 block around
|
| 56 |
+
the soma centre. An inverted guard there never grows the block, so a soma with more than 9 dendrites, or one at
|
| 57 |
+
an image corner, leaves some dendrites without inputs. The ring rule used here avoids that case.
|
| 58 |
+
|
| 59 |
+
**Networks.**
|
| 60 |
+
|
| 61 |
+
* `DendriticNet` is a `DendriticLayer` followed by a dense linear read-out, the paper's "fully connected output
|
| 62 |
+
layer".
|
| 63 |
+
* `DenseMLP` is the control: two dense hidden layers of equal width `h` with the same leaky ReLU, then a linear
|
| 64 |
+
read-out. `matched_dense_hidden` picks the `h` whose parameter count is closest to the dANN's.
|
| 65 |
+
|
| 66 |
+
The trainable parameter counts are:
|
| 67 |
+
|
| 68 |
+
```
|
| 69 |
+
dANN = D·S + 2·D + somas + somas·classes + classes (dann_parameter_count; D = somas · dendrites_per_soma)
|
| 70 |
+
dense = 144·h + h + h² + h + h·classes + classes (dense_parameter_count)
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
## Benchmark (`run_experiment`, `EXPERIMENTS = {'dendritic_layer': run_experiment}`)
|
| 74 |
+
|
| 75 |
+
**Glyphs (`render_glyph`, `make_glyph_dataset`).** There are ten stroke classes, defined as polylines in the unit
|
| 76 |
+
square: `box, bar, plus, cross, ell, tee, zed, caret, aitch, cup`. Each image is rendered anti-aliased into
|
| 77 |
+
12 × 12 pixels, so the input is 144-dimensional:
|
| 78 |
+
|
| 79 |
+
* random scale 6–8.5 px;
|
| 80 |
+
* rotation ±0.25 rad;
|
| 81 |
+
* translation ±2 px;
|
| 82 |
+
* half stroke width 0.35–0.9 px;
|
| 83 |
+
* additive Gaussian pixel noise with σ = 0.2.
|
| 84 |
+
|
| 85 |
+
The pixel value is `clip(half_width + 0.5 − distance to the nearest segment, 0, 1)` plus noise. Nothing is
|
| 86 |
+
downloaded.
|
| 87 |
+
|
| 88 |
+
**Per seed** (default `seeds=(0, 1, 2)`):
|
| 89 |
+
|
| 90 |
+
* independent training (60 per class), validation (50 per class) and held-out (200 per class) sets, drawn from
|
| 91 |
+
different generator seeds;
|
| 92 |
+
* a noisy copy of the held-out set with extra Gaussian noise σ = 0.5, drawn from a `torch.Generator`. This copy
|
| 93 |
+
measures robustness.
|
| 94 |
+
|
| 95 |
+
**Arms.**
|
| 96 |
+
|
| 97 |
+
* `dann_random`, `dann_local` and `dann_global`: 16 somata × 8 dendrites × 9 synapses.
|
| 98 |
+
* `dense_mlp`: the dense control.
|
| 99 |
+
|
| 100 |
+
All arms share the data, the minibatch order (one generator seed), Adam (lr 3e-3, β = (0.9, 0.999)), batch 64
|
| 101 |
+
and 1000 updates. The paper uses Adam with lr 1e-3. Here 3e-3 is used because, with this update budget, lr 1e-3
|
| 102 |
+
left the models short of fitting their training set; see the calibration row under *Measured results*. The
|
| 103 |
+
parameter budget is computed **before training**. If the dense control cannot be matched within
|
| 104 |
+
`param_tolerance` (10 %), `run_experiment` raises `ValueError`. That happens, for example, when the dANN is
|
| 105 |
+
smaller than the narrowest dense MLP, which has 167 parameters.
|
| 106 |
+
|
| 107 |
+
**Verdict.**
|
| 108 |
+
|
| 109 |
+
1. The best dANN is the sampling mode with the highest mean *validation* accuracy. The held-out set plays no part
|
| 110 |
+
in that choice.
|
| 111 |
+
2. `verdict = harness.compare(best dANN, dense MLP)` on held-out accuracy per seed, a paired 95 % t interval over
|
| 112 |
+
seeds.
|
| 113 |
+
3. `robustness_verdict` is the same comparison on the extra-noise held-out copy.
|
| 114 |
+
|
| 115 |
+
The receipt also compares every sampling mode with the dense MLP, on clean and on noisy data, and records:
|
| 116 |
+
|
| 117 |
+
* the per-arm train, validation, held-out and noisy accuracies;
|
| 118 |
+
* the mask density, and a count of nonzero masked weights after training (always 0);
|
| 119 |
+
* the parameter budget;
|
| 120 |
+
* the estimated MACs;
|
| 121 |
+
* the measured wall-clock, which is kept out of the digest.
|
| 122 |
+
|
| 123 |
+
| option | default | quick |
|
| 124 |
+
|---|---|---|
|
| 125 |
+
| images per class train / val / held-out | 60 / 50 / 200 | 40 / 20 / 50 |
|
| 126 |
+
| noise / extra noise (σ) | 0.2 / 0.5 | same |
|
| 127 |
+
| somata × dendrites × synapses | 16 × 8 × 9 (mask density 9/144 = 0.0625) | same |
|
| 128 |
+
| trainable parameters dANN / dense (width) | 1,594 / 1,670 (10) | same |
|
| 129 |
+
| Adam updates / batch / lr | 1000 / 64 / 3e-3 | 250 / 64 / 3e-3 |
|
| 130 |
+
|
| 131 |
+
## Public API
|
| 132 |
+
|
| 133 |
+
```python
|
| 134 |
+
MODULE_ID = 'dendritic_layer'
|
| 135 |
+
EXPERIMENTS = {'dendritic_layer': run_experiment}
|
| 136 |
+
run_experiment(*, quick: bool = False, seeds=(0, 1, 2), **overrides) -> dict # overrides: any DEFAULTS key
|
| 137 |
+
|
| 138 |
+
DendriticLayer(in_features, somas, dendrites_per_soma, synapses_per_dendrite, sampling='random', *,
|
| 139 |
+
image_shape=None, seed=0, negative_slope=0.1)
|
| 140 |
+
.forward(x) -> somatic activity (batch, somas) .dendritic_activity(x) -> (batch, D)
|
| 141 |
+
.enforce_mask() .cable_mask() .parameter_count() .mask_density() .macs()
|
| 142 |
+
buffers: synaptic_mask (D, in_features), fields (D, S) input indices per dendrite
|
| 143 |
+
DendriticNet(in_features, classes, somas, dendrites_per_soma, synapses_per_dendrite, sampling='random', *,
|
| 144 |
+
image_shape=None, seed=0)
|
| 145 |
+
DenseMLP(in_features, classes, hidden, *, seed=0)
|
| 146 |
+
sample_receptive_fields(in_features, somas, dendrites_per_soma, synapses_per_dendrite, sampling, *,
|
| 147 |
+
image_shape=None, rng) -> np.ndarray (D, S)
|
| 148 |
+
dann_parameter_count(somas, dendrites_per_soma, synapses_per_dendrite, classes) -> int
|
| 149 |
+
dense_parameter_count(in_features, classes, hidden) -> int
|
| 150 |
+
matched_dense_hidden(target_params, in_features, classes) -> int
|
| 151 |
+
render_glyph(label, rng, *, noise=0.0, shift=2.0, size=(6.0, 8.5), thickness=(0.35, 0.9), rotation=0.25)
|
| 152 |
+
make_glyph_dataset(n_per_class, *, seed, noise=0.2, **render_kw) -> (x float32 (n, 144), y int64 (n,))
|
| 153 |
+
train_classifier(model, x, y, *, updates, batch_size, lr, generator) -> dict
|
| 154 |
+
accuracy(model, x, y) -> float
|
| 155 |
+
SAMPLING_MODES = ('random', 'local', 'global'), GLYPHS, GLYPH_NAMES, GLYPH_SIDE (12), DEFAULTS, QUICK
|
| 156 |
+
```
|
| 157 |
+
|
| 158 |
+
Image shapes default to a square, `(sqrt(n), sqrt(n))`, when `in_features` is a perfect square, and to
|
| 159 |
+
`(1, n)` otherwise. Pass `image_shape` to override.
|
| 160 |
+
|
| 161 |
+
Determinism and global state:
|
| 162 |
+
|
| 163 |
+
* masks use NumPy `default_rng`, and weights, minibatch order and test noise use `torch.Generator`;
|
| 164 |
+
* the global torch RNG is never touched;
|
| 165 |
+
* `run_experiment` runs on one torch thread and restores the caller's thread count afterwards.
|
| 166 |
+
|
| 167 |
+
## Connection to Sonapse
|
| 168 |
+
|
| 169 |
+
This is a standalone lab model (contract rule 3). It is not wired into the brain, a graft or the actor, and it
|
| 170 |
+
changes no Sonapse default. The frontier lab registry picks it up from `EXPERIMENTS`.
|
| 171 |
+
|
| 172 |
+
Sonapse already has two different dendrite abstractions:
|
| 173 |
+
|
| 174 |
+
* `synapse/dendritic_ltc.py` is a two-compartment, basal/apical liquid time-constant sub-graft;
|
| 175 |
+
* `synapse/dsag/` is the dual-soma axodendritic graft.
|
| 176 |
+
|
| 177 |
+
`DendriticLayer` is a plain `nn.Module`. It could replace a dense input projection in such a graft behind an
|
| 178 |
+
opt-in flag. That is not done here.
|
| 179 |
+
|
| 180 |
+
## Not implemented
|
| 181 |
+
|
| 182 |
+
* **Paper controls and analyses:**
|
| 183 |
+
* dANN-F (all-to-all dendrites) and the sparse-ANN (sANN) controls;
|
| 184 |
+
* vANNs with unequal hidden widths;
|
| 185 |
+
* the accuracy and loss efficiency scores (Eq. 4–5);
|
| 186 |
+
* the sequential-learning, dropout and depth studies;
|
| 187 |
+
* the entropy and selectivity analyses.
|
| 188 |
+
* **Datasets:** MNIST, Fashion-MNIST, Kuzushiji-MNIST, EMNIST and CIFAR-10. No data is downloaded.
|
| 189 |
+
* **Biological constraints:** positive or fixed cable weights, which the paper names as a more bio-realistic
|
| 190 |
+
option.
|
| 191 |
+
* **Sparse kernels.** The masked layer runs as a dense matrix product, so it is not faster than the dense MLP.
|
| 192 |
+
`estimated_cost.macs_per_example` reports what a sparse implementation would need.
|
| 193 |
+
|
| 194 |
+
## Verified references
|
| 195 |
+
|
| 196 |
+
* Spyridon Chavlis and Panayiota Poirazi. **Dendrites endow artificial neural networks with accurate, robust and
|
| 197 |
+
parameter-efficient learning.** *Nature Communications* 16, 943 (2025), published 22 January 2025 (received
|
| 198 |
+
4 April 2024, accepted 13 January 2025). DOI [10.1038/s41467-025-56297-9](https://doi.org/10.1038/s41467-025-56297-9);
|
| 199 |
+
open access as PMC11754790 (PMID 39843414). Preprint: arXiv:2404.03708, v1 4 April 2024, v2 13 September 2024,
|
| 200 |
+
<https://arxiv.org/abs/2404.03708>.
|
| 201 |
+
* **Re-checked on 2026-11-20 (review)** against PMC11754790 (title, authors, volume 16, article 943,
|
| 202 |
+
22 January 2025, received 4 April 2024, accepted 13 January 2025; R / LRF / GRF sampling, 16 synapses
|
| 203 |
+
per dendrite, leaky ReLU 0.1, `W ⊙ M` with masked gradients) and `codes_/receptive_fields.py` (3 × 3
|
| 204 |
+
block, ring expansion with a random subset of the last ring, centres with replacement, the inverted
|
| 205 |
+
somatic expansion guard). `sample_receptive_fields` matches the code, with the guard fixed.
|
| 206 |
+
* **Checked on 2026-11-17 against the PMC full text and the arXiv preprint:**
|
| 207 |
+
* Eq. 1, `W ← W ⊙ M`, and Eq. 3, gradient masking;
|
| 208 |
+
* one soma per dendrite, and a fully connected output layer;
|
| 209 |
+
* the three restricted sampling strategies R, LRF and GRF, and 16 inputs per dendrite;
|
| 210 |
+
* leaky ReLU with negative slope 0.1 on all hidden nodes;
|
| 211 |
+
* Adam with lr 0.001, betas 0.9 and 0.999, minibatch 128;
|
| 212 |
+
* a 90 / 10 train / validation split.
|
| 213 |
+
* **Checked in the authors' code** the same day: <https://github.com/Poirazi-Lab/dendritic_anns>,
|
| 214 |
+
`codes_/receptive_fields.py`.
|
| 215 |
+
* `allocate_synapses` uses the 3 × 3 base block, random subsampling, and ring expansion with a random subset
|
| 216 |
+
of the last ring.
|
| 217 |
+
* Centres are drawn uniformly with replacement.
|
| 218 |
+
* In somatic mode, dendrite centres come from the 3 × 3 block without replacement, behind the inverted
|
| 219 |
+
expansion guard noted above.
|
| 220 |
+
|
| 221 |
+
## Measured results
|
| 222 |
+
|
| 223 |
+
Measured on **2026-11-20** (`quick=True`, `seeds=(0, 1, 2)`, single CPU thread `OPENBLAS_NUM_THREADS=1`, digest `beb329f8b497c3e0`, wall-clock `5.03 s`):
|
| 224 |
+
|
| 225 |
+
| Arm | Train acc | Val acc | Held-out acc | Held-out noisy acc | Held-out Δ vs `dense_mlp` (95 % CI) |
|
| 226 |
+
|---|---:|---:|---:|---:|---|
|
| 227 |
+
| `dann_random` | 0.9067 | 0.6650 | 0.6560 | 0.4007 | −0.0127 (`[-0.0844, +0.0591]`, `no_detectable_difference`) |
|
| 228 |
+
| `dann_local` (best val) | 0.8625 | 0.6667 | 0.6780 | 0.4440 | +0.0093 (`[-0.0424, +0.0611]`, `no_detectable_difference`) |
|
| 229 |
+
| `dann_global` | 0.8158 | 0.6400 | 0.6433 | 0.4227 | −0.0253 (`[-0.1536, +0.1029]`, `no_detectable_difference`) |
|
| 230 |
+
| `dense_mlp` (baseline) | 0.9758 | 0.6633 | 0.6687 | 0.4080 | — |
|
| 231 |
+
|
| 232 |
+
* **Headline verdict (`best_dann(dann_local)_vs_dense_mlp`):** `no_detectable_difference` (mean +0.0093, 95 % CI `[-0.0424, +0.0611]`).
|
| 233 |
+
* **Robustness verdict (`best_dann_vs_dense_noisy`):** `no_detectable_difference` (mean +0.0360, 95 % CI `[-0.0372, +0.1092]`).
|
docs/frontier/modules/experiment_design.md
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `experiment_design`: decision-sensitive experiment selection
|
| 2 |
+
|
| 3 |
+
Module file: `synapse/frontier/experiment_design.py` · tests: `tests/test_frontier_addons.py` ·
|
| 4 |
+
experiment ids: `experiment_design`, `experiment_design_costed` · kind: methodology (no engine extension, no live observer) ·
|
| 5 |
+
evidence tier: `synthetic_abstraction`.
|
| 6 |
+
|
| 7 |
+
The module implements **one-step decision-sensitive Bayesian experimental design** over a finite hypothesis set,
|
| 8 |
+
inspired by COUNTERFORM's decision-risk acquisition and Mnemorph (`kai9987kai`) and by classical Bayesian
|
| 9 |
+
decision-theoretic design (Lindley, 1956; Chaloner & Verdinelli, 1995). Instead of picking the experiment that
|
| 10 |
+
maximises expected information gain about which hypothesis is true, the selector picks the experiment that
|
| 11 |
+
maximises the expected reduction in the **downstream decision's Bayes risk**, net of any experiment cost, and
|
| 12 |
+
**abstains** (recommends stopping) when no experiment improves expected net risk beyond a threshold.
|
| 13 |
+
|
| 14 |
+
This is a synthetic finite-hypothesis abstraction. It does not reproduce COUNTERFORM's physical oscillator studies
|
| 15 |
+
or any published benchmark.
|
| 16 |
+
|
| 17 |
+
## What it computes
|
| 18 |
+
|
| 19 |
+
**Problem (`DecisionProblem`).** There are $K$ hypotheses with prior weights $w \in \Delta^{K-1}$, $M$ candidate
|
| 20 |
+
experiments, and $D$ downstream decisions with a loss matrix $L \in \mathbb{R}^{D \times K}$ and non-negative
|
| 21 |
+
per-experiment costs $c \in \mathbb{R}_{\ge 0}^M$. Under hypothesis $k$, experiment $e$ produces a scalar Gaussian
|
| 22 |
+
outcome
|
| 23 |
+
|
| 24 |
+
$$
|
| 25 |
+
y \mid (k, e) \sim \mathcal{N}\!\left(\mu_{k,e},\; \sigma_{k,e}^2\right).
|
| 26 |
+
$$
|
| 27 |
+
|
| 28 |
+
* **Bayes update (`update`).** Given belief $w$ and outcome $y$ from experiment $e$, the posterior $w'(y)$ is
|
| 29 |
+
computed in log space:
|
| 30 |
+
$$
|
| 31 |
+
w'_k(y) \propto w_k \,\mathcal{N}\!\left(y;\; \mu_{k,e},\, \sigma_{k,e}^2\right),
|
| 32 |
+
\qquad w_k = 0 \implies w'_k(y) = 0.
|
| 33 |
+
$$
|
| 34 |
+
* **Bayes decision and Bayes risk (`decision`, `bayes_risk`).** The optimal decision at belief $w$ and its expected
|
| 35 |
+
loss are
|
| 36 |
+
$$
|
| 37 |
+
d^*(w) = \arg\min_{d \in \{0,\dots,D-1\}} \sum_{k=0}^{K-1} L_{d,k}\, w_k,
|
| 38 |
+
\qquad R(w) = \min_{d} (L w)_d,
|
| 39 |
+
$$
|
| 40 |
+
breaking ties by lowest decision index.
|
| 41 |
+
* **Deterministic posterior-predictive quadrature (`_fantasies`).** Under belief $w$, the marginal outcome
|
| 42 |
+
distribution of experiment $e$ is the Gaussian mixture $\sum_{k} w_k \,\mathcal{N}(\mu_{k,e}, \sigma_{k,e}^2)$.
|
| 43 |
+
Expectations over $y$ are evaluated with $Q$-point Gauss–Hermite quadrature (`quadrature=20` by default) applied
|
| 44 |
+
to each mixture component:
|
| 45 |
+
$$
|
| 46 |
+
y_{k,q} = \mu_{k,e} + \sigma_{k,e}\sqrt{2}\,x_q, \qquad p_{k,q} = \frac{w_k\,\omega_q}{\sqrt{\pi}},
|
| 47 |
+
$$
|
| 48 |
+
where $(x_q, \omega_q)_{q=1}^Q$ are the standard Gauss–Hermite nodes and weights ($\sum_q \omega_q / \sqrt{\pi} = 1$).
|
| 49 |
+
Because quadrature is deterministic, acquisition scores have zero Monte-Carlo variance.
|
| 50 |
+
* **Expected Bayes-risk reduction (`risk_reduction`).** The one-step value of information of experiment $e$ is
|
| 51 |
+
$$
|
| 52 |
+
\Delta R(e \mid w) = \max\!\left(0,\; R(w) - \sum_{k=0}^{K-1}\sum_{q=1}^{Q} p_{k,q}\, R\!\left(w'(y_{k,q})\right)\right).
|
| 53 |
+
$$
|
| 54 |
+
* **Expected information gain (`information_gain`).** Lindley's mutual information (in nats) between the hypothesis
|
| 55 |
+
and the outcome of experiment $e$:
|
| 56 |
+
$$
|
| 57 |
+
\mathrm{IG}(e \mid w) = \max\!\left(0,\; H(w) - \sum_{k=0}^{K-1}\sum_{q=1}^{Q} p_{k,q}\, H\!\left(w'(y_{k,q})\right)\right),
|
| 58 |
+
\qquad H(w) = -\sum_{k:\,w_k>0} w_k \ln w_k.
|
| 59 |
+
$$
|
| 60 |
+
|
| 61 |
+
**Selectors.**
|
| 62 |
+
|
| 63 |
+
* **`DecisionSensitiveSelector` (`decision_risk`)** scores each experiment by net value $\Delta R(e \mid w) - c_e$,
|
| 64 |
+
picks the lowest index among maxima, and returns `None` (abstains) when
|
| 65 |
+
$\max_e \{\Delta R(e \mid w) - c_e\} \le \tau$ (`abstain_threshold = 1e-9`). Once a study abstains, no further
|
| 66 |
+
experiments are run and no further cost is paid.
|
| 67 |
+
* **`_NoAbstainDecisionSelector` (`decision_risk_no_abstain`)** uses the same net-value ranking but never abstains;
|
| 68 |
+
it separates the effect of the decision-sensitive ranking from the stopping rule in costed studies.
|
| 69 |
+
* **`InformationGainSelector` (`information_gain`)** picks $\arg\max_e \mathrm{IG}(e \mid w)$ (abstaining only when
|
| 70 |
+
$\max_e \mathrm{IG}(e \mid w) \le 10^{-12}$, i.e., when every experiment has identical outcome distributions across
|
| 71 |
+
supported hypotheses).
|
| 72 |
+
* **`RandomSelector` (`random`)** draws uniformly from $\{0, \dots, M-1\}$ using a seeded NumPy generator
|
| 73 |
+
(`default_rng(seed + 104729)`).
|
| 74 |
+
|
| 75 |
+
## Benchmarks (`EXPERIMENTS = {'experiment_design': run_experiment, 'experiment_design_costed': run_costed_experiment}`)
|
| 76 |
+
|
| 77 |
+
**Synthetic studies (`make_study`).** The generator constructs problems where **information about the hypothesis**
|
| 78 |
+
and **relevance to the decision** diverge:
|
| 79 |
+
|
| 80 |
+
1. The $K$ hypotheses are partitioned into $D$ decision groups ($g_k = k \bmod D$). Decision $d$ has zero loss on
|
| 81 |
+
hypotheses in group $d$ and an asymmetric loss $L_{d,k} \sim \mathrm{Uniform}(0.5, 2.0)$ when $d \ne g_k$.
|
| 82 |
+
2. Prior weights follow $\mathrm{Dirichlet}(4, \dots, 4)$.
|
| 83 |
+
3. The $M - M_{\text{dist}}$ **relevant** experiments draw a group mean $\mathcal{N}(0, 1)$ per decision group plus
|
| 84 |
+
small within-group jitter $\mathcal{N}(0, 0.15^2)$: they separate decision groups with modest signal-to-noise.
|
| 85 |
+
4. The $M_{\text{dist}}$ **distractor** experiments repeat the same large within-group spacing (amplitude
|
| 86 |
+
$\mathrm{Uniform}(2, 4)$) inside every decision group: they carry high mutual information about *which*
|
| 87 |
+
hypothesis holds within a group, but almost zero information about *which group* holds.
|
| 88 |
+
5. Experiment columns are randomly permuted so the selector must infer relevance from $(\mu, \sigma, L)$.
|
| 89 |
+
|
| 90 |
+
**Common random numbers (`simulate_study`).** For each study, the hidden true hypothesis $k^* \sim w^{(0)}$ and the
|
| 91 |
+
standard-normal observation noise draws $z_0, \dots, z_{B-1}$ are shared across every selector arm. After $B$
|
| 92 |
+
steps (or earlier abstention), the terminal decision $d^*(w^{(B)})$ is scored by its **decision regret** against an
|
| 93 |
+
oracle that knows $k^*$:
|
| 94 |
+
|
| 95 |
+
$$
|
| 96 |
+
\mathrm{regret}\!\left(d, k^*\right) = L_{d, k^*} - \min_{d'} L_{d', k^*}.
|
| 97 |
+
$$
|
| 98 |
+
|
| 99 |
+
* **`experiment_design` (`run_experiment`)** compares `decision_risk`, `information_gain`, and `random` at zero
|
| 100 |
+
experiment cost (`c_e = 0`). Headline verdict: `harness.compare(decision_risk, information_gain, higher_is_better=False)`
|
| 101 |
+
on mean final decision regret across seeds.
|
| 102 |
+
* **`experiment_design_costed` (`run_costed_experiment`)** assigns per-experiment costs
|
| 103 |
+
$c_e \sim \mathrm{Uniform}(\text{cost\_low}, \text{cost\_high})$ and compares `decision_risk`,
|
| 104 |
+
`decision_risk_no_abstain`, and `information_gain` on **mean total loss** ($\text{final regret} + \sum c_e$,
|
| 105 |
+
lower is better).
|
| 106 |
+
|
| 107 |
+
| option | `experiment_design` default / quick | `experiment_design_costed` default / quick |
|
| 108 |
+
|---|---|---|
|
| 109 |
+
| studies per seed | 300 / 60 | 300 / 60 |
|
| 110 |
+
| experiment budget $B$ | 4 / 3 | 6 / 4 |
|
| 111 |
+
| hypotheses $K$ / decisions $D$ | 6 / 2 | 6 / 2 |
|
| 112 |
+
| experiments $M$ / distractors $M_{\text{dist}}$ | 8 / 3 | 8 / 3 |
|
| 113 |
+
| noise scale / quadrature $Q$ | 1.0 / 20 | 1.0 / 20 |
|
| 114 |
+
| per-experiment cost range | `(0.0, 0.0)` | `(0.02, 0.08)` |
|
| 115 |
+
|
| 116 |
+
## Public API
|
| 117 |
+
|
| 118 |
+
```python
|
| 119 |
+
MODULE_ID = 'experiment_design'
|
| 120 |
+
SELECTORS = ('decision_risk', 'information_gain', 'random')
|
| 121 |
+
EXPERIMENTS = {
|
| 122 |
+
'experiment_design': run_experiment,
|
| 123 |
+
'experiment_design_costed': run_costed_experiment,
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
DecisionProblem(prior, means, sigmas, loss, costs=None, *, quadrature=20)
|
| 127 |
+
.n_hypotheses .n_experiments .n_decisions
|
| 128 |
+
.log_likelihood(e, y) -> np.ndarray
|
| 129 |
+
.update(w, e, y) -> np.ndarray
|
| 130 |
+
.decision(w) -> (decision_idx: int, bayes_risk: float)
|
| 131 |
+
.bayes_risk(w) -> float
|
| 132 |
+
.risk_reduction(w) -> np.ndarray # shape (M,)
|
| 133 |
+
.information_gain(w) -> np.ndarray # shape (M,), nats
|
| 134 |
+
.to_dict() -> dict
|
| 135 |
+
DecisionSensitiveSelector(problem, *, abstain_threshold=1e-9)
|
| 136 |
+
.scores(w) -> np.ndarray # risk_reduction(w) - costs
|
| 137 |
+
.choose(w) -> int | None
|
| 138 |
+
InformationGainSelector(problem, *, abstain_threshold=1e-12)
|
| 139 |
+
.scores(w) -> np.ndarray
|
| 140 |
+
.choose(w) -> int | None
|
| 141 |
+
RandomSelector(problem, *, seed=0)
|
| 142 |
+
.choose(w) -> int | None
|
| 143 |
+
make_selector(name, problem, *, seed=0, abstain=True)
|
| 144 |
+
make_study(seed, *, hypotheses=6, experiments=8, decisions=2, distractors=3,
|
| 145 |
+
noise=1.0, cost_range=(0.0, 0.0), quadrature=20) -> DecisionProblem
|
| 146 |
+
simulate_study(problem, truth, selector, budget, noise) -> dict
|
| 147 |
+
run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict
|
| 148 |
+
run_costed_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
## Connection to Sonapse
|
| 152 |
+
|
| 153 |
+
This is a standalone methodology module (contract rule 3). It has no live observer and no engine extension, and it
|
| 154 |
+
changes no Sonapse or NEUROWEAVE default. Its `EXPERIMENTS` dictionary plugs into the frontier lab registry.
|
| 155 |
+
|
| 156 |
+
## Not implemented
|
| 157 |
+
|
| 158 |
+
* **Multi-step (non-myopic) lookahead.** Value of information is greedy (one step). When two experiments are
|
| 159 |
+
individually weak but jointly decisive, greedy one-step lookahead underestimates their combined value and can
|
| 160 |
+
abstain early.
|
| 161 |
+
* **Continuous hypothesis spaces or non-Gaussian likelihoods.** Hypotheses are finite and likelihoods are scalar
|
| 162 |
+
Gaussian so that one-step expectations are exact up to Gauss–Hermite quadrature.
|
| 163 |
+
* **COUNTERFORM's physical oscillator simulator and adequacy gates.** Only the decision-theoretic acquisition
|
| 164 |
+
principle is abstracted here.
|
| 165 |
+
|
| 166 |
+
## Verified references
|
| 167 |
+
|
| 168 |
+
* Dennis V. Lindley. **On a Measure of the Information Provided by an Experiment.** *The Annals of Mathematical
|
| 169 |
+
Statistics* 27(4), 986–1005 (December 1956). DOI [10.1214/aoms/1177728069](https://doi.org/10.1214/aoms/1177728069);
|
| 170 |
+
Project Euclid: <https://projecteuclid.org/journals/annals-of-mathematical-statistics/volume-27/issue-4/On-a-Measure-of-the-Information-Provided-by-an-Experiment/10.1214/aoms/1177728069.full>.
|
| 171 |
+
* **Checked on 2026-11-19:** defines the expected Shannon information gain of an experiment as
|
| 172 |
+
$I = H_{\text{prior}} - \mathbb{E}_y[H_{\text{posterior}}(y)]$ (used here for `InformationGainSelector`).
|
| 173 |
+
* Kathryn Chaloner and Isabella Verdinelli. **Bayesian Experimental Design: A Review.** *Statistical Science*
|
| 174 |
+
10(3), 273–304 (August 1995). DOI [10.1214/ss/1177009939](https://doi.org/10.1214/ss/1177009939);
|
| 175 |
+
Project Euclid: <https://projecteuclid.org/journals/statistical-science/volume-10/issue-3/Bayesian-Experimental-Design-A-Review/10.1214/ss/1177009939.full>.
|
| 176 |
+
* **Checked on 2026-11-19:** reviews the decision-theoretic formulation of Bayesian experimental design (following
|
| 177 |
+
Raiffa & Schlaifer, 1961, and DeGroot, 1970) where an experiment $e$ is chosen to maximise expected utility
|
| 178 |
+
$\int \max_d \int u(d, \theta, y, e)\, p(\theta \mid y, e)\, d\theta\, p(y \mid e)\, dy$, equivalent to
|
| 179 |
+
minimising expected posterior Bayes risk plus experiment cost (`DecisionSensitiveSelector`).
|
| 180 |
+
* Portfolio provenance: `kai9987kai/COUNTERFORM` (v0.2 decision-sensitive fantasy design-risk acquisition with
|
| 181 |
+
abstention) and `kai9987kai/Mnemorph`, inspected in the local read-only portfolio clones on 2026-11-19.
|
| 182 |
+
|
| 183 |
+
## Measured results
|
| 184 |
+
|
| 185 |
+
Measured on **2026-11-19** with `seeds=(0, 1, 2)` on one CPU thread (`OPENBLAS_NUM_THREADS=1`).
|
| 186 |
+
|
| 187 |
+
### `experiment_design` (fixed budget, zero cost; metric: mean final decision regret, lower is better)
|
| 188 |
+
|
| 189 |
+
| mode | digest (prefix) | wall-clock | `decision_risk` regret (acc / abstain / exp run / entropy) | `information_gain` regret (acc / exp run / entropy) | `random` regret (acc) | `decision_risk - information_gain` (95 % CI) | verdict |
|
| 190 |
+
|---|---|---|---|---|---|---|---|
|
| 191 |
+
| `quick=True` (60 studies, $B=3$) | `a847c682598c5663` | 2.76 s | 0.0746 (93.9 % / 8.3 % / 2.92 / 1.062 nats) | 0.1170 (89.4 % / 3.00 / 0.254 nats) | 0.2453 (77.2 %) | −0.0424 (`[-0.1079, +0.0231]`, SD 0.0264) | `no_detectable_difference` |
|
| 192 |
+
| `quick=False` (300 studies, $B=4$) | `36526702c942f04e` | 12.26 s | 0.0481 (95.9 % / 25.7 % / 3.65 / 1.002 nats) | 0.0609 (94.8 % / 4.00 / 0.151 nats) | 0.2134 (80.8 %) | −0.0128 (`[-0.0384, +0.0129]`, SD 0.0103) | `no_detectable_difference` |
|
| 193 |
+
|
| 194 |
+
Regret by budget step (`quick=False`, steps $t = 0, 1, 2, 3, 4$):
|
| 195 |
+
|
| 196 |
+
* `decision_risk`: `[0.4885, 0.2164, 0.1157, 0.0698, 0.0481]`
|
| 197 |
+
* `information_gain`: `[0.4885, 0.4139, 0.1752, 0.0898, 0.0609]`
|
| 198 |
+
* `random`: `[0.4885, 0.3695, 0.2972, 0.2421, 0.2134]`
|
| 199 |
+
|
| 200 |
+
On step 1, `information_gain` typically chooses a high-entropy distractor experiment (regret drops only from 0.4885
|
| 201 |
+
to 0.4139 while posterior entropy falls sharply), whereas `decision_risk` chooses a group-separating experiment
|
| 202 |
+
(regret drops from 0.4885 to 0.2164). By step $B=4$, `information_gain` has also sampled relevant experiments and
|
| 203 |
+
nearly catches up in terminal regret, so the paired 95 % t interval across 3 seeds spans zero (`no_detectable_difference`),
|
| 204 |
+
while both active selectors beat `random` (`improved` at `quick=False`).
|
| 205 |
+
|
| 206 |
+
### `experiment_design_costed` (costs in `[0.02, 0.08]`; metric: mean total loss = final regret + cost, lower is better)
|
| 207 |
+
|
| 208 |
+
| mode | digest (prefix) | wall-clock | `decision_risk` total (regret + cost, abstain, exp run) | `decision_risk_no_abstain` total (regret + cost, exp run) | `information_gain` total (regret + cost, exp run) | `decision_risk - information_gain` (95 % CI) | `decision_risk - no_abstain` (95 % CI) | verdict |
|
| 209 |
+
|---|---|---|---|---|---|---|---|---|
|
| 210 |
+
| `quick=True` (60 studies, $B=4$) | `1bbab8d035695813` | 4.40 s | 0.1442 (0.0700 + 0.0742, 91.7 %, 1.63) | 0.1899 (0.0518 + 0.1380, 4.00) | 0.2606 (0.0670 + 0.1936, 4.00) | −0.1164 (`[-0.1693, -0.0635]`) | −0.0457 (`[-0.1131, +0.0218]`) | `improved` |
|
| 211 |
+
| `quick=False` (300 studies, $B=6$) | `ec83a4fa770b5f9c` | 10.68 s | 0.1504 (0.0750 + 0.0754, 98.4 %, 1.65) | 0.2388 (0.0422 + 0.1967, 6.00) | 0.3197 (0.0223 + 0.2974, 6.00) | −0.1693 (`[-0.2814, -0.0572]`) | −0.0885 (`[-0.1332, -0.0438]`) | `improved` |
|
docs/frontier/modules/hh_cable.md
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `hh_cable`: Hodgkin-Huxley cable reference
|
| 2 |
+
|
| 3 |
+
Module file: `synapse/frontier/hh_cable.py` · tests: `tests/test_frontier_biophysics.py` ·
|
| 4 |
+
experiment id: `hh_cable` (`kind: 'validation'`) · no observer, no engine extension ·
|
| 5 |
+
evidence tier: `synthetic_abstraction`.
|
| 6 |
+
|
| 7 |
+
A multi-compartment Hodgkin-Huxley (HH) cable, used as a **biophysical reference** next to NEUROWEAVE's
|
| 8 |
+
abstract discrete-time cell. It is *inspired by* NeuroPulse-CableLab (kai9987kai), a single-file browser HH
|
| 9 |
+
cable workbench with Euler, RK4 and Rush-Larsen integrators and a dt versus dt/2 comparison. It is built on
|
| 10 |
+
the membrane equations of Hodgkin & Huxley (1952).
|
| 11 |
+
|
| 12 |
+
This is a numerical integration of the 1952 equations on a discretised cable. It does not reproduce the paper's
|
| 13 |
+
own procedure: HH solved a travelling-wave ODE (their eqn 30) by shooting for the velocity, using Hartree's
|
| 14 |
+
method. It is not a validated neuron simulator. The NEUROWEAVE comparison is descriptive only, and the
|
| 15 |
+
abstract cell is never "validated" against HH.
|
| 16 |
+
|
| 17 |
+
## What it computes
|
| 18 |
+
|
| 19 |
+
**Membrane and cable.** `v` is in mV with rest near −65 mV. HH's own variable is the displacement
|
| 20 |
+
`V = −(v + 65)`, with depolarisation negative.
|
| 21 |
+
|
| 22 |
+
```
|
| 23 |
+
Cm dv_i/dt = I_stim,i + g_ax (v_{i-1} - 2 v_i + v_{i+1}) - gNa m^3 h (v - ENa) - gK n^4 (v - EK) - gL (v - EL)
|
| 24 |
+
dx/dt = phi (alpha_x(v) (1 - x) - beta_x(v) x), x in {m, h, n}, phi = 3^((T - 6.3) / 10)
|
| 25 |
+
g_ax = a / (2 Ra dx^2) (HH eqn 28, I = (a / 2 R2) d2V/dx2, discretised by central differences)
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
* The rate functions are HH eqns 12, 13, 20, 21, 23 and 24 (p. 519), rewritten for `v`. For example,
|
| 29 |
+
`alpha_m = 0.1 (v + 40) / (1 - exp(-(v + 40)/10))` and `beta_h = 1 / (1 + exp(-(v + 35)/10))`. The removable
|
| 30 |
+
singularities at `v = −40` (alpha_m) and `v = −55` (alpha_n) take their limits, 1.0 and 0.1.
|
| 31 |
+
* Constants come from Table 3 (p. 520): `Cm = 1 uF/cm^2`, `gNa = 120`, `gK = 36`, `gL = 0.3 mS/cm^2`. The
|
| 32 |
+
reversal potentials `V_Na = −115`, `V_K = +12`, `V_l = −10.613 mV` become `ENa = 50`, `EK = −77` and
|
| 33 |
+
`EL = −54.387 mV`.
|
| 34 |
+
* Rates are for 6.3 °C, scaled by `phi` with a Q10 of 3 (pp. 519, 523).
|
| 35 |
+
* Both ends are sealed: no axial current leaves the first or last compartment. The stimulus is a current
|
| 36 |
+
density (uA/cm^2) on compartment 0.
|
| 37 |
+
* Each simulation starts at the resting state, the most negative stable zero of the steady-state ionic current.
|
| 38 |
+
|
| 39 |
+
**Integrators.**
|
| 40 |
+
|
| 41 |
+
* `'rk4'`: classical Runge-Kutta. The constructor rejects time steps beyond a conservative linear stability
|
| 42 |
+
bound.
|
| 43 |
+
* `'exp_euler'`: the gates are integrated exactly for frozen voltage (Rush-Larsen style). The voltage takes an
|
| 44 |
+
exponential step with conductances and neighbour voltages frozen. It is first order and stable for any step.
|
| 45 |
+
|
| 46 |
+
Spike times are upward crossings of 0 mV, re-armed below −30 mV, located inside the step by cubic Hermite
|
| 47 |
+
interpolation. Everything is batched over amplitudes, intervals or diameters, so each search is a handful of
|
| 48 |
+
vectorised simulations.
|
| 49 |
+
|
| 50 |
+
**Measurements (methods of `HHCable`).**
|
| 51 |
+
|
| 52 |
+
* `resting_potential()`: bisection to 1e-10 mV.
|
| 53 |
+
* `threshold_current(duration_ms, ...)`: batched bisection for the smallest step amplitude that gives a spike
|
| 54 |
+
at a site, by default the last compartment.
|
| 55 |
+
* `fi_curve(amplitudes, ...)`: steady rate `(k − 1) / (t_last − t_first)` over the spikes after a transient.
|
| 56 |
+
A lone onset spike counts as 0 Hz.
|
| 57 |
+
* `conduction_velocity(...)`: distance over the difference in first-spike arrival at 1/3 and 2/3 of the
|
| 58 |
+
cable, optionally batched over diameters.
|
| 59 |
+
* `refractory_period(...)`: paired pulses. A conditioning pulse (2 × the single-pulse threshold) is followed by
|
| 60 |
+
a test pulse (4 × threshold). The result is the smallest onset-to-onset interval at which the test pulse
|
| 61 |
+
evokes a second spike. This is an operational estimate of the absolute refractory period for that test
|
| 62 |
+
strength.
|
| 63 |
+
|
| 64 |
+
**NEUROWEAVE reference.** `neuroweave_fi_curve` drives isolated `CellPopulation` cells from
|
| 65 |
+
`synapse/neuroweave/cells.py` with constant external drive and counts spikes. The cells have the
|
| 66 |
+
`membrane_dynamics` flag, no recurrent input and neutral controls. `neuroweave_threshold` finds the smallest
|
| 67 |
+
drive that fires. `compare_fi_curves` then compares the two f-I curves:
|
| 68 |
+
|
| 69 |
+
* Both curves are taken on the same threshold-normalised levels and normalised to their maximum.
|
| 70 |
+
* It reports the Spearman rank correlation over the suprathreshold levels, the level where repetitive firing
|
| 71 |
+
starts, and the mean absolute difference.
|
| 72 |
+
* `adaptation_index` gives the mean of `(ISI_{k+1} − ISI_k) / (ISI_{k+1} + ISI_k)` at one level.
|
| 73 |
+
|
| 74 |
+
The comparison is descriptive: an abstract unit with one step as its time unit is compared in shape only.
|
| 75 |
+
|
| 76 |
+
## Lab experiment (`run_experiment`, `EXPERIMENTS = {'hh_cable': run_experiment}`)
|
| 77 |
+
|
| 78 |
+
Every named check must hold for `verdict: 'pass'`:
|
| 79 |
+
|
| 80 |
+
| Check | Known answer |
|
| 81 |
+
|---|---|
|
| 82 |
+
| `resting_within_0.5mV_of_documented_-65mV` | HH chose `V_l` so the ionic current is zero at `V = 0` (Table 3 footnote) |
|
| 83 |
+
| `rest_stationary_without_input` | zero current: no spike, voltage stays at rest to 1e-6 mV |
|
| 84 |
+
| `subthreshold_steps_silent` / `suprathreshold_steps_fire` | all-or-none response at 0.5 × and ≥ 1.1 × the long-step threshold |
|
| 85 |
+
| `spike_peak_above_0mV` | overshoot in the patch and at mid-cable for every diameter |
|
| 86 |
+
| `velocity_positive`, `velocity_increases_with_diameter` | |
|
| 87 |
+
| `velocity_scaling_exponent_within_tolerance_of_0.5` | HH eqn 34, `theta = sqrt(K a / (2 R2 CM))`: velocity grows as sqrt(diameter) on a uniform cable (tolerance 0.03 on the log-log slope) |
|
| 88 |
+
| `reference_velocity_within_tolerance_of_hh1952_computed` | HH p. 528: 18.8 m/s computed for their axon (a = 238 um, R2 = 35.4 ohm cm, CM = 1 uF/cm^2, 18.5 °C; observed 21.2 m/s); tolerance 2 %. Present only when the 476 um diameter, 18.5 °C and 35.4 ohm cm are used |
|
| 89 |
+
| `spike_time_converges_under_dt_halving` | patch RK4: the change in first-spike time at dt/2 at least halves or stays below 1e-6 ms, and is below 1e-3 ms |
|
| 90 |
+
| `exp_euler_first_order_convergence` | observed order between 0.7 and 1.5 |
|
| 91 |
+
| `velocity_changes_below_1pct_at_dt_half` | cable velocities at dt and dt/2 |
|
| 92 |
+
| `refractory_second_pulse_fails_then_recovers` | the test pulse fails at one pulse width and succeeds at the longest interval |
|
| 93 |
+
|
| 94 |
+
Settings:
|
| 95 |
+
|
| 96 |
+
* Patch at 6.3 °C, with `dt` 0.0125 ms and RK4.
|
| 97 |
+
* Cable at 18.5 °C: 40 mm long, 200 compartments, `dt` 0.0006 ms, diameters 119, 238 and 476 um, stimulated
|
| 98 |
+
with a 0.2 ms pulse of 3000 uA/cm^2. The velocity is measured between 1/3 and 2/3 of the length, because
|
| 99 |
+
both ends bias the local speed over several millimetres.
|
| 100 |
+
* `quick=True` uses 60 compartments and `dt` 0.005 ms for the cable, shorter windows, single-round searches and
|
| 101 |
+
fewer f-I levels.
|
| 102 |
+
* The HH model is deterministic. `seeds` only seed the NEUROWEAVE `CellPopulation` constructors, and the
|
| 103 |
+
receipt reports per-seed NEUROWEAVE curves with `seed_invariant`.
|
| 104 |
+
* All settings are overridable (`_DEFAULTS` keys). Unknown overrides raise `ValueError`.
|
| 105 |
+
|
| 106 |
+
## Public API
|
| 107 |
+
|
| 108 |
+
```python
|
| 109 |
+
MODULE_ID = 'hh_cable'; EXPERIMENTS = {'hh_cable': run_experiment}; METHODS = ('rk4', 'exp_euler')
|
| 110 |
+
HH_REST_MV = -65.0; HH1952_REFERENCE_AXON = {'diameter_um': 476.0, 'Ra_ohm_cm': 35.4, ...}
|
| 111 |
+
run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed validation receipt
|
| 112 |
+
HHCable(compartments=1, length_um=100.0, diameter_um=476.0, Ra=35.4, Cm=1.0, gNa=120.0, gK=36.0, gL=0.3,
|
| 113 |
+
ENa=50.0, EK=-77.0, EL=-54.387, dt_ms=0.01, method='rk4', temperature_c=6.3)
|
| 114 |
+
.run(pulses, *, t_stop_ms, record=None, trace_site=None, trace_every=1) # pulses: (P, 3) or (B, P, 3)
|
| 115 |
+
.resting_potential(); .threshold_current(duration_ms, ...); .fi_curve(amplitudes, ...)
|
| 116 |
+
.conduction_velocity(*, amplitude=3000.0, duration_ms=0.2, t_stop_ms=2.0, sites=None, diameters_um=None)
|
| 117 |
+
.refractory_period(*, pulse_ms=0.5, threshold=None, ...); .replace(**changes); .config()
|
| 118 |
+
vtrap(x, y); hh_rates(v); steady_state_gates(v); temperature_factor(temperature_c)
|
| 119 |
+
neuroweave_fi_curve(drives, *, steps=400, transient=100, seed=0, flags=('membrane_dynamics',))
|
| 120 |
+
neuroweave_threshold(*, steps=400, seed=0, bracket=(0.0, 2.0), rounds=2, batch=64, flags=...)
|
| 121 |
+
adaptation_index(isis); average_ranks(x); spearman_rho(a, b); compare_fi_curves(levels, hh_rates, nw_rates)
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
* Units: um, ohm cm, uF/cm^2, mS/cm^2, mV, ms and uA/cm^2.
|
| 125 |
+
* Input is validated before anything runs, and bad input raises `ValueError`.
|
| 126 |
+
The convergence study requires three successive time steps, each half its predecessor. The f-I study
|
| 127 |
+
requires strictly increasing drive levels with at least three at or above threshold and one at or above
|
| 128 |
+
1.1 times threshold.
|
| 129 |
+
* Simulations are bounded: at most 2 M steps, 4096 batch elements and 64 pulses. Non-finite states raise
|
| 130 |
+
`FloatingPointError`.
|
| 131 |
+
* No randomness is used, and no global NumPy or torch RNG or thread state is touched (tested).
|
| 132 |
+
|
| 133 |
+
## Connection to Sonapse
|
| 134 |
+
|
| 135 |
+
* An offline reference. It neither reads nor writes any brain, engine or graft state, apart from
|
| 136 |
+
constructing its own isolated `CellPopulation` cells for the comparison.
|
| 137 |
+
* No Sonapse or NEUROWEAVE default, API or checkpoint format changes.
|
| 138 |
+
* It gives the abstract NEUROWEAVE cell a fixed biophysical yardstick for the shape of its f-I curve and its
|
| 139 |
+
adaptation. This is not a fidelity target.
|
| 140 |
+
|
| 141 |
+
## Not implemented
|
| 142 |
+
|
| 143 |
+
* Branched or tapered morphologies, non-uniform channel densities, synapses, extracellular potentials,
|
| 144 |
+
myelination and other channel types. The cable is uniform and unbranched, with sealed ends.
|
| 145 |
+
* HH's own travelling-wave shooting method. Their observed 21.2 m/s is not a target; the check compares with
|
| 146 |
+
their computed 18.8 m/s.
|
| 147 |
+
* Temperature dependence of `Cm` or of the conductances. HH also held these constants independent of
|
| 148 |
+
temperature.
|
| 149 |
+
* Any claim that the NEUROWEAVE cell is biologically realistic.
|
| 150 |
+
* The refractory estimate depends on the test strength (4 × threshold) and the temperature (6.3 °C), and it
|
| 151 |
+
is not compared with a published value.
|
| 152 |
+
|
| 153 |
+
## Verified references
|
| 154 |
+
|
| 155 |
+
Checked on 2026-11-20.
|
| 156 |
+
|
| 157 |
+
1. A. L. Hodgkin, A. F. Huxley. **A quantitative description of membrane current and its application to
|
| 158 |
+
conduction and excitation in nerve.** *The Journal of Physiology* 117(4), 500–544, 28 August 1952.
|
| 159 |
+
doi:10.1113/jphysiol.1952.sp004764, https://physoc.onlinelibrary.wiley.com/doi/10.1113/jphysiol.1952.sp004764,
|
| 160 |
+
PubMed 12991237. Checked against page images of the paper's scanned PDF:
|
| 161 |
+
* the rate equations (12), (13), (20), (21), (23), (24) and the 6.3 °C / Q10 = 3 statement (p. 519);
|
| 162 |
+
* Table 3 constants and its footnote on `V_l` (p. 520);
|
| 163 |
+
* eqns 27–30 for the propagated action potential (p. 522);
|
| 164 |
+
* the factor `phi = 3^((T − 6.3)/10)` and the numerical method (p. 523);
|
| 165 |
+
* `K = 10.47 /ms`, eqn 34, `a = 238 um`, `R2 = 35.4 ohm cm`, `CM = 1.0 uF/cm^2`, 18.5 °C, and the
|
| 166 |
+
computed 18.8 m/s against the observed 21.2 m/s (p. 528).
|
| 167 |
+
2. NeuroPulse-CableLab (kai9987kai), a sibling repository. Its README and integrator list (Euler, RK4,
|
| 168 |
+
Rush-Larsen gates, the dt versus dt/2 comparison) were read in a read-only clone. None of its code was
|
| 169 |
+
executed or copied.
|
| 170 |
+
|
| 171 |
+
## Measured results
|
| 172 |
+
|
| 173 |
+
Measured on 2026-11-20 on Windows 11 on ARM64, with Python 3.12.10, NumPy 2.4 and one BLAS/OpenMP thread
|
| 174 |
+
(`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1`). Seeds were 0, 1 and 2. Receipts are deterministic:
|
| 175 |
+
two runs of the quick receipt gave the same digest (tested). Wall-clock covers the whole call on a machine
|
| 176 |
+
shared with other jobs.
|
| 177 |
+
|
| 178 |
+
| Run | Verdict | Wall-clock |
|
| 179 |
+
|---|---|---|
|
| 180 |
+
| `run_experiment(quick=True)` | `pass` (13/13 checks) | 6.1–6.8 s |
|
| 181 |
+
| `run_experiment()` | `pass` (13/13 checks) | 36.4 s |
|
| 182 |
+
|
| 183 |
+
Key numbers (quick / default):
|
| 184 |
+
|
| 185 |
+
* **Rest:** −64.996 mV. Table 3 gives `V_l` to three decimals (−10.613 mV), which leaves the computed rest
|
| 186 |
+
0.004 mV above −65.
|
| 187 |
+
* **Long-step threshold** (a spike within 15 / 40 ms of onset): 2.22–2.30 / 2.229–2.248 uA/cm^2.
|
| 188 |
+
* **Patch spike peak:** 41.8 / 42.7 mV.
|
| 189 |
+
* **Repetitive firing:**
|
| 190 |
+
* With the default levels, the HH patch fires a single onset spike up to 2.5 × threshold, and repetitive
|
| 191 |
+
firing starts between 2.5 × and 3 × (56.7 Hz at 3 ×, 112.8 Hz at 20 ×, 6.3 °C).
|
| 192 |
+
* With the quick levels, it starts between 2 × and 3 × (57.1 Hz at 3 ×).
|
| 193 |
+
* The HH adaptation index at 4 × threshold is −0.008 / −0.0007, so firing is essentially regular.
|
| 194 |
+
* **Convergence** (patch, 20 uA/cm^2 for 1 ms):
|
| 195 |
+
* RK4 first-spike times at dt 0.0125, 0.00625 and 0.003125 ms agree to 2.1e-9 ms, which is the
|
| 196 |
+
interpolation and rounding floor.
|
| 197 |
+
* Exponential Euler changes by 1.9e-4 and then 8.6e-5 ms, an observed order of 1.15.
|
| 198 |
+
* **Velocity** (40 mm cable, 18.5 °C):
|
| 199 |
+
* Quick (60 compartments, dt 0.005 ms): 9.23 / 13.15 / 18.65 m/s for 119 / 238 / 476 um. Log-log slope
|
| 200 |
+
0.507. The 476 um axon is 0.79 % below HH's computed 18.8 m/s.
|
| 201 |
+
* Default (200 compartments, dt 0.0006 ms): 9.35 / 13.24 / 18.72 m/s. Slope 0.501. 0.41 % below 18.8 m/s.
|
| 202 |
+
* Relative change at dt/2 ≤ 4.7e-7.
|
| 203 |
+
* **Paired-pulse refractory estimate** (6.3 °C; 0.5 ms pulses; conditioning 2 ×, test 4 × the single-pulse
|
| 204 |
+
threshold of 13.3 uA/cm^2): 9.45–9.63 / 9.46–9.49 ms.
|
| 205 |
+
* **NEUROWEAVE cell** (descriptive):
|
| 206 |
+
* The threshold drive is 0.277 per step.
|
| 207 |
+
* Repetitive firing starts at 1.1 × (quick) or 1.5 × (default) threshold, earlier than in HH.
|
| 208 |
+
* The normalised rate saturates at 1.0 from 3 × (quick) or 3.5 × (default) threshold upwards.
|
| 209 |
+
* Spearman rank correlation with the HH curve over the suprathreshold levels is 0.839 / 0.858, and the
|
| 210 |
+
mean absolute difference of the normalised curves is 0.20 / 0.24.
|
| 211 |
+
* The adaptation index is 0.0, so firing is regular.
|
| 212 |
+
* Curves are identical across seeds (`seed_invariant: true`).
|
| 213 |
+
|
| 214 |
+
The cable reproduces the two quantitative anchors it is checked against: the √diameter scaling of eqn 34, and
|
| 215 |
+
HH's computed velocity for their axon, to under 1 %. The abstract NEUROWEAVE cell has a monotone f-I curve of
|
| 216 |
+
broadly similar rank order. It fires repetitively closer to threshold than HH, its normalised rate saturates
|
| 217 |
+
early, and it shows no adaptation. These are shape observations only.
|
docs/frontier/modules/joint_failure.md
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `joint_failure`: joint-failure ensemble selection
|
| 2 |
+
|
| 3 |
+
Module file: `synapse/frontier/joint_failure.py` · tests: `tests/test_frontier_methodology.py` ·
|
| 4 |
+
experiment ids: `joint_failure` (kind `selection_benchmark`) and `joint_failure_neuroweave` (kind
|
| 5 |
+
`selection_application`) · no live observer · evidence tier: `synthetic_abstraction`.
|
| 6 |
+
|
| 7 |
+
The module chooses an odd-sized majority-vote **panel** of components from boolean failure observations
|
| 8 |
+
(component × condition × trial). It compares four selection rules and scores the frozen panels on held-out
|
| 9 |
+
trials.
|
| 10 |
+
|
| 11 |
+
The module is *inspired by* FAULTLINE, a kai9987kai portfolio laboratory for correlated and higher-order
|
| 12 |
+
failures in small voting ensembles. The following follow FAULTLINE's design:
|
| 13 |
+
|
| 14 |
+
* the four rules and their tie-breaking;
|
| 15 |
+
* the second factorial-moment pairwise bound;
|
| 16 |
+
* the 3-bit parity example.
|
| 17 |
+
|
| 18 |
+
These parts are this module's own:
|
| 19 |
+
|
| 20 |
+
* the NumPy array format;
|
| 21 |
+
* the seeded family generator with exact population errors;
|
| 22 |
+
* the three further constructed trap cases;
|
| 23 |
+
* the NEUROWEAVE application.
|
| 24 |
+
|
| 25 |
+
It reproduces none of FAULTLINE's recorded numbers.
|
| 26 |
+
|
| 27 |
+
## What it computes
|
| 28 |
+
|
| 29 |
+
**Data.** `failures[i, c, t]` is true when component `i` is wrong on trial `t` of condition `c`. Every
|
| 30 |
+
condition has the same number of trials `T`.
|
| 31 |
+
|
| 32 |
+
**Majority-vote error.** A panel `P` of odd size `k` votes by majority, with threshold `s = (k + 1) / 2`:
|
| 33 |
+
|
| 34 |
+
```
|
| 35 |
+
W_P(c, t) = sum_{i in P} F[i, c, t] Err(P | c) = (1/T) sum_t 1[ W_P(c, t) >= s ]
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
* **Two labels.** With binary labels every wrong member votes for the single wrong label, so this is the
|
| 39 |
+
exact vote error.
|
| 40 |
+
* **More labels.** With more labels it is an upper bound on plurality-vote error. If fewer than `s` members
|
| 41 |
+
are wrong, the correct label has a strict majority.
|
| 42 |
+
* **Signatures.** `Err` depends only on the joint failure pattern of each trial. `failure_signatures` lists,
|
| 43 |
+
per condition, every distinct set of failing components with its count. These are the empirical failure
|
| 44 |
+
hyperedges, and the list includes the empty set.
|
| 45 |
+
* **Signature path.** `majority_error_from_signatures` recomputes `Err` from those counts alone. The tests
|
| 46 |
+
check it against the array computation on every 3-member panel of random correlated data.
|
| 47 |
+
|
| 48 |
+
**Pairwise bound.** Since `1[W >= s] <= C(W, 2) / C(s, 2)`, taking expectations gives:
|
| 49 |
+
|
| 50 |
+
```
|
| 51 |
+
B(P | c) = sum_{i<j in P} Pr(F_i and F_j | c) / C(s, 2) >= Err(P | c) (k = 1: the individual error)
|
| 52 |
+
k = 3: B = Pr(W = 2) + 3 Pr(W = 3) but Err = Pr(W = 2) + Pr(W = 3)
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
A unanimous failure therefore counts three times in the pairwise score. This is FAULTLINE's argument for
|
| 56 |
+
why pairwise co-failure misranks panels with rare higher-order faults.
|
| 57 |
+
|
| 58 |
+
**Selectors.** All four use calibration trials only. Every key is an integer count, so ties are exact. A tie
|
| 59 |
+
goes to the next key and finally to the lexicographically first panel.
|
| 60 |
+
|
| 61 |
+
| policy | ranking key (minimised) |
|
| 62 |
+
|---|---|
|
| 63 |
+
| `accuracy` | `sum_{i in P}` individual failures (pooled individual error) |
|
| 64 |
+
| `pairwise` | worst-condition `B(P \| c)`, then `sum_c B(P \| c)`, then accuracy |
|
| 65 |
+
| `pooled` | pooled majority error, then worst-condition majority error, then accuracy |
|
| 66 |
+
| `joint` | worst-condition majority error `max_c Err(P \| c)`, then pooled, then accuracy |
|
| 67 |
+
|
| 68 |
+
* **Equivalence to FAULTLINE.** With equal trials per condition, the sums over conditions are proportional
|
| 69 |
+
to FAULTLINE's pooled rates. The keys therefore match FAULTLINE's `core.select_panel`, which uses exact
|
| 70 |
+
fractions and breaks the last tie by component id order.
|
| 71 |
+
* **Tested against a direct implementation.** The tests compare every selector with a direct exact-fraction
|
| 72 |
+
re-implementation of those keys. They cover 12 random correlated arrays, `k ∈ {1, 3, 5}` and all four
|
| 73 |
+
policies.
|
| 74 |
+
* **`run_selection`.** It selects on calibration, freezes the panels and scores them on the held-out test
|
| 75 |
+
trials. It also reports an `oracle`: the panel with the lowest *test* worst-condition error. The oracle
|
| 76 |
+
is chosen on test data, so it is a reference, never a selector.
|
| 77 |
+
* **`evaluate_panel`.** It reports per-condition error, worst condition, pooled error, unanimous-failure rate
|
| 78 |
+
and the worst pairwise bound.
|
| 79 |
+
* **Bounds.** At most 24 components, 64 conditions, 100,000 trials, 5,000,000 cells and 100,000 candidate
|
| 80 |
+
panels. Panels are scored in chunks of at most 2,000,000 panel-condition-trial cells. Bad input raises
|
| 81 |
+
`ValueError` before any computation.
|
| 82 |
+
|
| 83 |
+
## Constructed known-answer cases (`constructed_cases`, `check_constructed_cases`)
|
| 84 |
+
|
| 85 |
+
| case | construction | known answer |
|
| 86 |
+
|---|---|---|
|
| 87 |
+
| `parity` (FAULTLINE's example) | 3 components; `even` holds the 4 even-weight failure patterns, `odd` the 4 odd-weight ones | marginals 1/2 and pair rates 1/4 in both, majority error **3/4 vs 1/4** |
|
| 88 |
+
| `accuracy_trap` | 0–2 individually best (error 0.10) but fail together on 20 % of `stress` trials; 3–5 (0.15) never co-fail | `accuracy` picks (0, 1, 2), worst-condition error 0.20; `joint` finds a panel with 0 |
|
| 89 |
+
| `pairwise_trap` | (2, 3, 4) fails only unanimously, 10 % (bound 30 %); (0, 1, 2) fails in pairs, 18 % (bound 18 %); cross pairs make mixed panels worse | `pairwise` picks (0, 1, 2), error 0.18; `joint` picks (2, 3, 4), error 0.10 |
|
| 90 |
+
| `pooled_trap` | 0–2 fail together on 30 % of `b` trials only (pooled 0.15, worst 0.30); 3–5 fail together on 20 % of trials in both conditions | `pooled` picks worst-condition error 0.30; `joint` picks 0.20 (pooled 0.20) |
|
| 91 |
+
|
| 92 |
+
* **In the receipt.** The nine named checks are recorded in every benchmark receipt as `constructed_checks`.
|
| 93 |
+
* **Further hand cases in the tests.** One has failing sets `{}, {0}, {0,1}, {1,2}, {0,1,2}`, where
|
| 94 |
+
`Err = 3/5` exactly and the pairwise sum is `5/5`. Another is a 5-member case.
|
| 95 |
+
|
| 96 |
+
## Synthetic generator (`make_failure_data`)
|
| 97 |
+
|
| 98 |
+
**Components and conditions.** There are `families × family_size` components (default 3 × 3 = 9),
|
| 99 |
+
shuffled per seed so that tie-breaking cannot favour a family. The conditions are `nominal` plus one
|
| 100 |
+
`stress_f` per family (default 4).
|
| 101 |
+
|
| 102 |
+
* **`shared`.**
|
| 103 |
+
* Base error: family 0 (the "accurate" family) draws from `U(0.01, 0.03)`, the others from
|
| 104 |
+
`U(0.03, 0.07)`.
|
| 105 |
+
* In `stress_f`, family `f`'s stressor is active with probability `U(0.25, 0.40)`, drawn once per seed and
|
| 106 |
+
family.
|
| 107 |
+
* When active, it hits each member of family `f` with probability 0.85.
|
| 108 |
+
* **`independent`** (negative control).
|
| 109 |
+
* There is no stressor. Component `i` fails with `e_i · mu_c`, where `e_i ~ U(0.04, 0.16)`, `mu_0 = 1` and
|
| 110 |
+
`mu_c ~ U(1.0, 1.6)`.
|
| 111 |
+
* Every condition ranks the components identically. Poisson-binomial tails increase in each `p_i`, so the
|
| 112 |
+
`k` individually best components form the optimal panel in every condition.
|
| 113 |
+
* **`shift`** (unobserved common cause).
|
| 114 |
+
* Calibration is identical to `shared`.
|
| 115 |
+
* On held-out `nominal` trials a common cause is active with probability 0.6. It then hits each member of
|
| 116 |
+
a cross-family set with probability 0.9.
|
| 117 |
+
* With `shift_target='hardened'` (the default) the set is the lowest-base-error member of every family.
|
| 118 |
+
That is adversarial to diversity-based selection by construction. `'random'` draws one member per
|
| 119 |
+
family.
|
| 120 |
+
|
| 121 |
+
**Population errors.** `expected_condition_errors(structure, panel, split)` gives the exact population
|
| 122 |
+
`Err(P | c)`. Given the state of the (at most one) channel acting in a condition, components fail
|
| 123 |
+
independently, so `Err` is a mixture of Poisson-binomial tails. The tests compare it with 40,000-trial
|
| 124 |
+
Monte Carlo (within 5 standard errors).
|
| 125 |
+
|
| 126 |
+
**Digest.** Each dataset carries a SHA-256 digest of its packed arrays.
|
| 127 |
+
|
| 128 |
+
## Benchmark (`run_experiment`, id `joint_failure`)
|
| 129 |
+
|
| 130 |
+
* **Protocol.** For every seed and scenario, all four selectors see the same calibration trials and the same
|
| 131 |
+
`C(9, 3) = 84` candidate panels. The frozen panels are scored on fresh test trials.
|
| 132 |
+
* **Verdict.** `harness.compare` of joint vs accuracy held-out worst-condition error in the `shared` scenario
|
| 133 |
+
(lower is better). `improved` requires the paired 95 % t interval over seeds to exclude zero.
|
| 134 |
+
* **Also reported.**
|
| 135 |
+
* Joint vs pairwise and joint vs pooled (`shared`), and joint vs accuracy (`independent`, `shift`).
|
| 136 |
+
* The exact population error of every chosen panel.
|
| 137 |
+
* The oracle.
|
| 138 |
+
* The constructed checks.
|
| 139 |
+
* A budget: candidate panels, calibration component calls (`9 × 4 × T_cal`), `k` deployment calls per case
|
| 140 |
+
and 0 trainable parameters.
|
| 141 |
+
* **No capacity-matched control.** Every rule deploys `k` components with no trainable parameters and the
|
| 142 |
+
same calibration data, so the comparison is between selection rules at equal cost.
|
| 143 |
+
* **Sizes.** Defaults: `k = 3`, 64 calibration and 512 test trials per condition. `quick=True` uses 48 and 256.
|
| 144 |
+
Generator parameters can be overridden, and unknown keys raise `ValueError`.
|
| 145 |
+
|
| 146 |
+
## NEUROWEAVE application (`run_neuroweave_application`, id `joint_failure_neuroweave`)
|
| 147 |
+
|
| 148 |
+
* **Components.** Each component is a NEUROWEAVE engine that differs only in its mechanism set. Seed,
|
| 149 |
+
`clustered` topology, neuron count, training stream and head initialisation are shared.
|
| 150 |
+
* **Training.** Each engine is trained with the lab's `run_task_phase(learn=True)`, with one `ReadoutHead`
|
| 151 |
+
per task. The first task, `delayed_recall`, supplies the engine reward.
|
| 152 |
+
* **Conditions.** The four temporal tasks: `delayed_recall`, `xor`, `rhythm` and `context_switch`. Targets
|
| 153 |
+
are binary, so majority-of-failures equals majority-vote error exactly.
|
| 154 |
+
* **Failure recording.** Failures are recorded frozen (`learn=False`, cloned engines and head copies) on a
|
| 155 |
+
calibration stream (`seed + 50,000`) and a disjoint test stream (`seed + 60,000`). Training, calibration
|
| 156 |
+
and test stream seeds must be pairwise disjoint.
|
| 157 |
+
* **Verdict.** `harness.compare` of joint vs accuracy held-out worst-task error over seeds.
|
| 158 |
+
* **Mechanism sets.** `()`, `sparse_code`, `homeostatic_governor`, `astrocyte_regulation`, `multi_soma`,
|
| 159 |
+
`reward_plasticity` and `dendritic_compartments`. Quick mode uses the first five.
|
| 160 |
+
* **How they were chosen.** A decision-diversity probe on seed 99, which is not an evaluation seed. It
|
| 161 |
+
trained each single mechanism at 16 neurons for 120 steps and at 24 neurons for 160 steps (clustered
|
| 162 |
+
topology, one head per task) and ranked mechanisms by how many training-phase head decisions they changed
|
| 163 |
+
relative to the unmodified engine. Accuracy and selector outcomes played no part. The six sets are the
|
| 164 |
+
probe's top six, in rank order (244, 127, 116, 71, 66 and 62 changed decisions over both sizes).
|
| 165 |
+
* **Many mechanisms do nothing here.** 17 of the 45 single mechanisms changed no decision in that probe.
|
| 166 |
+
A re-run of the probe on 2026-11-20 gave the same ranking and the same 17.
|
| 167 |
+
* **Sizes.** Defaults: 7 sets, 24 neurons, 160 training / 96 calibration / 96 test steps. Quick: 5 sets,
|
| 168 |
+
16 neurons, 120 / 32 / 32 steps.
|
| 169 |
+
|
| 170 |
+
## Public API
|
| 171 |
+
|
| 172 |
+
```python
|
| 173 |
+
POLICIES = ('accuracy', 'pairwise', 'pooled', 'joint'); SCENARIOS = ('shared', 'independent', 'shift')
|
| 174 |
+
validate_failures(failures, *, name='failures') -> bool ndarray (components, conditions, trials)
|
| 175 |
+
majority_threshold(panel_size) -> int
|
| 176 |
+
majority_error(failures, panel) -> ndarray (per condition)
|
| 177 |
+
pairwise_bound(failures, panel) -> ndarray (per condition)
|
| 178 |
+
failure_signatures(failures) -> list[dict]; majority_error_from_signatures(signatures, panel) -> ndarray
|
| 179 |
+
panel_scores(failures, panel_size) -> dict; evaluate_panel(failures, panel) -> dict
|
| 180 |
+
select_panels(failures, panel_size, policies=POLICIES) -> dict[str, tuple]; select_panel(failures, panel_size, policy)
|
| 181 |
+
run_selection(calibration, test, panel_size) -> dict # every policy + oracle, frozen panels on test
|
| 182 |
+
make_failure_data(seed, *, scenario='shared', **params) -> dict
|
| 183 |
+
expected_condition_errors(structure, panel, *, split='test') -> ndarray
|
| 184 |
+
constructed_cases() -> dict; check_constructed_cases() -> dict[str, bool]
|
| 185 |
+
run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> sealed receipt
|
| 186 |
+
run_neuroweave_application(*, quick=False, seeds=(0, 1, 2), **overrides) -> sealed receipt
|
| 187 |
+
EXPERIMENTS = {'joint_failure': run_experiment, 'joint_failure_neuroweave': run_neuroweave_application}
|
| 188 |
+
```
|
| 189 |
+
|
| 190 |
+
Randomness comes only from `numpy.random.default_rng(seed + offset)`. The module never touches the global
|
| 191 |
+
NumPy RNG, never imports torch, and has no stateful observer or extension to export or import.
|
| 192 |
+
|
| 193 |
+
## Connection to Sonapse
|
| 194 |
+
|
| 195 |
+
* **What it consumes.** This is a methodology module. It does not attach to an engine or observe live
|
| 196 |
+
activity. It consumes failure arrays, so any set of Sonapse or NEUROWEAVE components with per-trial
|
| 197 |
+
correctness under named conditions can be compared. The application builds those arrays from per-task
|
| 198 |
+
readout correctness of differently configured engines.
|
| 199 |
+
* **What it uses.** The NEUROWEAVE lab helpers (`make_spec`, `ReadoutHead`, `run_task_phase`,
|
| 200 |
+
`clone_engine`, `make_stream`) and `synapse.frontier.harness` (`base_receipt`, `compare`, `seal`,
|
| 201 |
+
`TASKS`).
|
| 202 |
+
* **Scope.** It does not change any engine or any other module.
|
| 203 |
+
|
| 204 |
+
## Differences from FAULTLINE and not implemented
|
| 205 |
+
|
| 206 |
+
* **Data.** FAULTLINE reads `faultline-dataset-v1` JSON (ids, truth, predictions; 3–12 components; unequal
|
| 207 |
+
trials per condition allowed). This module takes boolean failure arrays with equal trials per condition
|
| 208 |
+
and up to 24 components.
|
| 209 |
+
* **Fixtures.**
|
| 210 |
+
* FAULTLINE's fixtures are 8 named sensor specialists with hand-designed regimes, driven by event-keyed
|
| 211 |
+
SHA-256 draws. They include `glare_surge` faults that hit five components at once and a latent clock
|
| 212 |
+
fault on a hardened triad.
|
| 213 |
+
* The generator here is parametric and has no composed higher-order faults. On it the `pairwise`,
|
| 214 |
+
`pooled` and `joint` rules chose the same panels in every measured seed of the `shared` scenario.
|
| 215 |
+
* Their differences are therefore shown only on the constructed traps.
|
| 216 |
+
* **Not implemented.**
|
| 217 |
+
* FAULTLINE's receipts and replay verifier, HTTP API, browser UI, test witnesses, bootstrap intervals and
|
| 218 |
+
dataset import.
|
| 219 |
+
* Plurality or weighted voting.
|
| 220 |
+
* Any defence against common causes absent from calibration. No rule here protects against them, and the
|
| 221 |
+
`shift` scenario exists to show that.
|
| 222 |
+
|
| 223 |
+
## Source (portfolio)
|
| 224 |
+
|
| 225 |
+
* **FAULTLINE: Joint-Failure Ensemble Selection Laboratory** (kai9987kai).
|
| 226 |
+
<https://github.com/kai9987kai/FAULTLINE>.
|
| 227 |
+
* **Files read.** In a read-only clone at commit `b7ae1b9` (24 October 2026), the following were read on
|
| 228 |
+
2026-11-20:
|
| 229 |
+
* `README.md`;
|
| 230 |
+
* `docs/design.md` (design decision dated 24 October 2026);
|
| 231 |
+
* `PAPER.md` (dated 24 October 2026);
|
| 232 |
+
* `faultline/core.py` (selector keys and metrics);
|
| 233 |
+
* `faultline/fixtures.py` (scenarios and the parity demo).
|
| 234 |
+
* **Nothing executed.** No FAULTLINE code was run.
|
| 235 |
+
* **Not re-verified.** The literature FAULTLINE cites was not re-checked for this module and is not cited
|
| 236 |
+
here.
|
| 237 |
+
|
| 238 |
+
## Measured results
|
| 239 |
+
|
| 240 |
+
All numbers were measured on 2026-11-20 (UTC) on Windows 11 ARM64 with Python 3.12.10 and NumPy 2.4.3, with
|
| 241 |
+
`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1`. Other agents shared the CPU, so wall-clock is
|
| 242 |
+
indicative only. Errors are held-out (test) majority-vote errors averaged over seeds `(0, 1, 2)`. "pop." is
|
| 243 |
+
the exact population worst-condition error of the chosen panels under the generator.
|
| 244 |
+
|
| 245 |
+
**Benchmark, quick** (`run_experiment(quick=True)`: 9 components, 4 conditions, `k = 3`, 48 calibration and
|
| 246 |
+
256 test trials per condition).
|
| 247 |
+
|
| 248 |
+
| scenario | accuracy | pairwise | pooled | joint | oracle | joint − accuracy, 95 % CI |
|
| 249 |
+
|---|---|---|---|---|---|---|
|
| 250 |
+
| `shared` | 0.160 (pop. 0.155) | 0.038 | 0.038 | 0.038 (pop. 0.029) | 0.021 | −0.122 [−0.387, +0.143] |
|
| 251 |
+
| `independent` | 0.030 (pop. 0.027) | 0.035 | 0.035 | 0.035 (pop. 0.034) | 0.022 | +0.005 [−0.010, +0.020] |
|
| 252 |
+
| `shift` | 0.398 (pop. 0.414) | 0.197 | 0.197 | 0.197 (pop. 0.197) | 0.027 | −0.202 [−0.756, +0.352] |
|
| 253 |
+
|
| 254 |
+
* **Verdict.** **no_detectable_difference**.
|
| 255 |
+
* **Per-seed `shared` differences.** 0.000, −0.195 and −0.172. In seed 0 `accuracy` happened to pick the
|
| 256 |
+
same panel as the other rules.
|
| 257 |
+
* **Other values.** All 9 constructed checks pass. The digest prefix is `2ef7216676bbedb6` (identical across
|
| 258 |
+
separate processes). Wall-clock was 0.08–0.10 s.
|
| 259 |
+
|
| 260 |
+
**Benchmark, default** (`run_experiment()`: 64 calibration and 512 test trials per condition).
|
| 261 |
+
|
| 262 |
+
| scenario | accuracy | pairwise | pooled | joint | oracle | joint − accuracy, 95 % CI |
|
| 263 |
+
|---|---|---|---|---|---|---|
|
| 264 |
+
| `shared` | 0.258 (pop. 0.259) | 0.027 | 0.027 | 0.027 (pop. 0.028) | 0.023 | **−0.231 [−0.239, −0.224]** |
|
| 265 |
+
| `independent` | 0.029 (pop. 0.026) | 0.038 | 0.028 | 0.028 (pop. 0.028) | 0.025 | −0.001 [−0.004, +0.002] |
|
| 266 |
+
| `shift` | 0.327 (pop. 0.335) | 0.382 | 0.382 | 0.382 (pop. 0.373) | 0.029 | +0.055 [−0.977, +1.086] |
|
| 267 |
+
|
| 268 |
+
* **Verdict.** **improved**: joint selection lowered held-out worst-condition error in `shared`.
|
| 269 |
+
* **Other values.** All 9 constructed checks pass. The digest prefix is `1bfc6d4ab8e769a7` (identical in two
|
| 270 |
+
separate runs). Wall-clock was 0.10–0.20 s.
|
| 271 |
+
* **Same panels.** `pairwise`, `pooled` and `joint` chose the same panel in every `shared` seed of the quick,
|
| 272 |
+
default and ten-seed runs.
|
| 273 |
+
* **Ten seeds.** A further run, `run_experiment(seeds=range(10))` at default size, gave these joint −
|
| 274 |
+
accuracy differences:
|
| 275 |
+
* `shared`: −0.224 [−0.243, −0.206], improved;
|
| 276 |
+
* `independent`: +0.002 [−0.007, +0.011];
|
| 277 |
+
* `shift`: −0.023 [−0.236, +0.189].
|
| 278 |
+
|
| 279 |
+
**NEUROWEAVE application.**
|
| 280 |
+
|
| 281 |
+
| | quick (5 sets, 16 neurons, 120/32/32 steps) | default (7 sets, 24 neurons, 160/96/96 steps) |
|
| 282 |
+
|---|---|---|
|
| 283 |
+
| verdict | **no_detectable_difference** | **no_detectable_difference** |
|
| 284 |
+
| joint − accuracy worst-task error (95 % CI) | 0.000 [0.000, 0.000] | −0.031 [−0.166, +0.103] (per seed −0.094, 0, 0) |
|
| 285 |
+
| mean worst-task error: accuracy / pairwise / pooled / joint / oracle | 0.563 / 0.552 / 0.563 / 0.563 / 0.552 | 0.552 / 0.521 / 0.552 / 0.521 / 0.507 |
|
| 286 |
+
| best single component's worst-task error (per seed) | 0.438 / 0.563 / 0.500 | 0.365 / 0.583 / 0.469 |
|
| 287 |
+
| oracle panel's worst-task error (per seed; chosen on test data) | 0.594 / 0.563 / 0.500 | 0.469 / 0.583 / 0.469 |
|
| 288 |
+
| components with identical calibration failures (pairs) | 1 / 6 / 1 of 10 | 0 / 0 / 0 of 21 |
|
| 289 |
+
| mean pairwise calibration-failure agreement | 0.68 / 0.86 / 0.79 | 0.88 / 0.87 / 0.67 |
|
| 290 |
+
| a component's mean test accuracy over tasks (min–max over components and seeds) | 0.49–0.65 | 0.53–0.72 |
|
| 291 |
+
| digest (prefix) | `1f7709e86ceea33e` (identical across separate processes) | `6f1e1af36c5f24f6` (identical in separate runs) |
|
| 292 |
+
| measured wall-clock | 9.7–10.9 s | 25.2–27.9 s |
|
| 293 |
+
|
| 294 |
+
Reading:
|
| 295 |
+
|
| 296 |
+
* **Synthetic benchmark.** Joint-failure selection removes the shared-stressor failure mode that accuracy
|
| 297 |
+
selection walks into. The improvement shows at default size and over ten seeds. Quick mode is too small,
|
| 298 |
+
with 3 seeds and one tie.
|
| 299 |
+
* **Negative controls.** The independent control shows no difference, as it should. In the unobserved
|
| 300 |
+
common-cause scenario the advantage disappears: every rule is far from the oracle, and joint is not
|
| 301 |
+
significantly better or worse than accuracy.
|
| 302 |
+
* **What this generator cannot separate.** It does not distinguish `joint` from `pairwise` or `pooled`.
|
| 303 |
+
* **NEUROWEAVE.** The readouts are close to chance on most tasks and their failures are strongly correlated.
|
| 304 |
+
No selector beats another detectably. In all six measured seed runs (quick and default), even the oracle
|
| 305 |
+
panel was no better than the best single component on test worst-task error: worse in seed 0, equal in
|
| 306 |
+
seeds 1 and 2. These runs exercise the pipeline on real engine outputs; they are not evidence for any
|
| 307 |
+
mechanism or selector.
|
docs/frontier/modules/kuramoto_binding.md
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `kuramoto_binding`: oscillatory binding units
|
| 2 |
+
|
| 3 |
+
Module file: `synapse/frontier/kuramoto.py` · tests: `tests/test_frontier_kuramoto.py` ·
|
| 4 |
+
experiment ids: `kuramoto_binding`, `kuramoto_binding_benchmark` · engine extension: `KuramotoExtension` ·
|
| 5 |
+
live observer: `KuramotoObserver` · evidence tier: `synthetic_abstraction`.
|
| 6 |
+
|
| 7 |
+
The module implements the discrete oscillator update of **Artificial Kuramoto Oscillatory Neurons** (AKOrN,
|
| 8 |
+
Miyato et al., ICLR 2025) and uses it in three small settings:
|
| 9 |
+
|
| 10 |
+
* a NEUROWEAVE engine extension that adds synchrony features to the readout,
|
| 11 |
+
* a read-only live observer of unit activity,
|
| 12 |
+
* a synthetic binding benchmark with a known answer.
|
| 13 |
+
|
| 14 |
+
It is *inspired by* AKOrN and does not reproduce it. Couplings here are fixed rather than learned. There are no
|
| 15 |
+
convolutional or attention couplings, no readout blocks and no training. None of the paper's tasks or results
|
| 16 |
+
(object discovery, adversarial robustness, calibration, Sudoku) are attempted. The oscillators are an abstract
|
| 17 |
+
computational device, not a model of neural oscillations.
|
| 18 |
+
|
| 19 |
+
## What it computes
|
| 20 |
+
|
| 21 |
+
**Oscillators.** Each oscillator is a unit vector `x_i` in `R^N`, with `N` even and `N = 2` by default. The
|
| 22 |
+
update is the paper's Eq. 2 in discrete form (Eqs. 4–5):
|
| 23 |
+
|
| 24 |
+
```
|
| 25 |
+
dx_i = Omega_i x_i + Proj_{x_i}( c_i + sum_j J_ij x_j ) Proj_x(y) = y - <y, x> x
|
| 26 |
+
x_i <- Pi( x_i + gamma * dx_i ) Pi(v) = v / ||v||
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
* `Omega_i` is antisymmetric: a natural-frequency block `[[0, -w], [w, 0]]` on each coordinate plane
|
| 30 |
+
`(2p, 2p+1)`.
|
| 31 |
+
* `c_i` is the conditional stimulus.
|
| 32 |
+
* `J_ij` is a scalar coupling (`J_ij * I_N`). A full `(C*N, C*N)` block matrix is also accepted, and
|
| 33 |
+
`kron(J, I_N)` gives exactly the scalar result (tested).
|
| 34 |
+
* `K` iterations run per call (`akorn_step`, `akorn_run`).
|
| 35 |
+
|
| 36 |
+
Properties that are tested:
|
| 37 |
+
|
| 38 |
+
* The projection is tangent (`<Proj_x(y), x> = 0`) and idempotent, and every update returns unit rows.
|
| 39 |
+
* With `J = 0` and `c = 0`, each rotation plane advances by exactly `arctan(gamma * w)` per step. The plane
|
| 40 |
+
amplitudes change when frequencies differ. As `gamma -> 0`, the phase follows `dtheta/dt = w`.
|
| 41 |
+
* Uniform positive coupling `2/(C-1)` takes `R` from 0.05 to 1 (to `1 - 1e-9` with identical frequencies, and
|
| 42 |
+
above 0.99 with a 0.1 frequency spread, for both `N = 2` and `N = 4`). Uniform negative coupling drives
|
| 43 |
+
`R` below `1e-6`.
|
| 44 |
+
* The energy `E = -1/2 sum_ij x_i^T J_ij x_j - sum_i c_i^T x_i` (paper Eq. 3, `kuramoto_energy`) never
|
| 45 |
+
increases by more than `1e-12` per step under the paper's Lyapunov conditions. Those conditions are symmetric
|
| 46 |
+
scalar couplings, a shared `Omega` (here 0) and `Omega c_i = 0`. The tested regime is `gamma = 0.1` with
|
| 47 |
+
`||J||_2 = 1`.
|
| 48 |
+
|
| 49 |
+
**Measures.**
|
| 50 |
+
|
| 51 |
+
* Order parameter `R = ||mean_i x_i||`, and per-group coherence `||mean_{i in g} x_i||`.
|
| 52 |
+
* Phase `atan2(x_1, x_0)`. This is the first rotation plane, which is exact for `N = 2`.
|
| 53 |
+
* Phase-locking value `|mean_t exp(i (phi_a - phi_b))|`. It is a time-averaged variant of the PLV of Lachaux
|
| 54 |
+
et al. (1999); the extension uses an exponentially weighted, bias-corrected average over engine steps.
|
| 55 |
+
* Phase-cluster count: the number of circular runs of *dense* bins in a 36-bin angle histogram. A bin is dense
|
| 56 |
+
when it holds at least 10 % of the oscillators. An incoherent population, or one with no sparse bin at all,
|
| 57 |
+
gives 0. A cluster smaller than about 20 % of the population can be missed if it straddles a bin edge.
|
| 58 |
+
* Shanahan (2010) indices from the community synchrony `phi_c(t)`, with the paper's sample variances:
|
| 59 |
+
* Metastability `lambda`: the mean over communities of `1/(T-1) sum_t (phi_c(t) - <phi_c>)^2`.
|
| 60 |
+
* Chimera index `chi`: the mean over time of `1/(M-1) sum_c (phi_c(t) - <phi(t)>)^2`.
|
| 61 |
+
|
| 62 |
+
The tests reproduce the paper's reference values: `sigma_chi = 2/7` for a "perfect" chimera state,
|
| 63 |
+
`chi_max = 1/7`, and `sigma_met -> 1/12` for uniformly distributed synchrony.
|
| 64 |
+
* Adjusted Rand index (Hubert & Arabie, 1985), implemented in NumPy from the contingency table. It returns 1
|
| 65 |
+
for identical partitions, including the degenerate one-cluster and all-singleton cases. The tests check it
|
| 66 |
+
against hand cases (`24/99`, `-1/2`, `4/7`) and against a brute-force pair-counting formula.
|
| 67 |
+
* Seeded k-means with k-means++ seeding (Arthur & Vassilvitskii, 2007). It runs several restarts, and the
|
| 68 |
+
lowest inertia wins.
|
| 69 |
+
|
| 70 |
+
## Engine extension (`KuramotoExtension`, id `kuramoto_binding`)
|
| 71 |
+
|
| 72 |
+
```python
|
| 73 |
+
KuramotoExtension(seed=0, *, mode='region', units=16, dim=2, iterations=4, gamma=0.1, coupling_scale=1.0,
|
| 74 |
+
stimulus_scale=1.0, omega_mean=1.0, omega_spread=0.5, top_pairs=4, plv_rate=0.1)
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
**Oscillators.** In `mode='region'` there is one oscillator per NEUROWEAVE region (10). In `mode='units'`
|
| 78 |
+
there is one oscillator per unit, for `units` units sampled at `bind` with the extension seed.
|
| 79 |
+
|
| 80 |
+
**Coupling (copied at `bind`).** The engine itself is not kept.
|
| 81 |
+
|
| 82 |
+
* Synapse weights `brain.synapses.w` are summed over `src -> dst` into `J[group(dst), group(src)]`.
|
| 83 |
+
* Each row is divided by the size of its target group, which gives the mean input per target unit.
|
| 84 |
+
* The diagonal is zeroed, because self-coupling vanishes under the projection.
|
| 85 |
+
* `J` is scaled so that its largest absolute row sum equals `|coupling_scale|`.
|
| 86 |
+
* Inhibitory synapses give negative (anti-phase) couplings.
|
| 87 |
+
* `J` is a snapshot: later plasticity is not tracked.
|
| 88 |
+
|
| 89 |
+
**Stimulus.** `c_g = stimulus_scale * m_g * u_g`, where `m_g` is the group's current mean output and `u_g` is a
|
| 90 |
+
fixed, seeded unit vector.
|
| 91 |
+
|
| 92 |
+
**Dynamics.** Each engine step runs `iterations` AKOrN updates. Natural frequencies are
|
| 93 |
+
`omega_mean + omega_spread * N(0, 1)`, drawn per oscillator and plane.
|
| 94 |
+
|
| 95 |
+
**Features.** There are `feature_dim = C + 1 + top_pairs` of them: **15** in region mode with the defaults. All
|
| 96 |
+
lie in `[-1, 1]`.
|
| 97 |
+
|
| 98 |
+
1. `C` cosines between each oscillator and the global mean-field direction. These are 0 when `R` is about 0.
|
| 99 |
+
Like the other two blocks, they only see relative phases: rotating every oscillator by the same angle leaves
|
| 100 |
+
all features unchanged (tested to `1e-12`).
|
| 101 |
+
2. The global order parameter `R`.
|
| 102 |
+
3. The `top_pairs` largest pairwise PLVs, in descending order.
|
| 103 |
+
|
| 104 |
+
**Rules.**
|
| 105 |
+
|
| 106 |
+
* The extension only adds readout features. `transform_drive` is the neutral base method, and the tests check
|
| 107 |
+
that the engine's trajectory and exported state are bit-identical with and without it.
|
| 108 |
+
* It has no trainable parameters (`parameter_count() == 0`). It is therefore frozen when `ctx['learn']` is
|
| 109 |
+
false, and its oscillator state evolves the same way in both cases.
|
| 110 |
+
* It is deep-copyable.
|
| 111 |
+
* `export_state` and `import_state` round-trip exactly through JSON. `import_state` validates everything before
|
| 112 |
+
mutating: config, `n`, shapes, finiteness, unit norm, `|PLV| <= 1` and a zero coupling diagonal.
|
| 113 |
+
* Accessors return copies: `coupling_matrix()` and `states()`.
|
| 114 |
+
* `telemetry()` reports the order parameter, mean and max PLV, and coupling statistics.
|
| 115 |
+
|
| 116 |
+
## Live observer (`KuramotoObserver`)
|
| 117 |
+
|
| 118 |
+
```python
|
| 119 |
+
KuramotoObserver(n_units, *, seed=7, history=256, oscillators=64, dim=2, iterations=2, gamma=0.1, omega_mean=1.0,
|
| 120 |
+
omega_spread=0.3, fan_in=4, coupling=0.5, hebbian_rate=0.01, hebbian_scale=2.0, stimulus_scale=0.5,
|
| 121 |
+
communities=8, groups=None, bins=36, min_cluster_fraction=0.1, **spec_params)
|
| 122 |
+
KuramotoObserver.from_spec(n_units, spec: FrontierSpecV1, **params) # uses spec.seed and spec.history
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
**Oscillators and stimulus.** There are `M = min(oscillators, n_units)` oscillators, each driven by one
|
| 126 |
+
subsampled unit (seeded, sorted indices). The stimulus is `c_i = stimulus_scale * tanh(rate_i) * u_i`.
|
| 127 |
+
|
| 128 |
+
**Coupling.** `J = J0 + hebbian_scale * H / sqrt(M - 1)`.
|
| 129 |
+
|
| 130 |
+
* `J0` is fixed, seeded and sparse: `fan_in` partners per oscillator, each with weight `coupling / fan_in`.
|
| 131 |
+
* `H` is a slow Hebbian co-activity estimate, built as follows:
|
| 132 |
+
* Rates are standardised with a running EWMA mean and variance (rate 0.05) and clipped to ±3 sd.
|
| 133 |
+
* `S <- (1 - eta) S + eta z z^T` starts at the identity, a shrinkage prior.
|
| 134 |
+
* `H_ij = S_ij / sqrt(S_ii S_jj)` off the diagonal, so `|H| <= 1`.
|
| 135 |
+
|
| 136 |
+
The tests check that `H` recovers a two-block correlation structure: above 0.95 within blocks, where the true
|
| 137 |
+
value is 0.99, and below 0.1 across blocks. They also check that `J - hebbian_scale * H / sqrt(M - 1)` stays
|
| 138 |
+
equal to the fixed `J0`.
|
| 139 |
+
|
| 140 |
+
**Communities.** Shanahan's indices are computed over communities: contiguous blocks of the sampled unit order
|
| 141 |
+
(NEUROWEAVE regions are contiguous unit blocks), or the given `groups` labels.
|
| 142 |
+
|
| 143 |
+
**`summary()` keys.** The summary is JSON-safe and contains no wall-clock.
|
| 144 |
+
|
| 145 |
+
* Always present: `module`, `evidence_tier`, `observed_steps`, `history_len`, `history`, `oscillators`, `dim`,
|
| 146 |
+
`communities`, `hebbian_mean_abs` and `hebbian_max_abs`.
|
| 147 |
+
* `None` before the first observation: `R_last`, `R_mean` and `R_std` (the standard deviation of `R` over the
|
| 148 |
+
history, a metastability measure), `metastability_index`, `chimera_index`, `community_R_mean`,
|
| 149 |
+
`phase_clusters` (the latest histogram count) and `phase_clusters_mean`.
|
| 150 |
+
|
| 151 |
+
**Rules.**
|
| 152 |
+
|
| 153 |
+
* The observer copies its input and never writes to it.
|
| 154 |
+
* All buffers have a fixed size.
|
| 155 |
+
* `export_state` and `import_state` (schema `KuramotoObserverStateV1`) round-trip bit-exactly. Imports are fully
|
| 156 |
+
validated before any state changes.
|
| 157 |
+
* Unknown keyword parameters raise `ValueError`. `FrontierSpecV1` parameters meant for other observers
|
| 158 |
+
(`sync_pairs`, `sae_features`, `sae_k`, `fc_window`, `max_observed_units`, `observe_every`) are accepted and
|
| 159 |
+
ignored.
|
| 160 |
+
|
| 161 |
+
## Binding benchmark (`run_binding_benchmark`, id `kuramoto_binding_benchmark`)
|
| 162 |
+
|
| 163 |
+
**Task.** There are `groups` latent signals `s_g(t) ~ N(0, 1)`. Feature `i` of group `g` is
|
| 164 |
+
`a_i s_g(t) + noise * eps_i(t)`, with loading `a_i ~ U(0.5, 1.5)`.
|
| 165 |
+
|
| 166 |
+
**Candidate coupling.** The Pearson correlation of the feature rows, minus the mean off-diagonal correlation
|
| 167 |
+
(a uniform inhibition), with a zero diagonal. It is scaled so that the largest absolute row sum equals
|
| 168 |
+
`coupling_scale` (2.0).
|
| 169 |
+
|
| 170 |
+
**Dynamics.** The stimulus is `c_i = 0`, so binding comes from the coupling alone. Each seed draws its own
|
| 171 |
+
initial states and near-identical natural frequencies (`1 ± 0.05`), and all arms of that seed share them.
|
| 172 |
+
|
| 173 |
+
**Readout.** Seeded k-means (`k = groups`) on the final unit vectors after `K` iterations, scored by the ARI
|
| 174 |
+
against the ground truth. The receipt also records the ARI at the checkpoints `0, K/8, K/4, K/2, K`.
|
| 175 |
+
|
| 176 |
+
**Arms.**
|
| 177 |
+
|
| 178 |
+
* `candidate`: the correlation coupling.
|
| 179 |
+
* `shuffled_control`: the same multiset of coupling values, permuted and kept symmetric.
|
| 180 |
+
* `zero_control`: no coupling.
|
| 181 |
+
* `reference_correlation_kmeans`: a non-oscillatory reference, k-means on the correlation rows.
|
| 182 |
+
|
| 183 |
+
**Verdict.** The verdict is `harness.compare` (a paired 95 % t interval over seeds) of candidate against
|
| 184 |
+
shuffled-control ARI. The candidate and the shuffled control have the same coupling budget.
|
| 185 |
+
|
| 186 |
+
**Defaults.**
|
| 187 |
+
|
| 188 |
+
* Full: `groups=4, per_group=8, samples=256, dim=2, iterations=120, gamma=0.1`.
|
| 189 |
+
* Quick: `groups=3, per_group=6, samples=128`.
|
| 190 |
+
|
| 191 |
+
**Diagnostics.** Per seed, the receipt reports:
|
| 192 |
+
|
| 193 |
+
* `within_group_R`: the mean ground-truth group coherence.
|
| 194 |
+
* `global_R`.
|
| 195 |
+
* `max_group_cosine`: the largest cosine between two groups' mean-field directions. A value near 1 means two
|
| 196 |
+
groups ended up in phase.
|
| 197 |
+
|
| 198 |
+
**Limitation (measured).** With symmetric scalar couplings, the between-group repulsion only constrains the
|
| 199 |
+
resultant of the group mean fields. Any arrangement whose resultant is zero is an equilibrium. For four or more
|
| 200 |
+
groups that includes two groups settling nearly in phase. The same happens for three groups whose latents are
|
| 201 |
+
correlated by chance in a short sample. Groups still synchronise internally (per-seed `within_group_R` between
|
| 202 |
+
0.89 and 1.00 in every cell of the sweep below), but the ARI drops, to 0.41 at worst.
|
| 203 |
+
|
| 204 |
+
The table below is a pilot sweep: mean (min) ARI over seeds 0–9 at 120 iterations, with `noise = 1`. It was
|
| 205 |
+
measured on 2026-11-17 with the shipped coupling rule, and a second run later that day gave identical numbers
|
| 206 |
+
(the runs are deterministic). In the same sweep, the shuffled-coupling controls stayed within ±0.05 mean ARI
|
| 207 |
+
(largest magnitude 0.033).
|
| 208 |
+
|
| 209 |
+
| groups × per_group, samples | N = 2 | N = 4 | N = 8 |
|
| 210 |
+
|---|---|---|---|
|
| 211 |
+
| 3 × 6, T = 48 | 0.902 (0.54) | 0.943 (0.60) | 0.948 (0.83) |
|
| 212 |
+
| 4 × 8, T = 64 | 0.705 (0.41) | 0.794 (0.58) | 0.791 (0.59) |
|
| 213 |
+
| 4 × 8, T = 256 | 0.910 (0.45) | 0.991 (0.91) | 1.000 (1.00) |
|
| 214 |
+
| 6 × 6, T = 128 | 0.749 (0.46) | 0.912 (0.77) | 0.916 (0.77) |
|
| 215 |
+
|
| 216 |
+
Two things drive the result. More samples give more accurate couplings, and larger `N` gives more room to keep
|
| 217 |
+
groups apart. At `N = 2` with four groups (4 × 8, seeds 0–9), running longer does not help. At 120, 160, 200 and
|
| 218 |
+
240 iterations the mean ARI was 0.910, 0.917, 0.904 and 0.905 with `T = 256`, and 0.913, 0.957, 0.929 and 0.846
|
| 219 |
+
with `T = 512`: no upward trend.
|
| 220 |
+
|
| 221 |
+
The task is also easy for direct clustering of the correlation matrix. Over the same seeds 0–9, the
|
| 222 |
+
non-oscillatory reference arm scored mean ARI 1.000 in every sweep cell except 3 × 6 with `T = 48`, where it
|
| 223 |
+
scored 0.983 (min 0.83). That is at or above the oscillators in every cell. The benchmark therefore tests that
|
| 224 |
+
the oscillator dynamics *implement* binding. It does not show that they beat conventional clustering.
|
| 225 |
+
|
| 226 |
+
## Lab experiment (`run_experiment`, id `kuramoto_binding`)
|
| 227 |
+
|
| 228 |
+
`harness.run_extension_experiment('kuramoto_binding', ...)` on the NEUROWEAVE `context_switch` task compares
|
| 229 |
+
three arms:
|
| 230 |
+
|
| 231 |
+
* `baseline`: the unmodified engine and readout.
|
| 232 |
+
* `candidate`: `KuramotoExtension` with its 15 features.
|
| 233 |
+
* `control`: random leaky traces with the same feature count (the harness's `random_trace` control).
|
| 234 |
+
|
| 235 |
+
All arms share seeds, streams and the readout protocol, and held-out streams are evaluated frozen. The headline
|
| 236 |
+
verdict requires a win over both the baseline and the capacity-matched control. Extension parameters and
|
| 237 |
+
harness run parameters (`task`, `steps`, `neurons`, ...) can be overridden. `quick=True` uses the harness quick
|
| 238 |
+
sizes: 24 neurons, 24 training steps, and one 12-step held-out stream.
|
| 239 |
+
|
| 240 |
+
## Public API
|
| 241 |
+
|
| 242 |
+
```python
|
| 243 |
+
MODULE_ID = 'kuramoto_binding'; BENCHMARK_ID = 'kuramoto_binding_benchmark'
|
| 244 |
+
EXPERIMENTS = {'kuramoto_binding': run_experiment, 'kuramoto_binding_benchmark': run_binding_benchmark}
|
| 245 |
+
run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed receipt
|
| 246 |
+
run_binding_benchmark(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed receipt
|
| 247 |
+
project_tangent(x, y); natural_frequency_matrices(frequencies, dim)
|
| 248 |
+
akorn_step(x, coupling=None, stimulus=None, omega=None, *, gamma=0.1)
|
| 249 |
+
akorn_run(x, coupling=None, stimulus=None, omega=None, *, gamma=0.1, iterations=16)
|
| 250 |
+
kuramoto_energy(x, coupling=None, stimulus=None); order_parameter(x); group_coherence(x, labels, n_groups=None)
|
| 251 |
+
phases(x); phase_locking_value(phase_a, phase_b); count_phase_clusters(phase, *, bins=36, min_fraction=0.1)
|
| 252 |
+
shanahan_indices(community_order); adjusted_rand_index(labels_true, labels_pred)
|
| 253 |
+
kmeans_labels(points, k, *, seed=0, restarts=8, max_iter=100)
|
| 254 |
+
make_binding_task(seed, *, groups=4, per_group=8, samples=64, noise=1.0)
|
| 255 |
+
correlation_coupling(features, *, scale=2.0, center=True); shuffle_coupling(coupling, seed)
|
| 256 |
+
```
|
| 257 |
+
|
| 258 |
+
All randomness comes from `numpy.random.default_rng(seed + offset)`. Every public function validates its input
|
| 259 |
+
and raises `ValueError` on bad input.
|
| 260 |
+
|
| 261 |
+
## Connection to Sonapse
|
| 262 |
+
|
| 263 |
+
* **Live observer.** `kuramoto_binding` is in `spec.OBSERVER_MODULE_IDS`, so a `FrontierSpecV1` can list it in
|
| 264 |
+
`modules`. The observer reads a copy of activity and never writes to the brain, graft bus, actor or any
|
| 265 |
+
shared RNG. This module does not wire it into the live runtime; the runtime hook lives elsewhere.
|
| 266 |
+
* **Engine extension.** It influences nothing unless it is attached to a NEUROWEAVE engine with
|
| 267 |
+
`attach_extension`, as in the lab experiment. Even when attached, it only adds readout features.
|
| 268 |
+
* **Defaults.** No Sonapse or NEUROWEAVE default, API or checkpoint format changes.
|
| 269 |
+
|
| 270 |
+
## Not implemented
|
| 271 |
+
|
| 272 |
+
* Learned couplings, frequencies or step size. In the paper, `J`, `Omega` and `gamma` are learned per layer.
|
| 273 |
+
* Convolutional or attention connectivity, and multi-block AKOrN networks.
|
| 274 |
+
* The paper's readout block (norms of learned projections, Eq. 6).
|
| 275 |
+
* Training through the dynamics, and any of the paper's tasks or results.
|
| 276 |
+
* In the extension, couplings that track later synaptic plasticity: `J` is a snapshot taken at `bind`.
|
| 277 |
+
* A stimulus in the binding benchmark. A symmetry-breaking stimulus might resolve the group-collision
|
| 278 |
+
degeneracy described above, but it is not tested here.
|
| 279 |
+
|
| 280 |
+
## Verified references
|
| 281 |
+
|
| 282 |
+
Each reference below was checked on 2026-11-17 against the arXiv, conference, publisher, Crossref or PubMed
|
| 283 |
+
listing (checked twice that day, the second time in a separate session). On 2026-11-20 (review) the AKOrN
|
| 284 |
+
title, authors and update rule (Eq. 2, the projection, and the discrete Eqs. 4–5 with `Pi(x) = x / ||x||`)
|
| 285 |
+
were re-checked against the arXiv HTML of v3; `akorn_step` matches them.
|
| 286 |
+
|
| 287 |
+
1. Takeru Miyato, Sindy Löwe, Andreas Geiger, Max Welling. **Artificial Kuramoto Oscillatory Neurons.**
|
| 288 |
+
*International Conference on Learning Representations (ICLR) 2025*, oral, held 24–28 April 2025 at the
|
| 289 |
+
Singapore EXPO. arXiv:2410.13821 (v1 17 October 2024, v2 14 February 2025, v3 16 May 2025; arXiv comment
|
| 290 |
+
"Accepted for Oral presentation at ICLR2025"). https://arxiv.org/abs/2410.13821 ·
|
| 291 |
+
https://iclr.cc/virtual/2025/oral/31776. The update rule (Sec. 3 Eq. 2 and Sec. 4 Eqs. 4–5), the projection
|
| 292 |
+
`Proj_x(y) = y - <y, x> x`, the energy and its Lyapunov conditions (Eq. 3: `J_ij = J_ij I` with
|
| 293 |
+
`J_ij = J_ji`, `Omega_i = Omega`, `Omega c_i = 0`), and the readout (Eq. 6) were checked against the paper's
|
| 294 |
+
method section (arXiv HTML of v3).
|
| 295 |
+
2. Murray Shanahan. **Metastable chimera states in community-structured oscillator networks.**
|
| 296 |
+
*Chaos* 20(1), 013108, March 2010 issue (published online 22 February 2010, per Crossref).
|
| 297 |
+
doi:10.1063/1.3305451, https://pubs.aip.org/aip/cha/article/20/1/013108/280633 · arXiv:0908.3881. The
|
| 298 |
+
definitions of `lambda` (variance over time with `1/(T-1)`) and `chi` (variance over communities with
|
| 299 |
+
`1/(M-1)`), and the reference values 1/12, 2/7 (eight communities, half fully synchronised) and 1/7, were
|
| 300 |
+
checked against the text of the arXiv PDF.
|
| 301 |
+
3. Jean-Philippe Lachaux, Eugenio Rodriguez, Jacques Martinerie, Francisco J. Varela. **Measuring phase
|
| 302 |
+
synchrony in brain signals.** *Human Brain Mapping* 8(4), 194–208, 1999 (PubMed Central lists the issue date
|
| 303 |
+
as 30 November 1999). doi:10.1002/(SICI)1097-0193(1999)8:4<194::AID-HBM4>3.0.CO;2-C,
|
| 304 |
+
https://pubmed.ncbi.nlm.nih.gov/10619414/ (PMID 10619414, PMC6873296). Only the bibliographic details and
|
| 305 |
+
the abstract were verified; the abstract names the method "phase-locking statistics". The full-text PLV
|
| 306 |
+
definition could not be opened in this build, so the module calls its measure a time-averaged *variant*.
|
| 307 |
+
4. Lawrence Hubert, Phipps Arabie. **Comparing partitions.** *Journal of Classification* 2(1), 193–218,
|
| 308 |
+
December 1985 (Crossref). doi:10.1007/BF01908075, https://link.springer.com/article/10.1007/BF01908075.
|
| 309 |
+
5. David Arthur, Sergei Vassilvitskii. **k-means++: the advantages of careful seeding.** *Proceedings of the
|
| 310 |
+
18th ACM-SIAM Symposium on Discrete Algorithms (SODA '07)*, New Orleans, 7–9 January 2007, SIAM,
|
| 311 |
+
pp. 1027–1035. https://dl.acm.org/doi/10.5555/1283383.1283494.
|
| 312 |
+
|
| 313 |
+
## Measured results
|
| 314 |
+
|
| 315 |
+
All runs were measured on 2026-11-17 on Windows 11 on ARM64, with Python 3.12.10, NumPy 2.4 and one BLAS/OpenMP
|
| 316 |
+
thread (`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1`). Receipts are deterministic: the same
|
| 317 |
+
arguments give the same digest, and every number below was reproduced exactly by a second run later the same
|
| 318 |
+
day. Wall-clock covers the whole call. It is given as the range over those two runs, because the machine was
|
| 319 |
+
shared with other jobs running in parallel.
|
| 320 |
+
|
| 321 |
+
| Run | Seeds | Verdict | Key numbers | Wall-clock |
|
| 322 |
+
|---|---|---|---|---|
|
| 323 |
+
| `run_binding_benchmark(quick=True)` | 0, 1, 2 | `improved` | ARI: candidate 1.000 / shuffled 0.019 / zero −0.011 / reference 1.000. Candidate − shuffled 0.981, CI [0.764, 1.198] | 0.21–0.50 s |
|
| 324 |
+
| `run_experiment(quick=True)` | 0, 1, 2 | `no_detectable_difference` | Held-out accuracy: baseline 0.472 / candidate 0.500 / control 0.500 (chance 0.5). Candidate − baseline +0.028, CI [−0.092, 0.147] | 0.88–1.20 s |
|
| 325 |
+
| `run_binding_benchmark()` | 0, 1, 2 | `improved` | ARI: candidate 1.000 / shuffled 0.002 / zero 0.004. `within_group_R` 0.995, `max_group_cosine` 0.633 | 0.30–0.50 s |
|
| 326 |
+
| `run_binding_benchmark(seeds=range(8))` | 0–7 | `improved` | ARI: candidate 0.957 (one seed 0.653) / shuffled −0.023. CI [0.86, 1.10] | 0.65–1.01 s |
|
| 327 |
+
| `run_binding_benchmark(dim=4)` | 0, 1, 2 | `improved` | ARI: candidate 0.971 (min 0.914) / shuffled 0.050 | 0.25–0.39 s |
|
| 328 |
+
| `run_experiment()` | 0, 1, 2 | `no_detectable_difference` | Held-out accuracy: baseline 0.541 / candidate 0.513 / control 0.530 (chance 0.51). Candidate − baseline −0.028, CI [−0.083, 0.027]; candidate − control −0.017, CI [−0.050, 0.017] | 8.99–15.38 s |
|
| 329 |
+
|
| 330 |
+
On `context_switch` at these sizes, the synchrony features did not help the readout. The quick run is too short
|
| 331 |
+
for any arm to learn the task. The binding benchmark shows the mechanism working on a task with a known
|
| 332 |
+
partition: correlation-coupled oscillators synchronise by latent group, while shuffled and zero coupling stay at
|
| 333 |
+
chance. That is a statement about the dynamics on synthetic data only.
|
| 334 |
+
|
| 335 |
+
**Observer cost.** One `observe()` with 256 units, 64 oscillators, `N = 2` and 2 iterations took 0.33–0.73 ms
|
| 336 |
+
(mean of 300 calls; range over two runs on the shared machine). A `summary()` is about
|
| 337 |
+
0.5 KB of JSON (529 bytes measured), and `export_state()` is about 143 KB of JSON with `history = 256`.
|
docs/frontier/modules/morphogenesis.md
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `morphogenesis`: developmental growth and regeneration of a connectome
|
| 2 |
+
|
| 3 |
+
Module file: `synapse/frontier/morphogenesis.py` · tests: `tests/test_frontier_addons.py` ·
|
| 4 |
+
experiment id: `morphogenesis` · kind: discovery (no engine extension, no live observer) ·
|
| 5 |
+
evidence tier: `synthetic_abstraction`.
|
| 6 |
+
|
| 7 |
+
The module grows a 2-D multi-cell body from a single seed cell (**organizer**) under a compact five-parameter
|
| 8 |
+
developmental program, converts the grown tissue into a valid `synapse.neuroweave.topology.Topology` connectome,
|
| 9 |
+
and studies **regeneration after lesions** with and without a stored **pattern memory** (plus a capacity-matched
|
| 10 |
+
shuffled-memory control). It is inspired by the user's `morpheus`, `prometheus-alpha`, `GenesisEngine` and `MOLT`
|
| 11 |
+
repositories (`kai9987kai`), by Growing Neural Cellular Automata (Mordvintsev, Randazzo, Niklasson & Levin, 2020),
|
| 12 |
+
and by the bioelectric pattern-memory perspective on regeneration (Pezzulo & Levin, 2015).
|
| 13 |
+
|
| 14 |
+
This is a synthetic five-parameter growth-logit abstraction on a small grid, not a trained neural cellular
|
| 15 |
+
automaton or a biophysical tissue model.
|
| 16 |
+
|
| 17 |
+
## What it computes
|
| 18 |
+
|
| 19 |
+
**Developmental program (`DevelopmentalProgram`) and growth (`grow`).** A body lives on an $S \times S$ grid
|
| 20 |
+
($8 \le S \le 48$) starting from a single living cell at the organizer $(o_y, o_x) = (\lfloor S/2 \rfloor, \lfloor S/2 \rfloor)$.
|
| 21 |
+
At each developmental step ($2S$ steps by default):
|
| 22 |
+
|
| 23 |
+
1. For every grid site $(y, x)$, define scaled coordinates relative to the organizer:
|
| 24 |
+
$$
|
| 25 |
+
\Delta x = \frac{x - o_x}{S / 4}, \qquad \Delta y = \frac{y - o_y}{S / 4},
|
| 26 |
+
$$
|
| 27 |
+
and let $n(y, x) \in \{0, \dots, 8\}$ be the number of living 8-neighbours.
|
| 28 |
+
2. Evaluate the five-parameter growth logit $\theta = (\theta_0, \theta_1, \theta_2, \theta_3, \theta_4)$:
|
| 29 |
+
$$
|
| 30 |
+
\ell(y, x) = \theta_0 + \theta_1 \frac{n(y, x)}{8} + \theta_2 (\Delta x)^2 + \theta_3 (\Delta y)^2 + \theta_4 (\Delta x)^4
|
| 31 |
+
+ \mathbf{1}_{\text{memory}}\, \alpha \left(2 M(y, x) - 1\right),
|
| 32 |
+
$$
|
| 33 |
+
where $M(y, x) \in [0, 1]$ is the upsampled pattern-memory setpoint field (when present) and $\alpha \ge 0$ is
|
| 34 |
+
`memory.strength` (default `3.0`).
|
| 35 |
+
3. Draw an asynchronous stochastic update mask $U(y, x) \sim \mathrm{Bernoulli}(p_{\text{update}})$ (`p_update = 0.5`),
|
| 36 |
+
analogous to the per-cell stochastic update mask of Mordvintsev et al. (2020):
|
| 37 |
+
* an empty site with $n(y, x) > 0$, $\ell(y, x) > 0$, and $U(y, x) = 1$ becomes alive;
|
| 38 |
+
* a living non-organizer site with $\ell(y, x) < -\delta_{\text{death}}$ (`death_margin = 2.0`) and $U(y, x) = 1$
|
| 39 |
+
dies (the organizer persists while alive).
|
| 40 |
+
|
| 41 |
+
**Positional differentiation (`_assign_types`).** Living cells differentiate into four functional types by position
|
| 42 |
+
relative to the organizer (French-flag style) and map to NEUROWEAVE region indices:
|
| 43 |
+
|
| 44 |
+
* `sensory` (`visual_sensory`, region `0`): $\Delta x < -1$;
|
| 45 |
+
* `action` (`premotor`, region `8`): $\Delta x > +1$;
|
| 46 |
+
* `memory` (`working_memory`, region `5`): $(\Delta x)^2 + (\Delta y)^2 \le 0.36$ (and $|\Delta x| \le 1$);
|
| 47 |
+
* `association` (`association_a`, region `3`): all remaining living sites.
|
| 48 |
+
|
| 49 |
+
**Connectome conversion (`body_to_topology`).** Living cells become neurons in row-major order ($N$ neurons):
|
| 50 |
+
|
| 51 |
+
* **Dale sign:** $\mathrm{sign}(y, x) = -1$ when $(7y + 13x) \bmod 5 = 0$ (~20 % inhibitory) and $+1$ otherwise,
|
| 52 |
+
pinned to grid coordinates so a regenerated site keeps its sign.
|
| 53 |
+
* **Directed edges** connect distinct cells within Euclidean distance $r$ (`radius = 1.5` by default) when:
|
| 54 |
+
* they have the **same** cell type (local recurrent),
|
| 55 |
+
* the source has strictly **lower** processing rank (`KIND_RANK`: `sensory < association < memory < action`) than
|
| 56 |
+
the target (feedforward), or
|
| 57 |
+
* the source has strictly **higher** rank and is a direct 4-neighbour ($d \le 1$, local feedback).
|
| 58 |
+
* **Delays and weights:** integer delay $1 + \mathbf{1}_{d > 1.5} + \mathbf{1}_{d > 2.5} \in \{1, 2, 3\}$; signed
|
| 59 |
+
weight $\mathrm{sign}_{\text{src}} \cdot \left(w_{\min} + w_{\text{span}} \cdot \mathrm{clip}(1 - (d - 1)/r, 0, 1)\right)$.
|
| 60 |
+
Every generated `Topology` passes `topo.validate()` (no self-loops, no duplicate edges, delays in `[1, 3]`,
|
| 61 |
+
weights matching source signs) and can be passed directly to `topology_metrics(topo)`.
|
| 62 |
+
|
| 63 |
+
**Evolution (`evolve_program`).** A seeded $(1 + \lambda)$ evolution strategy (`generations=30`, `offspring=8`,
|
| 64 |
+
`sigma=0.4`) mutates $\theta$ with isotropic Gaussian perturbations clipped to $[-50, 50]$ to maximise intersection-over-union
|
| 65 |
+
(`iou`) with a target binary mask (`two_lobes`, `ellipse`, or `cross`). Ties keep the parent so fitness is
|
| 66 |
+
monotonically non-decreasing.
|
| 67 |
+
|
| 68 |
+
**Lesion and regeneration (`lesion`, `make_memory`, `shuffled_memory`, `regrow`).**
|
| 69 |
+
|
| 70 |
+
* `lesion(body, box)` clears all cells in `[r0:r1, c0:c1)`.
|
| 71 |
+
* `make_memory(body, block=2, strength=3.0)` stores a coarse setpoint map of shape $(S/b) \times (S/b)$ holding the
|
| 72 |
+
fractional occupancy of each $b \times b$ block (`0.5` is neutral inside $2M - 1$), plus the organizer coordinates
|
| 73 |
+
$(o_y, o_x)$ (`(S // b)**2 + 2` numbers in total).
|
| 74 |
+
* **Regrowth arms (`regrow`):**
|
| 75 |
+
1. **`pattern_memory` (candidate):** restores the organizer coordinates from the stored pattern memory and biases
|
| 76 |
+
the growth logit by $\alpha (2M - 1)$.
|
| 77 |
+
2. **`no_memory` (baseline):** runs the developmental program alone; if the lesion removed the organizer, the new
|
| 78 |
+
organizer is re-derived as the surviving cell nearest the centroid of surviving tissue.
|
| 79 |
+
3. **`shuffled_memory` (capacity-matched control):** stores the exact same number of numbers (`PatternMemory.numbers`)
|
| 80 |
+
and total occupancy mass, with the block occupancies and organizer coordinates randomly permuted by a seeded
|
| 81 |
+
generator (`default_rng(seed + 141421)`).
|
| 82 |
+
|
| 83 |
+
## Benchmark (`run_experiment`, `EXPERIMENTS = {'morphogenesis': run_experiment}`)
|
| 84 |
+
|
| 85 |
+
For each seed (`seeds=(0, 1, 2)` by default):
|
| 86 |
+
|
| 87 |
+
1. Evolve a `DevelopmentalProgram` towards `target_mask(target, size)` (`two_lobes` by default) and grow the intact
|
| 88 |
+
body and its connectome.
|
| 89 |
+
2. Apply `lesions_per_seed` random square lesions covering `lesion_fraction = 0.4` of the body's bounding box
|
| 90 |
+
(centred on randomly chosen living cells; some lesions remove the organizer, others spare it).
|
| 91 |
+
3. Regrow from each damaged state under `pattern_memory`, `no_memory`, and `shuffled_memory`, measuring:
|
| 92 |
+
* **`iou`**: mask IoU with the pre-lesion body (headline metric, higher is better);
|
| 93 |
+
* **`edge_jaccard`**: Jaccard similarity of position-keyed directed connectome edge sets;
|
| 94 |
+
* **`type_agreement`**: fraction of overlapping living cells that recover their pre-lesion cell type;
|
| 95 |
+
* **`metric_similarity`**: $1 - \text{mean relative gap}$ across connectome `density`, `clustering_mean`,
|
| 96 |
+
`modularity`, and `global_efficiency`.
|
| 97 |
+
4. Headline verdict uses `harness.headline_verdict(vs_no_memory, vs_shuffled_memory)`: `improved` requires a paired
|
| 98 |
+
95 % t-interval win over **both** `no_memory` and `shuffled_memory`.
|
| 99 |
+
|
| 100 |
+
| option | default | quick |
|
| 101 |
+
|---|---|---|
|
| 102 |
+
| grid size $S$ / target | 20 / `two_lobes` | 14 / `two_lobes` |
|
| 103 |
+
| ES generations / offspring $\lambda$ / $\sigma$ | 30 / 8 / 0.4 | 10 / 6 / 0.4 |
|
| 104 |
+
| lesions per seed / lesion fraction | 4 / 0.4 | 3 / 0.4 |
|
| 105 |
+
| memory block $b$ / strength $\alpha$ | 2 / 3.0 | 2 / 3.0 |
|
| 106 |
+
| pattern-memory numbers $(S/b)^2 + 2$ | 102 | 51 |
|
| 107 |
+
|
| 108 |
+
## Public API
|
| 109 |
+
|
| 110 |
+
```python
|
| 111 |
+
MODULE_ID = 'morphogenesis'
|
| 112 |
+
CELL_TYPES = ('sensory', 'association', 'memory', 'action')
|
| 113 |
+
TARGETS = ('two_lobes', 'ellipse', 'cross')
|
| 114 |
+
EXPERIMENTS = {'morphogenesis': run_experiment}
|
| 115 |
+
|
| 116 |
+
DevelopmentalProgram(theta=(2.0, 1.0, -1.2, -1.2, 0.0), p_update=0.5, death_margin=2.0)
|
| 117 |
+
PatternMemory(setpoint, block, organizer, strength=3.0)
|
| 118 |
+
.field(size) -> np.ndarray (size, size)
|
| 119 |
+
.numbers -> int
|
| 120 |
+
Body(alive, cell_type, organizer)
|
| 121 |
+
.size -> int .cells -> int .copy() -> Body
|
| 122 |
+
target_mask(name, size) -> np.ndarray
|
| 123 |
+
grow(program, size, *, seed=0, steps=None) -> Body
|
| 124 |
+
lesion(body, box) -> Body
|
| 125 |
+
make_memory(body, *, block=2, strength=3.0) -> PatternMemory
|
| 126 |
+
shuffled_memory(memory, *, seed=0) -> PatternMemory
|
| 127 |
+
regrow(program, damaged, *, memory=None, seed=0, steps=None) -> Body
|
| 128 |
+
body_to_topology(body, *, radius=1.5, name='morphogenesis', seed=0) -> Topology
|
| 129 |
+
iou(a, b) -> float
|
| 130 |
+
edge_jaccard(body_a, body_b, *, radius=1.5) -> float
|
| 131 |
+
evolve_program(target, *, seed=0, generations=30, offspring=8, sigma=0.4,
|
| 132 |
+
growth_seed=0, steps=None) -> dict
|
| 133 |
+
run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict
|
| 134 |
+
```
|
| 135 |
+
|
| 136 |
+
## Connection to Sonapse
|
| 137 |
+
|
| 138 |
+
`body_to_topology` returns a validated `synapse.neuroweave.topology.Topology` with ten-region indexing and
|
| 139 |
+
Dale-signed weights, compatible with `topology_metrics` and with `NeuroWeaveEngine`. The module is default-off and
|
| 140 |
+
does not alter any existing `build_topology` generator.
|
| 141 |
+
|
| 142 |
+
## Not implemented
|
| 143 |
+
|
| 144 |
+
* **Differentiable multi-channel neural cellular automata** trained by backpropagation through time on RGBA images
|
| 145 |
+
(Mordvintsev et al., 2020). This module evolves a 5-parameter radial/neighbour growth logit with a $(1+\lambda)$-ES.
|
| 146 |
+
* **Explicit voltage-gated ion channels or gap-junction diffusion equations** for bioelectric pattern memory
|
| 147 |
+
(Pezzulo & Levin, 2015); the pattern memory is represented directly as a coarse spatial setpoint field plus the
|
| 148 |
+
organizer coordinates.
|
| 149 |
+
* **Activity-dependent synaptic plasticity during development.** Connectome weights come from geometry and cell-type
|
| 150 |
+
ranks after growth finishes.
|
| 151 |
+
|
| 152 |
+
## Verified references
|
| 153 |
+
|
| 154 |
+
* Alexander Mordvintsev, Ettore Randazzo, Eyvind Niklasson and Michael Levin. **Growing Neural Cellular Automata.**
|
| 155 |
+
*Distill* (published 11 February 2020). DOI [10.23915/distill.00023](https://doi.org/10.23915/distill.00023);
|
| 156 |
+
URL <https://distill.pub/2020/growing-ca/>.
|
| 157 |
+
* **Checked on 2026-11-19:** single-seed growth on a 2-D grid, local neighbourhood perception, asynchronous
|
| 158 |
+
per-cell stochastic update mask, and regeneration experiments after rectangular lesions.
|
| 159 |
+
* Giovanni Pezzulo and Michael Levin. **Re-membering the body: applications of computational neuroscience to the
|
| 160 |
+
top-down control of regeneration of limbs and other complex organs.** *Integrative Biology* 7(12), 1487–1517
|
| 161 |
+
(December 2015). DOI [10.1039/c5ib00221d](https://doi.org/10.1039/c5ib00221d); PMC4700597 (PMID 26571072).
|
| 162 |
+
* **Checked on 2026-11-19:** conceptualises regeneration as error-minimising remodelling guided by an encoded
|
| 163 |
+
target-morphology "pattern memory" distinct from local growth rules alone.
|
| 164 |
+
* Portfolio provenance: `kai9987kai/morpheus`, `kai9987kai/prometheus-alpha`, `kai9987kai/GenesisEngine`, and
|
| 165 |
+
`kai9987kai/MOLT`, inspected in the local read-only portfolio clones on 2026-11-19.
|
| 166 |
+
|
| 167 |
+
## Measured results
|
| 168 |
+
|
| 169 |
+
Measured on **2026-11-19** with `seeds=(0, 1, 2)` on one CPU thread (`OPENBLAS_NUM_THREADS=1`).
|
| 170 |
+
|
| 171 |
+
| mode | digest (prefix) | wall-clock | target IoU (initial $\to$ evolved) | `pattern_memory` IoU (edge Jaccard / type agree / metric sim) | `no_memory` IoU (edge Jaccard / type agree / metric sim) | `shuffled_memory` IoU (edge Jaccard / type agree / metric sim) | `pattern - no_memory` IoU (95 % CI) | `pattern - shuffled` IoU (95 % CI) | headline verdict (`verdict_basis`) |
|
| 172 |
+
|---|---|---|---|---|---|---|---|---|---|
|
| 173 |
+
| `quick=True` ($14\times 14$, 10 gen, 3 lesions/seed, 51 memory numbers) | `67f7c190ce564e66` | 3.39 s | $0.6351 \to 0.7437$ | 0.9593 (0.9580 / 1.0000 / 0.9770) | 0.9020 (0.8641 / 0.8526 / 0.9878) | 0.3294 (0.2393 / 0.4084 / 0.8252) | +0.0573 (`[+0.0347, +0.0799]`) | +0.6299 (`[+0.4159, +0.8439]`) | `improved` (`candidate_vs_baseline_and_control`) |
|
| 174 |
+
| `quick=False` ($20\times 20$, 30 gen, 4 lesions/seed, 102 memory numbers) | `18af03324af0663f` | 13.37 s | $0.6062 \to 0.8229$ | 0.9739 (0.9749 / 1.0000 / 0.9835) | 0.9358 (0.9131 / 0.9120 / 0.9873) | 0.1978 (0.1286 / 0.2724 / 0.5317) | +0.0381 (`[-0.2242, +0.3004]`) | +0.7761 (`[+0.3605, +1.1917]`) | `no_detectable_difference` (`candidate_vs_baseline`) |
|
| 175 |
+
|
| 176 |
+
In both modes `pattern_memory` restores 100 % cell-type agreement on overlapping tissue and beats the
|
| 177 |
+
capacity-matched `shuffled_memory` control with a wide margin (`improved`). At `quick=False` ($20 \times 20$),
|
| 178 |
+
several random lesions spare the organizer cell, allowing the developmental rule alone (`no_memory`) to regrow
|
| 179 |
+
most of the symmetrical shape (mean IoU 0.9358 vs 0.9739 with pattern memory), so across 3 seeds the paired 95 % t
|
| 180 |
+
interval against `no_memory` spans zero (`[-0.2242, +0.3004]`, `no_detectable_difference`). When a lesion removes
|
| 181 |
+
the organizer, `no_memory` shifts the organizer to the centroid of surviving tissue and systematically misplaces
|
| 182 |
+
cell-type poles (`test_regrowth_with_pattern_memory_recovers_better_after_losing_the_organizer`).
|
docs/frontier/modules/muon_optimizer.md
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `muon_optimizer`: orthogonalised-momentum optimiser (Muon)
|
| 2 |
+
|
| 3 |
+
Module file: `synapse/frontier/muon.py` · tests: `tests/test_frontier_optim.py` ·
|
| 4 |
+
experiment id: `muon_optimizer` · kind: `tool` (an optimiser plus a benchmark; no engine extension, no live
|
| 5 |
+
observer) · evidence tier: `synthetic_abstraction`.
|
| 6 |
+
|
| 7 |
+
The module implements a **Muon**-style optimiser (MomentUm Orthogonalized by Newton–Schulz) for matrix
|
| 8 |
+
parameters, with an internal **AdamW** for everything else, in one `torch.optim.Optimizer`
|
| 9 |
+
(`MuonWithAuxAdam`). It is *inspired by* Jordan et al. (2024), whose blog post and reference code define the
|
| 10 |
+
algorithm, and by Liu et al. (2025), whose update scale and decoupled weight decay it uses. It also provides
|
| 11 |
+
`make_graft_optimizer`, the opt-in optimiser for Sonapse's live neural graft
|
| 12 |
+
(`FrontierSpecV1(graft_optimizer='muon')`), and a small benchmark of Muon against Adam on the graft's own
|
| 13 |
+
architecture. Nothing here reproduces a published training result, and no speed or scale claim is made.
|
| 14 |
+
|
| 15 |
+
## What it computes
|
| 16 |
+
|
| 17 |
+
For a 2-D parameter `W` of shape `A × B` with gradient `G_t`, momentum `mu`, learning rate `lr` and weight decay
|
| 18 |
+
`wd`, one step is:
|
| 19 |
+
|
| 20 |
+
```
|
| 21 |
+
M_t = mu * M_{t-1} + (1 - mu) * G_t momentum (EMA form of Jordan's code: lerp)
|
| 22 |
+
U_t = (1 - mu) * G_t + mu * M_t Nesterov input (U_t = M_t with nesterov=False)
|
| 23 |
+
X_0 = U_t / (||U_t||_F + 1e-7) Frobenius normalisation: singular values in (0, 1]
|
| 24 |
+
X_{k+1} = a X_k + b (X_k X_k^T) X_k + c (X_k X_k^T)^2 X_k, (a, b, c) = (3.4445, -4.7750, 2.0315), 5 steps
|
| 25 |
+
W_t = W_{t-1} - lr * (0.2 * sqrt(max(A, B)) * X_5 + wd * W_{t-1}) (Liu et al., Eq. 4)
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
* **Orientation.** The iteration runs on the wide orientation of the matrix (transposed when `A > B`), as in
|
| 29 |
+
the reference code, so the Gram matrix is the smaller one.
|
| 30 |
+
* **What Newton–Schulz returns.** It keeps the singular vectors of `U_t` and maps every singular value `s` of
|
| 31 |
+
`X_0` through `p^5`, with `p(x) = a x + b x^3 + c x^5`. It is not the exact polar factor `U V^T`. Iterating the
|
| 32 |
+
scalar map on a dense grid (2,000,001 points, recomputed on 2026-11-20) gives outputs in
|
| 33 |
+
`[0.6818, 1.1344]` for every start `s >= 0.01` and in `(0, 1.2024]` for every `s` in `(0, 1]`; the tests check
|
| 34 |
+
this band on random matrices and the exact scalar map on a matrix with a known SVD.
|
| 35 |
+
* **Momentum form.** Liu et al. write `M_t = mu M_{t-1} + G_t` with the Nesterov input `mu M_t + G_t`. The EMA
|
| 36 |
+
form above is the same sequence multiplied by `1 - mu`, and the Frobenius normalisation removes that factor
|
| 37 |
+
(up to the `1e-7`), so both give the same update.
|
| 38 |
+
* **Update scale.** `update_scale * sqrt(max(A, B))` with `update_scale = 0.2` (Liu et al., Eq. 4). It lets the
|
| 39 |
+
Muon part and the AdamW part share one learning rate. Jordan's reference code scales by
|
| 40 |
+
`max(1, A / B) ** 0.5` instead and uses separate learning rates for the two parts; that variant is not
|
| 41 |
+
implemented.
|
| 42 |
+
* **Other shapes.** A parameter with more than two dimensions that is routed to Muon is flattened to
|
| 43 |
+
`(shape[0], -1)`, as the reference code does for convolution filters, and `max(A, B)` is taken on the flattened
|
| 44 |
+
shape.
|
| 45 |
+
* **AdamW part.** Every parameter not routed to Muon (biases, norm gains, embeddings, output heads, other
|
| 46 |
+
shapes) is updated with the arithmetic of `torch.optim.AdamW`'s single-tensor path, in the same order
|
| 47 |
+
(decoupled decay, bias-corrected moments; defaults `betas = (0.9, 0.999)`, `eps = 1e-8`). A test checks that
|
| 48 |
+
vector parameters follow `torch.optim.AdamW` bit for bit.
|
| 49 |
+
* **Overflow.** When the squares of finite entries overflow the Frobenius norm, the matrix is first divided by
|
| 50 |
+
its largest absolute entry (the reference code would return zeros there). The update is invariant to the
|
| 51 |
+
gradient's scale, which a test checks up to a gradient scale of `1e25`.
|
| 52 |
+
|
| 53 |
+
**Atomic steps.** `step()` computes the whole update first. A non-finite gradient, or an update that would make
|
| 54 |
+
a parameter or a state tensor non-finite, raises `ValueError` and changes no parameter and no state, the Muon
|
| 55 |
+
part included. Sparse gradients are refused. `load_state_dict` validates the group layout, the routing of every
|
| 56 |
+
parameter (`use_muon`), the hyper-parameters, the state keys, shapes, dtypes and finiteness, and
|
| 57 |
+
`exp_avg_sq >= 0`, before it changes anything, and then loads a private deep copy.
|
| 58 |
+
|
| 59 |
+
## Parameter routing
|
| 60 |
+
|
| 61 |
+
* `MuonWithAuxAdam(params, ...)` accepts an `nn.Module` (routed by `muon_param_groups`), an iterable of tensors
|
| 62 |
+
(2-D tensors go to Muon, the rest to AdamW) or group dicts. A group may set `use_muon` explicitly (`True` needs
|
| 63 |
+
at least 2 dimensions) and override any hyper-parameter. Groups added later with `add_param_group` are
|
| 64 |
+
validated the same way. Sets are refused because their order is not deterministic.
|
| 65 |
+
* `muon_param_groups(module, *, aux_modules=(), **hyper)` puts every 2-D parameter on Muon except
|
| 66 |
+
`nn.Embedding` / `nn.EmbeddingBag` weights and parameters owned by `aux_modules`; everything else goes to
|
| 67 |
+
AdamW. Jordan et al. recommend AdamW for embeddings, classifier heads, input layers and scalar or vector
|
| 68 |
+
parameters; Liu et al. use AdamW for the norm, LM-head and embedding parameters.
|
| 69 |
+
* `make_graft_optimizer(params_or_module, kind='adam', lr=3e-4, *, heads_on_adam=True, inputs_on_adam=None,
|
| 70 |
+
**muon_options)`:
|
| 71 |
+
* `kind='adam'` returns exactly `torch.optim.Adam(params, lr=lr)`, the graft's existing optimiser (a test
|
| 72 |
+
checks identical trajectories and state); any other option is refused.
|
| 73 |
+
* `kind='muon'` on a module with the graft's structure (`actor_encoder`, `value` and `dynamics`
|
| 74 |
+
`nn.Sequential` paths plus `actor_head`) keeps the three output layers (`graft_output_layers`: the actor head
|
| 75 |
+
and the last linear layer of the value and dynamics paths) and the three input layers
|
| 76 |
+
(`graft_input_layers`: the first linear layer of each path) on AdamW, which leaves Muon the three
|
| 77 |
+
hidden-to-hidden matrices. This follows Jordan et al., who write that input and output parameters should be
|
| 78 |
+
optimised with AdamW even though they are 2-D. `inputs_on_adam=None` (the default) means `True` for a
|
| 79 |
+
graft-structured module and `False` for any other module or a parameter iterable, where input layers cannot
|
| 80 |
+
be identified; `inputs_on_adam=False` puts the graft's input layers on Muon as well (the routing ablation
|
| 81 |
+
below); `inputs_on_adam=True` on a non-graft module is refused.
|
| 82 |
+
|
| 83 |
+
| routing on the graft network | matrices on Muon | numbers on Muon / AdamW (hidden 32) | (hidden 64) |
|
| 84 |
+
|---|---|---|---|
|
| 85 |
+
| `kind='muon'` (default, the live opt-in) | the 3 hidden-to-hidden matrices | 3,072 / 19,221 | 12,288 / 38,421 |
|
| 86 |
+
| `kind='muon', inputs_on_adam=False` (ablation) | the 3 input + 3 hidden matrices | 21,344 / 949 | 48,832 / 1,877 |
|
| 87 |
+
|
| 88 |
+
*Review fix (2026-11-20).* Until this review the live opt-in used the second row (input layers on Muon), which
|
| 89 |
+
contradicts both sources' guidance and measured worse than Adam in this module's own benchmark (see *Measured
|
| 90 |
+
results*); the default is now the first row.
|
| 91 |
+
|
| 92 |
+
## Benchmark (`run_experiment`)
|
| 93 |
+
|
| 94 |
+
* **Architecture.** `synapse.neural_graft._ResidualNetwork` (the live graft's network: policy, value and
|
| 95 |
+
dynamics heads), built inside `torch.random.fork_rng` and then re-initialised from a private
|
| 96 |
+
`torch.Generator`, so the global torch RNG is left as it was.
|
| 97 |
+
* **Task.** Teacher–student regression. Inputs are shaped like the graft's: a 256-wide state (155 observation
|
| 98 |
+
values and 64 feature values from `N(0, 1)`, 5 baseline-action and 32 prior values from `U(-1, 1)`, clipped to
|
| 99 |
+
`[-5, 5]`), the 155 observation values for the value head and observation plus a 5-wide action for the
|
| 100 |
+
dynamics head. A fixed, never-trained teacher of the same architecture, with every linear layer (the actor
|
| 101 |
+
head included) at `teacher_gain = 2` times PyTorch's default initialisation range, gives the targets, which
|
| 102 |
+
are standardised per output with the training split's mean and standard deviation.
|
| 103 |
+
* **Student and training.** Every arm trains the same student initialisation (PyTorch's default
|
| 104 |
+
`nn.Linear` distribution and the architecture's zero actor head) on the same minibatch sequence for the same
|
| 105 |
+
number of steps, with the graft's loss form (the sum of the three heads' MSE) and gradient-norm clipping at 1.
|
| 106 |
+
* **Arms.** `adam`: `torch.optim.Adam` (with `weight_decay > 0`, `torch.optim.AdamW` with the same decay as
|
| 107 |
+
the Muon arms); `muon`: `make_graft_optimizer(kind='muon')`, the routing the live opt-in uses (input and
|
| 108 |
+
output layers on AdamW); `muon_with_inputs` (the routing ablation, `routing_ablation=True`):
|
| 109 |
+
`inputs_on_adam=False`, the input layers on Muon too. Both Muon arms use the same `heads_on_adam`.
|
| 110 |
+
* **Learning rate.** For every arm separately, the learning rate is chosen from `lr_grid` by the lowest mean
|
| 111 |
+
validation MSE over seeds. The receipt flags a choice at the edge of the grid
|
| 112 |
+
(`selected_at_grid_edge`) and lists every run, so a grid that is too narrow is visible.
|
| 113 |
+
* **Verdict.** `harness.compare` (paired 95 % t interval over seeds, lower is better) of held-out test MSE,
|
| 114 |
+
`muon` minus `adam`, at the selected learning rates. `muon_with_inputs` minus `adam` is reported as a
|
| 115 |
+
secondary comparison and does not set the verdict. If an arm diverges at its selected learning rate, the
|
| 116 |
+
basis becomes `training_diverged_at_selected_lr` (paired statistics drop non-finite pairs, so a divergence is
|
| 117 |
+
never hidden).
|
| 118 |
+
* **Receipt.** `config` (every option), `parameter_routing` (parameter names, counts and shapes per arm),
|
| 119 |
+
`arms` (selected learning rate, the grid of mean validation MSE with diverged seeds, per-seed results with
|
| 120 |
+
per-head test MSE and optimiser state size, every run), `comparisons`, `verdict`, `verdict_basis`, `budget`
|
| 121 |
+
(parameters, steps and runs, Muon/AdamW split and optimiser state numbers per arm), `estimated_cost`
|
| 122 |
+
(analytic forward–backward and Newton–Schulz FLOPs per step) kept apart from `measured_wallclock_s`, the
|
| 123 |
+
teacher's raw output scale and `notes`.
|
| 124 |
+
|
| 125 |
+
| setting | quick | default |
|
| 126 |
+
|---|---|---|
|
| 127 |
+
| hidden width, parameters | 32, 22,293 | 64, 50,709 |
|
| 128 |
+
| train / val / test examples | 512 / 256 / 256 | 2048 / 512 / 1024 |
|
| 129 |
+
| steps × batch | 40 × 128 | 300 × 128 |
|
| 130 |
+
| `lr_grid` | 1e-3, 1e-2 | 3e-4, 1e-3, 3e-3, 1e-2, 3e-2 |
|
| 131 |
+
| momentum, Nesterov, Newton–Schulz steps, weight decay | 0.95, yes, 5, 0 | same |
|
| 132 |
+
|
| 133 |
+
## Public API
|
| 134 |
+
|
| 135 |
+
```python
|
| 136 |
+
MODULE_ID = 'muon_optimizer'
|
| 137 |
+
NS_COEFFICIENTS = (3.4445, -4.7750, 2.0315)
|
| 138 |
+
ARMS = ('adam', 'muon', 'muon_with_inputs')
|
| 139 |
+
EXPERIMENTS = {'muon_optimizer': run_experiment}
|
| 140 |
+
DEFAULT_CONFIG, QUICK_CONFIG # benchmark options (overridable by keyword)
|
| 141 |
+
|
| 142 |
+
zeropower_via_newtonschulz5(matrix, steps=5, eps=1e-7) -> torch.Tensor
|
| 143 |
+
MuonWithAuxAdam(params, lr=1e-3, *, momentum=0.95, nesterov=True, ns_steps=5, weight_decay=0.0,
|
| 144 |
+
betas=(0.9, 0.999), eps=1e-8, update_scale=0.2)
|
| 145 |
+
.step(closure=None) .add_param_group(group) .load_state_dict(state) .state_dict()
|
| 146 |
+
.muon_parameters() .adam_parameters() .state_numbers()
|
| 147 |
+
muon_param_groups(module, *, aux_modules=(), **hyper) -> list[dict]
|
| 148 |
+
graft_output_layers(network) -> tuple[nn.Module, ...]
|
| 149 |
+
graft_input_layers(network) -> tuple[nn.Module, ...]
|
| 150 |
+
make_graft_optimizer(params_or_module, kind='adam', lr=3e-4, *, heads_on_adam=True, inputs_on_adam=None,
|
| 151 |
+
**muon_options) -> torch.optim.Optimizer
|
| 152 |
+
run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed receipt
|
| 153 |
+
```
|
| 154 |
+
|
| 155 |
+
Every constructor and function validates its input and raises `ValueError` on bad input. The benchmark draws
|
| 156 |
+
data from `numpy.random.default_rng(seed + offset)` and weights from private `torch.Generator` objects, runs
|
| 157 |
+
PyTorch on one thread and restores the caller's thread count; a test checks that the global torch RNG state and
|
| 158 |
+
the thread count are unchanged after a run.
|
| 159 |
+
|
| 160 |
+
## Connection to Sonapse
|
| 161 |
+
|
| 162 |
+
* `FrontierSpecV1.graft_optimizer` defaults to `'adam'`: the live neural graft keeps `torch.optim.Adam`, and its
|
| 163 |
+
checkpoint settings stay free of an `optimizer_kind` entry, so nothing changes by default.
|
| 164 |
+
* With `graft_optimizer='muon'`, `NeuralResidualGraft` builds its optimiser with
|
| 165 |
+
`make_graft_optimizer(network, kind='muon', lr=learning_rate)`, that is, the `muon` routing above (input
|
| 166 |
+
layers, output heads and vectors on AdamW; the hidden-to-hidden matrices on Muon). Its checkpoints record the
|
| 167 |
+
optimiser kind and refuse to load into an Adam graft. A Muon-graft checkpoint written before the 2026-11-20
|
| 168 |
+
routing fix stores the old routing and is refused by `load_state_dict`'s routing check.
|
| 169 |
+
* The benchmark measures that routing (`muon` arm) and the alternative with the input layers on Muon; see
|
| 170 |
+
*Measured results* before choosing the opt-in.
|
| 171 |
+
|
| 172 |
+
## Not implemented, and differences from the sources
|
| 173 |
+
|
| 174 |
+
* **Precision and hardware.** The reference code runs Newton–Schulz in bfloat16 on GPUs. Here it runs in float32
|
| 175 |
+
(float64 for float64 inputs) on the CPU. No speed, memory or scale benefit is claimed.
|
| 176 |
+
* **Scale and learning rates.** Liu et al.'s `0.2 sqrt(max(A, B))` scale with one shared learning rate is used.
|
| 177 |
+
Jordan's `max(1, A / B) ** 0.5` scale with separate learning rates (Muon 0.02, Adam 3e-4 in the reference
|
| 178 |
+
`MuonWithAuxAdam`, whose Adam part uses `betas = (0.9, 0.95)` and `eps = 1e-10`) is not.
|
| 179 |
+
* **Not attempted.** Distributed or sharded orthogonalisation, the language-model and speed-run benchmarks of
|
| 180 |
+
both sources, other Newton–Schulz coefficient schedules, and learning-rate schedules (the benchmark uses a
|
| 181 |
+
constant learning rate).
|
| 182 |
+
* **Benchmark scope.** One synthetic teacher–student task on one small architecture, with a short training
|
| 183 |
+
budget. It does not show how Muon behaves on the live graft, whose targets come from executed transitions.
|
| 184 |
+
|
| 185 |
+
## Measured results
|
| 186 |
+
|
| 187 |
+
Measured on **2026-11-20**, Windows 11 on ARM64, Python 3.12.10, torch 2.11 CPU, NumPy 2.4,
|
| 188 |
+
`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1` (the benchmark also runs torch on one thread). The machine
|
| 189 |
+
was shared with other jobs, so wall-clock is indicative only. Seeds 0, 1, 2. Test MSE is the mean over the three
|
| 190 |
+
heads of the MSE on standardised targets (a constant prediction scores about 1); lower is better.
|
| 191 |
+
|
| 192 |
+
**Quick** (`run_experiment(quick=True)`; digest `fe48c4d94d312b14`, identical in two calls; 14.3 s):
|
| 193 |
+
|
| 194 |
+
| Arm | Selected lr | Held-out test MSE (per seed) | Mean |
|
| 195 |
+
|---|---|---|---:|
|
| 196 |
+
| `adam` | 1e-2 (grid edge) | 0.3895, 0.4110, 0.4056 | 0.4020 |
|
| 197 |
+
| `muon` (input and output layers on AdamW) | 1e-2 (grid edge) | 0.3880, 0.3999, 0.4081 | 0.3987 |
|
| 198 |
+
| `muon_with_inputs` (input layers on Muon) | 1e-2 (grid edge) | 0.5432, 0.5858, 0.5516 | 0.5602 |
|
| 199 |
+
|
| 200 |
+
* `muon − adam`: −0.0034, 95 % CI [−0.0207, +0.0140] → **`no_detectable_difference`** (verdict).
|
| 201 |
+
`muon_with_inputs − adam`: +0.1582, CI [+0.1212, +0.1952] (`worse`).
|
| 202 |
+
* The quick grid has two values and every arm picked its upper edge; quick mode is a pipeline check, not
|
| 203 |
+
evidence.
|
| 204 |
+
|
| 205 |
+
**Default** (`run_experiment()`; digest `c23a6ae52d6e23c7`; 207.6 s, of which 49.5 / 70.8 / 82.9 s were the 15
|
| 206 |
+
`adam` / `muon` / `muon_with_inputs` runs):
|
| 207 |
+
|
| 208 |
+
| Arm | Selected lr | Held-out test MSE (per seed) | Mean | Per head: policy / value / dynamics | Optimiser state numbers |
|
| 209 |
+
|---|---|---|---:|---|---:|
|
| 210 |
+
| `adam` | 1e-3 | 0.2668, 0.2761, 0.2797 | 0.2742 | 0.174 / 0.163 / 0.485 | 101,418 |
|
| 211 |
+
| `muon` | 1e-3 | 0.2628, 0.2707, 0.2726 | 0.2687 | 0.164 / 0.157 / 0.486 | 89,130 |
|
| 212 |
+
| `muon_with_inputs` | 3e-3 | 0.3351, 0.3420, 0.3507 | 0.3426 | 0.212 / 0.234 / 0.582 | 52,586 |
|
| 213 |
+
|
| 214 |
+
* `muon − adam`: −0.0055, 95 % CI [−0.0094, −0.0016] → **`improved`** (verdict): about 2 % lower test MSE,
|
| 215 |
+
from the policy and value heads; the dynamics head is unchanged. No arm selected a learning rate at the edge
|
| 216 |
+
of the five-value grid, and no run diverged.
|
| 217 |
+
* `muon_with_inputs − adam`: +0.0684, CI [+0.0622, +0.0746] (`worse`).
|
| 218 |
+
* Analytic cost per step (`estimated_cost`, not measured): forward–backward 38.5 MFLOP; Newton–Schulz
|
| 219 |
+
23.6 MFLOP for `muon` and 78.2 MFLOP for `muon_with_inputs`.
|
| 220 |
+
|
| 221 |
+
**How to read this.** The `muon` routing was changed during the 2026-11-20 review, after both routings had
|
| 222 |
+
been measured: before the fix the candidate arm put the input layers on Muon and the input-layers-on-AdamW
|
| 223 |
+
routing was the ablation (then called `muon_hidden_only`). The receipts from before the fix (quick digest
|
| 224 |
+
`2aa131161a125fc2`, default `bab33558fdf5241c`, both run on 2026-11-20) contain the same per-seed numbers with
|
| 225 |
+
the two Muon arms swapped and gave the verdict `worse`. The change follows the routing both sources prescribe
|
| 226 |
+
(input and output layers on AdamW), not the result, but the order of events is stated here so the verdict can
|
| 227 |
+
be weighed accordingly. The effect is small, on one synthetic teacher–student task with three seeds and a
|
| 228 |
+
short budget; it is no evidence about the live graft. What the benchmark does show clearly, at both sizes, is
|
| 229 |
+
that putting the graft's input layers on Muon hurts.
|
| 230 |
+
|
| 231 |
+
Unit tests with known answers (`tests/test_frontier_optim.py`, Muon part): the Newton–Schulz output on a
|
| 232 |
+
matrix with a known SVD equals the scalar map `p^5` applied to its normalised singular values; the singular
|
| 233 |
+
value band on random matrices; scale invariance up to a gradient scale of `1e25`; one hand-computed Muon step
|
| 234 |
+
(momentum, Nesterov input, scale `0.2 sqrt(max(A, B))`, decoupled decay); the AdamW part equal to
|
| 235 |
+
`torch.optim.AdamW` bit for bit; `make_graft_optimizer('adam')` equal to `torch.optim.Adam`; the graft
|
| 236 |
+
routing (default and ablation); atomic refusal of non-finite steps; `load_state_dict` validation before any
|
| 237 |
+
change; and a sealed, deterministic receipt that leaves the global torch RNG and thread count unchanged.
|
| 238 |
+
|
| 239 |
+
## Verified references
|
| 240 |
+
|
| 241 |
+
* Keller Jordan, Yuchen Jin, Vlado Boza, Jiacheng You, Franz Cesista, Laker Newhouse, Jeremy Bernstein.
|
| 242 |
+
**Muon: An optimizer for hidden layers in neural networks.** Blog post, 8 December 2024.
|
| 243 |
+
<https://kellerjordan.github.io/posts/muon/>. Checked on 2026-11-20: the coefficients
|
| 244 |
+
`(3.4445, -4.7750, 2.0315)`, the replacement of `G` by `G / ||G||_F` before the iteration, Nesterov-style
|
| 245 |
+
momentum as the default, and AdamW for scalar and vector parameters, input and output layers, embeddings and
|
| 246 |
+
classifier heads.
|
| 247 |
+
* Reference code: <https://github.com/KellerJordan/Muon> (`muon.py`), read on 2026-11-20:
|
| 248 |
+
`zeropower_via_newtonschulz5` (bfloat16, transpose when rows > cols, Frobenius normalisation with `1e-7`),
|
| 249 |
+
`muon_update` (`momentum.lerp_(grad, 1 - beta)`, Nesterov `grad.lerp_(momentum, beta)`, the
|
| 250 |
+
`max(1, rows / cols) ** 0.5` scale, defaults `beta = 0.95`, `ns_steps = 5`), decoupled weight decay
|
| 251 |
+
`p.mul_(1 - lr * wd)`, and the `MuonWithAuxAdam` defaults quoted above.
|
| 252 |
+
* Jingyuan Liu, Jianlin Su, Xingcheng Yao, Zhejun Jiang, Guokun Lai, Yulun Du, Yidao Qin, Weixin Xu, Enzhe Lu,
|
| 253 |
+
Junjie Yan, Yanru Chen, Huabin Zheng, Yibo Liu, Shaowei Liu, Bohong Yin, Weiran He, Han Zhu, Yuzhi Wang,
|
| 254 |
+
Jianzhou Wang, Mengnan Dong, Zheng Zhang, Yongsheng Kang, Hao Zhang, Xinran Xu, Yutao Zhang, Yuxin Wu,
|
| 255 |
+
Xinyu Zhou, Zhilin Yang. **Muon is Scalable for LLM Training.** Technical report, arXiv:2502.16982
|
| 256 |
+
(v1, 24 February 2025). <https://arxiv.org/abs/2502.16982>. Checked on 2026-11-20 against the arXiv listing
|
| 257 |
+
and the HTML text: Eq. 1 (Muon with `M_t = mu M_{t-1} + grad`), Eq. 3 (weight decay), Eq. 4 (the
|
| 258 |
+
`0.2 · O_t · sqrt(max(A, B))` scale), momentum 0.95 "same as Jordan et al.", the Nesterov-style input, and
|
| 259 |
+
AdamW for the non-matrix parameters (RMSNorm, LM head, embeddings).
|
docs/frontier/modules/nir_export.md
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `nir_export`: NIR-style interchange export of NEUROWEAVE brains
|
| 2 |
+
|
| 3 |
+
Module file: `synapse/frontier/nir_export.py` · tests: `tests/test_frontier_biophysics.py` ·
|
| 4 |
+
experiment id: `nir_export` (`kind: 'validation'`) · no observer, no engine extension ·
|
| 5 |
+
evidence tier: `synthetic_abstraction`.
|
| 6 |
+
|
| 7 |
+
The module exports a NEUROWEAVE brain as a graph in the style of the **Neuromorphic Intermediate
|
| 8 |
+
Representation** (NIR, Pedersen et al., *Nature Communications* 2024). It uses NIR's node types and the
|
| 9 |
+
parameter names of the `nir` Python package. It is *inspired by* NIR and follows its primitives. It does not
|
| 10 |
+
claim equivalence with any NIR backend or hardware, and it has not been run on one.
|
| 11 |
+
|
| 12 |
+
The export is a **lossy approximation** of the abstract NEUROWEAVE cell. Every feature that cannot be
|
| 13 |
+
represented is listed in the graph metadata and in the receipt.
|
| 14 |
+
|
| 15 |
+
## Graph format
|
| 16 |
+
|
| 17 |
+
```
|
| 18 |
+
{'nodes': {name: {'type': <NIR primitive>, 'params': {field: value}}}, # values are nested float lists
|
| 19 |
+
'edges': [[src, dst], ...], # incoming edges are summed
|
| 20 |
+
'metadata': {...}} # optional; ignored by equality
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
Handled node types and fields (same names as the `nir` dataclasses): `Input(shape)`, `Output(shape)`,
|
| 24 |
+
`Affine(weight, bias)`, `Linear(weight)`, `Scale(scale)`, `Delay(delay)`, `I(r)`,
|
| 25 |
+
`IF(r, v_threshold, v_reset)`, `LI(tau, r, v_leak)`, `LIF(tau, r, v_leak, v_threshold, v_reset)`,
|
| 26 |
+
`CubaLI(tau_syn, tau_mem, r, v_leak, w_in)` and
|
| 27 |
+
`CubaLIF(tau_syn, tau_mem, r, v_leak, v_threshold, v_reset, w_in)`. Weights are `(out, in)` matrices.
|
| 28 |
+
|
| 29 |
+
## What it computes
|
| 30 |
+
|
| 31 |
+
**Layout of `brain_to_nir(source, *, input_dim=None, step_ms=1.0)`.** `source` can be a `NeuroWeaveBrain`, a
|
| 32 |
+
`NeuroWeaveEngine`, or either one's `export_state()` dict. The exporter works on a validated private copy and
|
| 33 |
+
never mutates the source (tested).
|
| 34 |
+
|
| 35 |
+
```
|
| 36 |
+
input (Input, d) -> input_projection (Linear, n x d) -> cells (CubaLIF or LIF, n) -> output (Output, n)
|
| 37 |
+
for each synaptic delay class k (steps):
|
| 38 |
+
cells -> delay_k (Delay, k * step_ms) -> recurrent_k (Linear, n x n) -> cells
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
* `input_projection` is the exact linear part of `brain.project_input`. It is computed column by column on a
|
| 42 |
+
copy with FlyHash switched off, because FlyHash is nonlinear.
|
| 43 |
+
* `recurrent_k[dst, src]` holds `0.52 * w` summed over the synapses with delay `k`, where `0.52` is the
|
| 44 |
+
recurrent gain of the fast channel. Static gains are folded into `w` when their mechanisms are on: int8
|
| 45 |
+
quantisation, region-pair route gains, myelin gain `0.85 + 0.25 * myelin`, and structural source weights.
|
| 46 |
+
The recurrent weights are a frozen snapshot of the synapse table.
|
| 47 |
+
* `delay_k` holds the delay in ms. Without `synaptic_delays` there is a single class `k = 1`, the one-step
|
| 48 |
+
recurrence of the engine. That class also breaks the recurrent loop in the simulator.
|
| 49 |
+
|
| 50 |
+
**Cell mapping (`cell_parameters`).** The constants come from `CellPopulation.step` in
|
| 51 |
+
`synapse/neuroweave/cells.py`. A per-step decay maps to a time constant by the zero-order-hold relation
|
| 52 |
+
`tau = -dt / ln(decay)`:
|
| 53 |
+
|
| 54 |
+
| NEUROWEAVE (per step) | NIR parameter |
|
| 55 |
+
|---|---|
|
| 56 |
+
| `fast = 0.58 fast + u + 0.52 I_rec` | `CubaLIF` current: `tau_syn = -dt / ln 0.58`, `w_in = 1 / (1 - 0.58)` |
|
| 57 |
+
| `membrane = 0.78 membrane + 0.22 (0.84 fast) - 0.06 adaptation` | `tau_mem = -dt / ln 0.78`, `r = 0.84`, `v_leak = 0` |
|
| 58 |
+
| spike when `membrane > threshold`, `threshold = 0.53` at rest | `v_threshold = 0.53` |
|
| 59 |
+
| `membrane <- 0.26 membrane` at a spike | `v_reset = 0.26 * 0.53` (closest constant) |
|
| 60 |
+
|
| 61 |
+
Cells without `membrane_dynamics` become `LIF` on the fast channel: `tau = -dt / ln 0.58`,
|
| 62 |
+
`r = 1 / (1 - 0.58)`, and `v_threshold = atanh(0.53) / 0.84`, the fast level at which `tanh(0.84 fast)`
|
| 63 |
+
crosses 0.53. The source never resets the fast channel, so `v_reset = v_threshold`.
|
| 64 |
+
|
| 65 |
+
**Lossy features (`unrepresentable_features`).** Each entry gives `feature`, `kind` and `treatment`
|
| 66 |
+
(`approximated`, `dropped` or `frozen_snapshot`) with a reason. The entries are:
|
| 67 |
+
|
| 68 |
+
* Always: graded `tanh` output transmission (NIR edges from a spiking node carry 0/1 spikes), the direct 0.16
|
| 69 |
+
recurrent feed-through, the readout head, input clipping, and runtime controls.
|
| 70 |
+
* With `membrane_dynamics`: the multiplicative reset, the refractory hold, the adaptive threshold and
|
| 71 |
+
adaptation current, and calcium feedback.
|
| 72 |
+
* Without `membrane_dynamics`: the threshold on the graded output and the absence of reset in the source.
|
| 73 |
+
* Every enabled neuron mechanism (multi-soma, dendrites, sparse code, ...) and state-dependent connectome gain.
|
| 74 |
+
* Plasticity rules, exported as a `frozen_snapshot` of current weights.
|
| 75 |
+
* Engine-level mechanisms outside the brain graph.
|
| 76 |
+
|
| 77 |
+
**Validation (`validate_graph`).** The checks are:
|
| 78 |
+
|
| 79 |
+
* known node types with exactly the expected parameter fields, and finite parameters;
|
| 80 |
+
* consistent 1-D parameter vectors and 2-D weights, positive time constants and non-negative delays;
|
| 81 |
+
* edge endpoints that exist, and no duplicate edges;
|
| 82 |
+
* no edges into an `Input` or out of an `Output`;
|
| 83 |
+
* matching shapes along every edge, and at least one `Input` and one `Output`.
|
| 84 |
+
|
| 85 |
+
The function returns a report (`valid`, `errors`, `warnings`, counts and node types). It never raises on a bad
|
| 86 |
+
graph.
|
| 87 |
+
|
| 88 |
+
**Serialisation (`write_nir`, `read_nir`).** With `backend='auto'`, the module writes a real NIR file with
|
| 89 |
+
`nir.write` and reads it back with `nir.read`, but only if the optional `nir` package imports. Otherwise it
|
| 90 |
+
writes JSON tagged `'format': 'nir-json-fallback'`. `backend='json'` forces the fallback, and `'nir'` requires
|
| 91 |
+
the package. `read_nir` detects the format from the HDF5 signature. Either path reports whether the read-back
|
| 92 |
+
graph equals the written one: same node names and types, the same parameter values compared exactly, and the
|
| 93 |
+
same edge set.
|
| 94 |
+
|
| 95 |
+
**Simulator (`simulate_graph`).** A small NumPy discrete-time simulator for the node types above. It uses the
|
| 96 |
+
zero-order-hold forms of the NIR equations:
|
| 97 |
+
|
| 98 |
+
* `LI`/`LIF`: `v <- a v + (1 - a)(v_leak + r x)` with `a = exp(-dt / tau)`.
|
| 99 |
+
* `Cuba*`: `i <- a_s i + (1 - a_s) w_in x`, then `v` as above, driven by `r i`.
|
| 100 |
+
* Spiking types emit `v > v_threshold` and reset to `v_reset`. The simulator checks the membrane potential
|
| 101 |
+
before reset so numerical overflow appears in the `finite` result even when the output spike is finite.
|
| 102 |
+
* `Delay` outputs its input from `round(delay / dt)` steps earlier. Delays of at least one step break
|
| 103 |
+
recurrent loops; a loop without one raises `ValueError`.
|
| 104 |
+
|
| 105 |
+
**Experiment (`run_experiment`).** Each seed builds a brain with `make_spec`, by default 48 neurons on the
|
| 106 |
+
`clustered` topology with `membrane_dynamics`, `synaptic_delays`, `quantised_synapses` and `stdp`. It runs
|
| 107 |
+
warm-up steps on seeded inputs, then exports, validates, writes and reads back a file, and simulates the
|
| 108 |
+
exported graph. The checks, all of which must hold for `verdict: 'pass'`:
|
| 109 |
+
|
| 110 |
+
* `graph_valid`, `node_types_known`.
|
| 111 |
+
* `round_trip_equal`, `edge_and_node_counts_preserved`.
|
| 112 |
+
* `synapse_count_matches`: the non-zero recurrent entries equal the represented count, which is at most the
|
| 113 |
+
number of unique `(src, dst, delay)` triples.
|
| 114 |
+
* `recurrent_drive_parity`: the exported Delay/Linear pairs, applied to NEUROWEAVE's own output history,
|
| 115 |
+
reproduce `SynapseTable.transmit` within `1e-9`. This check does not apply, and is recorded as such, when
|
| 116 |
+
state-dependent gains are on.
|
| 117 |
+
* `synaptic_current_parity`: isolated cells, with no recurrent input and the same random drive. The exported
|
| 118 |
+
current equals the fast channel within `1e-9`.
|
| 119 |
+
* `membrane_parity_before_first_spike`: the exported membrane equals NEUROWEAVE's membrane minus its
|
| 120 |
+
accumulated adaptation current (a dropped feature, corrected for explicitly) within `1e-9`, up to each
|
| 121 |
+
cell's first spike.
|
| 122 |
+
* `simulation_finite`, `simulation_active` (at least one spike).
|
| 123 |
+
* `lossy_features_listed`.
|
| 124 |
+
|
| 125 |
+
The spike rates of the exported graph and of NEUROWEAVE on the same inputs, and the first-spike agreement of
|
| 126 |
+
isolated cells, are reported side by side as descriptive numbers. They are not expected to agree, because of
|
| 127 |
+
the listed approximations.
|
| 128 |
+
|
| 129 |
+
## Public API
|
| 130 |
+
|
| 131 |
+
```python
|
| 132 |
+
MODULE_ID = 'nir_export'; EXPERIMENTS = {'nir_export': run_experiment}
|
| 133 |
+
FALLBACK_FORMAT = 'nir-json-fallback'; NIR_FORMAT = 'nir-hdf5'
|
| 134 |
+
NODE_PARAMS; NIR_NODE_TYPES; NEURON_TYPES; SPIKING_TYPES; CELL_CONSTANTS
|
| 135 |
+
run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed validation receipt
|
| 136 |
+
brain_to_nir(source, *, input_dim=None, step_ms=1.0) -> dict
|
| 137 |
+
cell_parameters(model, *, dt=1.0) -> dict # model in ('CubaLIF', 'LIF')
|
| 138 |
+
unrepresentable_features(source) -> list[dict]
|
| 139 |
+
validate_graph(graph) -> dict; node_io_shapes(name, node, errors=None)
|
| 140 |
+
canonical_graph(graph, *, include_metadata=True) -> dict; graphs_equal(a, b) -> bool
|
| 141 |
+
write_nir(graph, path, *, backend='auto') -> dict; read_nir(path) -> dict; nir_status() -> dict
|
| 142 |
+
simulate_graph(graph, inputs, *, dt=None, record_states=False, max_steps=100_000) -> dict
|
| 143 |
+
```
|
| 144 |
+
|
| 145 |
+
The `run_experiment` overrides are `neurons`, `topology`, `mechanisms`, `warmup_steps`, `simulate_steps`,
|
| 146 |
+
`input_dim`, `input_scale`, `step_ms`, `parity_cells`, `parity_steps`, `parity_drive_max`,
|
| 147 |
+
`parity_tolerance` and `backend`. `quick=True` sets 24 neurons, 30 warm-up steps, 80 simulated steps, and 8
|
| 148 |
+
parity cells for 80 steps.
|
| 149 |
+
|
| 150 |
+
All randomness comes from `numpy.random.default_rng(seed + offset)`. No global NumPy or torch RNG or thread
|
| 151 |
+
state is touched (tested). Bad input raises `ValueError` before anything is written. Graph and file sizes are
|
| 152 |
+
bounded (4096 nodes, 65 536 edges, 4 M parameter elements per field, 100 000 simulated steps).
|
| 153 |
+
|
| 154 |
+
## Connection to Sonapse
|
| 155 |
+
|
| 156 |
+
* An offline tool. It reads a brain, an engine or their exports and never writes back. Nothing in the live
|
| 157 |
+
runtime calls it, and no Sonapse or NEUROWEAVE default, API or checkpoint format changes.
|
| 158 |
+
* `nir` is an optional dependency. It is imported lazily, and a broken install falls back to JSON.
|
| 159 |
+
|
| 160 |
+
## Not implemented
|
| 161 |
+
|
| 162 |
+
* **The real-NIR path is untested here.** The `nir` package is not installed in this build, so `nir.write`,
|
| 163 |
+
`nir.read`, the conversion to `nir.NIRGraph` and NIR's own type checking of this recurrent graph have not
|
| 164 |
+
been exercised. The test `test_real_nir_round_trip` is skipped. The conversion code follows the field names
|
| 165 |
+
verified in the package source (see below).
|
| 166 |
+
* NIR's other primitives: `Conv1d`, `Conv2d`, `Flatten`, `SumPool2d`, `AvgPool2d` and `Threshold`.
|
| 167 |
+
Multi-dimensional shapes are also not handled.
|
| 168 |
+
* Exact representation of the NEUROWEAVE cell. Graded transmission, multiplicative reset, refractoriness, the
|
| 169 |
+
adaptive threshold and every listed mechanism are approximated or dropped. Plasticity is not representable
|
| 170 |
+
in NIR and is exported as a frozen snapshot.
|
| 171 |
+
* Continuous-time semantics. The simulator is a zero-order-hold discretisation with the step `dt`, and NIR
|
| 172 |
+
backends may integrate differently.
|
| 173 |
+
* Importing a NIR graph back into a NEUROWEAVE brain.
|
| 174 |
+
|
| 175 |
+
## Verified references
|
| 176 |
+
|
| 177 |
+
Checked on 2026-11-20.
|
| 178 |
+
|
| 179 |
+
1. Jens E. Pedersen, Steven Abreu, Matthias Jobst, Gregor Lenz, Vittorio Fra, Felix Christian Bauer, Dylan
|
| 180 |
+
Richard Muir, Peng Zhou, Bernhard Vogginger, Kade Heckel, Gianvito Urgese, Sadasivan Shankar, Terrence C.
|
| 181 |
+
Stewart, Sadique Sheik, Jason K. Eshraghian. **Neuromorphic intermediate representation: A unified
|
| 182 |
+
instruction set for interoperable brain-inspired computing.** *Nature Communications* 15, 8122, published
|
| 183 |
+
16 September 2024 (PubMed Central). doi:10.1038/s41467-024-52259-9,
|
| 184 |
+
https://www.nature.com/articles/s41467-024-52259-9, https://pmc.ncbi.nlm.nih.gov/articles/PMC11405706/.
|
| 185 |
+
Preprint: arXiv:2311.14641. Title, author order, volume, article number and date were checked on the PMC
|
| 186 |
+
page. The base primitives (Input, Output, Affine, Convolution, Delay, Flatten, Integrator, Leaky
|
| 187 |
+
integrator, Linear, Scale, Spike) and the higher-order IF, LIF and CuBa-LIF were checked against the
|
| 188 |
+
paper's primitives table on the same page. (OSTI lists 15 September 2024.)
|
| 189 |
+
2. NIR Python package, https://github.com/neuromorphs/NIR, main branch, checked on 2026-11-20:
|
| 190 |
+
* `nir/ir/neuron.py`: field names and order of `I`, `IF`, `LI`, `LIF`, `CubaLI`, `CubaLIF`, and the
|
| 191 |
+
documented dynamics `tau dv/dt = (v_leak - v) + R I` and `tau_syn dI/dt = -I + w_in S`.
|
| 192 |
+
* `nir/ir/linear.py`: `Affine(weight, bias)`, `Linear(weight)`, `Scale(scale)`, with the output size taken
|
| 193 |
+
from `weight.shape[-2]`.
|
| 194 |
+
* `nir/ir/delay.py`: `Delay(delay)` with `y(t) = x(t - tau)`.
|
| 195 |
+
* `nir/ir/graph.py`: `Input(input_type)`, `Output(output_type)`, and `NIRGraph(nodes, edges)` with type
|
| 196 |
+
checking on by default.
|
| 197 |
+
* `nir/serialization.py`: `write(filename, graph, compression='gzip', ...)` and
|
| 198 |
+
`read(filename, type_check=True)`, using HDF5 through `h5py`.
|
| 199 |
+
* PyPI https://pypi.org/project/nir/ lists release 1.0.8 (6 July 2026) as the latest.
|
| 200 |
+
|
| 201 |
+
## Measured results
|
| 202 |
+
|
| 203 |
+
Measured on 2026-11-20 on Windows 11 on ARM64, with Python 3.12.10, NumPy 2.4 and one BLAS/OpenMP thread
|
| 204 |
+
(`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1`), without the `nir` package, so the JSON fallback
|
| 205 |
+
was used. Seeds were 0, 1 and 2. Receipts are deterministic: two runs of the quick receipt gave the same digest
|
| 206 |
+
(tested). Wall-clock covers the whole call on a machine shared with other jobs.
|
| 207 |
+
|
| 208 |
+
| Run | Verdict | Key numbers | Wall-clock |
|
| 209 |
+
|---|---|---|---|
|
| 210 |
+
| `run_experiment(quick=True)` | `pass` (11/11 checks) | 24 neurons; 140 / 142 / 137 synapses, all represented; delay classes 1, 2, 3; graph of 10 nodes (Input, Linear ×4, CubaLIF, Delay ×3, Output) and 12 edges. Recurrent drive parity max abs diff 4.4e-16. Synaptic current diff 0. Membrane diff before first spike ≤ 1.1e-16. 10 lossy features listed. Exported-graph spike rate 0.0042 / 0.0031 / 0.0047 per cell-step vs NEUROWEAVE 0.240 / 0.0031 / 0.0 on the same inputs. Isolated-cell first-spike agreement 0.875 / 0.625 / 0.875 | 1.1–1.4 s |
|
| 211 |
+
| `run_experiment()` | `pass` (11/11 checks) | 48 neurons; 281 / 276 / 286 synapses, all represented. Recurrent parity ≤ 4.4e-16. Membrane diff ≤ 2.2e-16. Exported-graph spike rate 0.0044 / 0.0053 / 0.0056 vs NEUROWEAVE 0.051 / 0.0056 / 0.012. First-spike agreement 0.75 / 0.81 / 0.56 | 2.5 s |
|
| 212 |
+
|
| 213 |
+
Cell parameters at `dt = 1 ms`: `tau_syn = 1.836`, `tau_mem = 4.025`, `r = 0.84`, `w_in = 2.381`,
|
| 214 |
+
`v_threshold = 0.53`, `v_reset = 0.1378`.
|
| 215 |
+
|
| 216 |
+
The parity checks show that the parts called exact (linear input map, recurrent synapse table, synaptic
|
| 217 |
+
current, and the membrane up to the dropped adaptation current) are exact to rounding. The network-level spike
|
| 218 |
+
rates differ widely between the exported graph and NEUROWEAVE. This is expected: NIR edges carry binary spikes
|
| 219 |
+
where NEUROWEAVE transmits a graded `tanh` output, and refractoriness and the adaptive threshold are dropped.
|
| 220 |
+
The export is an interchange format with documented losses, not a faithful re-implementation.
|
docs/frontier/modules/quality_diversity.md
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `quality_diversity`: quality-diversity architecture search
|
| 2 |
+
|
| 3 |
+
Module file: `synapse/frontier/quality_diversity.py` · tests: `tests/test_frontier_quality_diversity.py` ·
|
| 4 |
+
experiment id: `quality_diversity` · kind: discovery (a search over NEUROWEAVE configurations; no live observer) ·
|
| 5 |
+
evidence tier: `synthetic_abstraction`.
|
| 6 |
+
|
| 7 |
+
The module searches a small, declared space of NEUROWEAVE configurations with a **MAP-Elites** archive (Mouret &
|
| 8 |
+
Clune, 2015): a grid over two behaviour descriptors that keeps the best configuration found in each cell. Parents
|
| 9 |
+
are drawn from the **Darwin Gödel Machine** (DGM) parent distribution (Zhang et al., 2025), which favours fit
|
| 10 |
+
elites that have few verified children. Every candidate passes a **verification gate** before it may enter the
|
| 11 |
+
archive: its sealed receipt must verify and match what the search asked for, and every k-th candidate is run again
|
| 12 |
+
and must reproduce the same receipt digest. Rejected candidates are logged with reasons, every evaluated candidate
|
| 13 |
+
is a node of a lineage DAG, and the archive exports to JSON with a SHA-256 integrity hash.
|
| 14 |
+
|
| 15 |
+
The design also borrows from two sibling `kai9987kai` projects. SONAPSE-ORIGIN contributes a 2-D MAP-Elites grid
|
| 16 |
+
with edge-clipped bins, NSGA-II Pareto sorting, and mutation plus crossover. sonapse-evo contributes structural
|
| 17 |
+
operators with preconditions, audit receipts, a failure archive with reasons, and verify-before-commit
|
| 18 |
+
transactions.
|
| 19 |
+
|
| 20 |
+
The module is *inspired by* these sources and reproduces none of them. DGM evolves self-modifying coding agents
|
| 21 |
+
that are checked on coding benchmarks. Here each candidate is a tiny NEUROWEAVE engine (16–32 neurons) trained for
|
| 22 |
+
16–48 steps on a synthetic temporal task, and a run evaluates 5–48 candidates per arm.
|
| 23 |
+
|
| 24 |
+
## What it computes
|
| 25 |
+
|
| 26 |
+
### Genome and search space
|
| 27 |
+
|
| 28 |
+
```
|
| 29 |
+
genome = (mechanisms ⊆ M, topology ∈ T, neurons ∈ N, sparsity ∈ S)
|
| 30 |
+
M = 10 NEUROWEAVE switches (SEARCH_MECHANISMS): structural_encoder, sparse_code, reward_plasticity,
|
| 31 |
+
synaptic_delays, homeostatic_governor, context_attention, flyhash_projection, adaptive_routing,
|
| 32 |
+
hierarchical_temporal_memory, membrane_dynamics
|
| 33 |
+
T = all 12 NEUROWEAVE topologies (synapse.neuroweave.spec.TOPOLOGIES)
|
| 34 |
+
N = (16, 24, 32) neurons S = (0.05, 0.15, 0.3, 0.5) k-winners-take-all fraction
|
| 35 |
+
|space| = 2^10 · 12 · 3 · 4 = 147,456 genomes
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
`Genome.to_spec(seed=, steps=)` is the NEUROWEAVE lab spec (`experiments.make_spec`) with the genome's `sparsity`.
|
| 39 |
+
The sparsity gene only acts when `sparse_code` is on. Without it, two genomes that differ only in sparsity give
|
| 40 |
+
identical metrics and descriptors but different specs, so their receipt digests differ (tested). Genomes are
|
| 41 |
+
canonical: mechanisms are kept in NEUROWEAVE order, and `Genome.key` (canonical JSON) identifies duplicates.
|
| 42 |
+
|
| 43 |
+
Measured on 2026-11-20 (16 neurons, `clustered`, 16 training steps, held-out seed 100 × 8 steps):
|
| 44 |
+
|
| 45 |
+
* five of the ten switches change the estimated operation count of a training run (17,840 with no switch):
|
| 46 |
+
`structural_encoder` +3,072, `adaptive_routing` +2,848, `context_attention` +2,048, `flyhash_projection` +2,048
|
| 47 |
+
and `sparse_code` +1,024; the other five change nothing;
|
| 48 |
+
* topology changes it too (15,872 to 21,200 with no switch);
|
| 49 |
+
* log2 ops per training step is 10.12 / 10.68 / 11.06 at 16 / 24 / 32 neurons (no switch, `clustered`).
|
| 50 |
+
|
| 51 |
+
### Variation (sonapse-evo style operators)
|
| 52 |
+
|
| 53 |
+
| Operator | Precondition | Change |
|
| 54 |
+
|---|---|---|
|
| 55 |
+
| `toggle_mechanism` | the space has a mechanism | flips one search-set mechanism on or off |
|
| 56 |
+
| `swap_mechanism` | 1 ≤ active < \|M\| | replaces one active mechanism with an inactive one |
|
| 57 |
+
| `change_topology` | ≥ 2 topologies | a different topology, uniformly |
|
| 58 |
+
| `step_neurons` | ≥ 2 neuron choices | an adjacent neuron count |
|
| 59 |
+
| `step_sparsity` | ≥ 2 sparsity choices | an adjacent k-WTA fraction |
|
| 60 |
+
|
| 61 |
+
`mutate` applies one applicable operator chosen uniformly. It then applies each further operator with
|
| 62 |
+
probability `extra_prob` (0.25), up to `max_operators` (3). A child that equals its parent (for example, the same
|
| 63 |
+
mechanism toggled twice) gets one more change, so a child always differs from its parent. Each change is logged
|
| 64 |
+
as an operator string, for example `toggle_mechanism:+sparse_code` or `step_neurons:16->24`; the tests replay these
|
| 65 |
+
trails and recover the child exactly. `crossover` is uniform: each mechanism's membership, and each other gene,
|
| 66 |
+
comes from either parent with probability 1/2.
|
| 67 |
+
|
| 68 |
+
### Evaluation, fitness and descriptors
|
| 69 |
+
|
| 70 |
+
`NeuroWeaveEvaluator(task, steps, heldout_seeds, heldout_steps)` follows the protocol of the lab's
|
| 71 |
+
`experiments._task_arm`:
|
| 72 |
+
|
| 73 |
+
* **Training.** A fresh engine is built from the genome's spec. It and a fresh `ReadoutHead` (logistic, learning
|
| 74 |
+
rate 0.05) run prequentially, with learning on, over `make_stream(seed, steps)`.
|
| 75 |
+
* **Held out.** For each held-out seed `h`, the trained engine and a copy of the head run frozen (`learn=False`)
|
| 76 |
+
over `make_stream(h, heldout_steps)`. Every stream starts from the trained state: a validated clone runs every
|
| 77 |
+
stream except the last, and the trained engine itself runs the last. An `ActivityRecorder` is attached to each.
|
| 78 |
+
|
| 79 |
+
At `sparsity = 0.15` (the spec default), the metrics, estimated cost and budget equal `_task_arm`'s exactly
|
| 80 |
+
(tested). The recorder is a read-only engine extension: it adds no readout features and leaves the drive
|
| 81 |
+
untouched. Engine outputs and the engine's state digest are identical with and without it (tested).
|
| 82 |
+
|
| 83 |
+
```
|
| 84 |
+
fitness f = mean held-out accuracy (ties: lower mean held-out log loss, then earlier)
|
| 85 |
+
d_cost = log2( estimated_cost.total_ops / training steps ) (from the candidate's own receipt)
|
| 86 |
+
d_activity = mean over held-out steps t of H(y_t), H(x) = (√n − ‖x‖₁ / ‖x‖₂) / (√n − 1) (Hoyer, 2004)
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
`y_t` is the engine output vector. `H` is 1 for a single non-zero entry and 0 for equal magnitudes. All-zero
|
| 90 |
+
steps are skipped (H is undefined there) and counted as `silent_steps`; a run with no scored step counts as 1.0.
|
| 91 |
+
Each candidate's result is a sealed receipt (`experiment_id 'quality_diversity_candidate'`, `kind
|
| 92 |
+
'candidate_evaluation'`) with the genome, seed, spec, protocol, train and held-out metrics, activity statistics,
|
| 93 |
+
estimated cost, budget, fitness and descriptors. Wall-clock is kept outside the digest.
|
| 94 |
+
|
| 95 |
+
Measured on 2026-11-20 (same settings as above): without `sparse_code` the outputs are dense, with `d_activity`
|
| 96 |
+
0.0008 (0.0000 to 0.0796 across the 12 topologies). With `sparse_code`, `d_activity` is 0.829 / 0.741 / 0.507 /
|
| 97 |
+
0.339 at sparsity 0.05 / 0.15 / 0.3 / 0.5. In this space the activity axis therefore mostly sorts `sparse_code`
|
| 98 |
+
genomes by their k-WTA fraction.
|
| 99 |
+
|
| 100 |
+
`LandscapeEvaluator(target, space)` is a deterministic synthetic evaluator with a known answer, used by the tests.
|
| 101 |
+
It runs no NEUROWEAVE engine. Fitness is the fraction of genes equal to a hidden target genome, so the target is
|
| 102 |
+
the unique optimum with fitness 1. Its descriptors are analytic: ops per step `16 · neurons · (4 + #mechanisms)`,
|
| 103 |
+
and activity `1 − sparsity` with `sparse_code` or 0.05 without.
|
| 104 |
+
|
| 105 |
+
### Archive (MAP-Elites grid)
|
| 106 |
+
|
| 107 |
+
```
|
| 108 |
+
cell(d) = ( bin(d_cost; lo_c, hi_c, B_c), bin(d_activity; lo_a, hi_a, B_a) )
|
| 109 |
+
bin(v) = clip( ⌊(v − lo) / (hi − lo) · B⌋, 0, B − 1 ) # out-of-range values join the edge cells
|
| 110 |
+
admit x' into cell b' iff b' is empty or (f', −loss') > (f, −loss) of the elite in b'
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
This is the replacement rule of the paper's Fig. 2 (`P(b′) = ∅ or P(b′) < p′`), with log loss as tie-break.
|
| 114 |
+
Exact ties keep the earlier elite. The invariant is that each cell holds the verified candidate with the highest
|
| 115 |
+
`(f, −loss)` among all verified candidates that mapped to it. It is tested against a brute-force map of a
|
| 116 |
+
32-genome space, and checked again on import by replaying the lineage.
|
| 117 |
+
|
| 118 |
+
### Parent selection (DGM)
|
| 119 |
+
|
| 120 |
+
```
|
| 121 |
+
s_i = 1 / (1 + exp(−λ (f_i − f_0))) h_i = 1 / (1 + n_i) p_i = s_i h_i / Σ_j s_j h_j
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
* **Eligibility.** The distribution is taken over elites with `f_i < 1`, as in DGM. When every elite has
|
| 125 |
+
`f_i = 1`, all elites are eligible: this fallback is ours, because DGM does not define that case. DGM writes
|
| 126 |
+
the normaliser `Σ_j` over the whole archive while sampling from the eligible set; we normalise over the
|
| 127 |
+
eligible set, so the probabilities sum to 1.
|
| 128 |
+
* **Values.** `λ = 10` and `f_0 = 0.5` are DGM's values. `n_i` is the number of the elite's children that passed
|
| 129 |
+
verification; DGM counts children that kept their codebase-editing functionality.
|
| 130 |
+
* **Drawing parents.** DGM samples `k` parents with replacement, and each makes its own child. Here each variation
|
| 131 |
+
step draws two parents with replacement and makes one child. With probability `crossover_rate` (0.25), and only
|
| 132 |
+
when the two are distinct elites, the child is `mutate(crossover(a, b))`; otherwise it is `mutate(a)`.
|
| 133 |
+
|
| 134 |
+
`selection='uniform'` gives the paper's uniform random choice of elite and serves as the ablation. The first
|
| 135 |
+
`initial_random` candidates (G in the paper) are random genomes. Up to `max_resample` (16) proposals are drawn to
|
| 136 |
+
avoid re-proposing a genome that was already evaluated.
|
| 137 |
+
|
| 138 |
+
### Verification gate
|
| 139 |
+
|
| 140 |
+
`verify_candidate(genome, receipt, seed=, protocol=, space=)` never raises for a bad receipt. It returns the
|
| 141 |
+
failed reason codes, and an empty list means the candidate passed. Each check is made against what the search
|
| 142 |
+
asked for, not against the receipt itself.
|
| 143 |
+
|
| 144 |
+
| Reason | Meaning |
|
| 145 |
+
|---|---|
|
| 146 |
+
| `receipt_not_a_mapping` | the evaluator returned something other than a mapping |
|
| 147 |
+
| `receipt_digest_mismatch` | the SHA-256 seal does not verify (edited after sealing) |
|
| 148 |
+
| `receipt_schema_mismatch` | schema, experiment id, kind, evidence tier or module differ |
|
| 149 |
+
| `genome_outside_space` | the genome is outside the declared space |
|
| 150 |
+
| `genome_mismatch` | the receipt's genome is not the proposed one |
|
| 151 |
+
| `protocol_mismatch` | the protocol or the seed differ from the search's |
|
| 152 |
+
| `invalid_spec` | the receipt's spec is not a valid `NeuroWeaveSpecV1` |
|
| 153 |
+
| `spec_mismatch` | the spec is valid but is not the spec the genome implies |
|
| 154 |
+
| `invalid_metrics` | fitness or descriptor source fields are missing or out of range |
|
| 155 |
+
| `inconsistent_metrics` | the stated fitness or descriptors differ from those recomputed from the raw fields |
|
| 156 |
+
| `evaluation_error` | the evaluator raised; the message is logged, truncated to 200 characters |
|
| 157 |
+
| `spot_check_digest_mismatch` | the re-evaluation produced a different digest |
|
| 158 |
+
| `spot_check_error` | the re-evaluation raised |
|
| 159 |
+
|
| 160 |
+
**Spot checks.** With `spot_check_every = k` (default 4), candidates number k, 2k, 3k, … (in evaluation order)
|
| 161 |
+
that pass the static checks are evaluated again. The re-run calls the evaluator itself, never the cache, and must
|
| 162 |
+
reproduce the receipt digest. `k = 0` disables spot checks; it exists only as an ablation.
|
| 163 |
+
|
| 164 |
+
**Rejection.** A rejected candidate goes into the lineage and the rejection log. The grid and the child counts are
|
| 165 |
+
untouched.
|
| 166 |
+
|
| 167 |
+
What the gate catches (tested):
|
| 168 |
+
|
| 169 |
+
* receipts edited after sealing;
|
| 170 |
+
* re-sealed receipts whose stated fitness disagrees with their raw metrics;
|
| 171 |
+
* wrong specs, genomes, protocols and seeds;
|
| 172 |
+
* evaluator exceptions.
|
| 173 |
+
|
| 174 |
+
A *consistently* re-sealed lie passes every static check. Only a re-evaluation catches it, and only on candidates
|
| 175 |
+
that are spot-checked. In the tests, inflated answers were all rejected with `spot_check_every = 1`. With
|
| 176 |
+
`spot_check_every = 0` they were admitted, and a later `audit()`, which re-evaluates every elite, flagged them. A
|
| 177 |
+
SHA-256 seal detects accidental or naive edits; it is not a signature.
|
| 178 |
+
|
| 179 |
+
### Lineage, persistence and metrics
|
| 180 |
+
|
| 181 |
+
* **Lineage.** Every evaluated candidate is a node with: id, genome, origin (`random` / `mutation` /
|
| 182 |
+
`crossover`), parents, operator trail, status (`elite` / `not_elite` / `rejected`), reasons, error, cell,
|
| 183 |
+
fitness, log loss, descriptors, receipt digest, `spot_checked` and `displaced_by`. A child's parents were
|
| 184 |
+
elites when it was created, so the lineage is a DAG in id order. It is bounded by the evaluation budget
|
| 185 |
+
(`max_nodes`).
|
| 186 |
+
* **Export.** `export_json()` writes canonical JSON:
|
| 187 |
+
`{schema: 'QualityDiversityArchiveV1', schema_version: 1, sha256, payload}`. The payload holds the grid
|
| 188 |
+
configuration, the elites with their sealed receipts (wall-clock removed, so exports are deterministic), the
|
| 189 |
+
lineage and the rejection log. `sha256` is the SHA-256 of the canonical payload (sorted keys, compact
|
| 190 |
+
separators).
|
| 191 |
+
* **Import.** `import_json()` / `EliteArchive.from_json()` validate everything before changing anything:
|
| 192 |
+
* the hash, the schema and the grid configuration;
|
| 193 |
+
* every lineage node;
|
| 194 |
+
* a full replay of the lineage, which must reproduce each node's status and `displaced_by`, the grid and the
|
| 195 |
+
rejection log;
|
| 196 |
+
* every elite's receipt, which must verify and match its entry and its lineage node.
|
| 197 |
+
|
| 198 |
+
Eighteen tamper cases are tested, and none changes the target archive.
|
| 199 |
+
* **Metrics.**
|
| 200 |
+
* QD-score is the total fitness over filled cells (Pugh et al., 2015). Coverage is filled cells over grid cells.
|
| 201 |
+
* Reliability, precision and `coverage_of_union` (Mouret & Clune, 2015, Sec. 5 and 9.4) are computed per seed
|
| 202 |
+
over the union of cells that either arm filled.
|
| 203 |
+
* Our convention: a filled cell whose best value is 0 counts with ratio 1. The paper instead divides by the
|
| 204 |
+
number of cells with a non-zero best value, and takes the best over all runs of all treatments, not over
|
| 205 |
+
the two arms of one seed.
|
| 206 |
+
* The summary also lists the Pareto front of the elites in (fitness, −log2 ops per step), cheapest first. This
|
| 207 |
+
is the sibling projects' multi-objective view of the same archive.
|
| 208 |
+
|
| 209 |
+
## Lab experiment (`run_experiment`, id `quality_diversity`)
|
| 210 |
+
|
| 211 |
+
The two arms are `quality_diversity` (MAP-Elites with DGM selection) and `random_search`. Per seed they share:
|
| 212 |
+
|
| 213 |
+
* the evaluator: the task, the training stream `seed` and the held-out streams;
|
| 214 |
+
* the search space, the grid, the verification gate and the spot-check schedule;
|
| 215 |
+
* the candidate budget.
|
| 216 |
+
|
| 217 |
+
Their first `initial_random` candidates are identical (common random numbers). Those candidates are evaluated once
|
| 218 |
+
through a per-seed cache, which the spot checks bypass. After the search, each arm's best elite is re-evaluated on
|
| 219 |
+
fresh `test_seeds` streams (`best_test`), because `best_fitness` is selected on the held-out streams and is
|
| 220 |
+
therefore optimistic.
|
| 221 |
+
|
| 222 |
+
* **Metrics per arm and seed.** `qd_score`, `coverage`, `best_fitness`, `best_test_accuracy`, `reliability`,
|
| 223 |
+
`precision` and `coverage_of_union`.
|
| 224 |
+
* **Comparisons.** `harness.compare` of QD − random for every metric, paired over seeds.
|
| 225 |
+
* **Verdict.** The `qd_score` comparison: `improved` only when the 95 % t interval excludes zero on the better
|
| 226 |
+
side.
|
| 227 |
+
|
| 228 |
+
| Setting | Default | `quick=True` |
|
| 229 |
+
|---|---|---|
|
| 230 |
+
| task | `delayed_recall` | same |
|
| 231 |
+
| training / held-out steps | 48 / 24 | 16 / 8 |
|
| 232 |
+
| held-out seeds / test seeds | (100, 101) / (200, 201) | (100,) / (200,) |
|
| 233 |
+
| candidates per arm per seed (`budget`) | 16 | 5 |
|
| 234 |
+
| `initial_random` / `spot_check_every` | 6 / 4 | 3 / 2 |
|
| 235 |
+
| neurons | (16, 24, 32) | (16,) |
|
| 236 |
+
| grid | 4 × 4; cost (10.0, 12.0), activity (0.0, 0.8) | cost (10.1, 10.8) |
|
| 237 |
+
| selection / `crossover_rate` / `extra_mutation_prob` | DGM (λ 10, f₀ 0.5) / 0.25 / 0.25 | same |
|
| 238 |
+
|
| 239 |
+
`delayed_recall` is the default task because it separated genomes best in a scan on 2026-11-20. The scan covered
|
| 240 |
+
10 random genomes from the default space (drawn with `default_rng(0)`; seed 0; 48 training steps; held-out seeds
|
| 241 |
+
100 and 101 × 24 steps):
|
| 242 |
+
|
| 243 |
+
| Task | Distinct held-out accuracies | sd (population) | Best / majority-class rate |
|
| 244 |
+
|---|---|---|---|
|
| 245 |
+
| `delayed_recall` | 6 | 0.075 | 0.604 / 0.583 |
|
| 246 |
+
| `xor` | 4 | 0.062 | 0.688 / 0.542 |
|
| 247 |
+
| `parity` | 3 | 0.028 | 0.521 / 0.500 |
|
| 248 |
+
| `delayed_recall_6` | 2 | 0.115 | 0.625 / 0.625 |
|
| 249 |
+
| `rhythm` | 1 (all genomes equal) | 0 | 0.792 / 0.792 |
|
| 250 |
+
| `context_switch` | 1 (all genomes equal) | 0 | 0.500 / 0.542 |
|
| 251 |
+
|
| 252 |
+
Even on `delayed_recall` the best value (0.604) was close to the majority-class rate (0.583). On `xor` the best
|
| 253 |
+
genome rose further above its majority-class rate (0.688 vs 0.542) but the accuracies took fewer distinct values;
|
| 254 |
+
the choice of default task was made on the number of distinct values only.
|
| 255 |
+
|
| 256 |
+
The receipt (`kind: 'search_comparison'`) contains:
|
| 257 |
+
|
| 258 |
+
* `config`, with the space, grid, evaluator protocol and admission rule;
|
| 259 |
+
* per-seed rows for each arm: evaluations, spot checks, evaluator calls, cache hits, status counts, rejections by
|
| 260 |
+
reason, QD-score and coverage trajectories, elites with their candidate-receipt digests, the best elite,
|
| 261 |
+
`best_test`, the Pareto front, lineage statistics and the archive SHA-256;
|
| 262 |
+
* `comparisons`, `verdict` and `verdict_basis`;
|
| 263 |
+
* `budget`: equal candidate budgets and counted evaluator calls;
|
| 264 |
+
* `estimated_cost`: the estimated ops of the verified candidates, kept apart from `measured_wallclock_s`;
|
| 265 |
+
* `notes`.
|
| 266 |
+
|
| 267 |
+
Candidate digests are stored as `receipt_digest`, because receipt seals skip keys named `digest`.
|
| 268 |
+
|
| 269 |
+
## Public API
|
| 270 |
+
|
| 271 |
+
```python
|
| 272 |
+
MODULE_ID = 'quality_diversity'
|
| 273 |
+
EXPERIMENTS = {'quality_diversity': run_experiment}
|
| 274 |
+
run_experiment(*, quick: bool = False, seeds=(0, 1, 2), **overrides) -> dict # overrides: any _DEFAULTS key
|
| 275 |
+
|
| 276 |
+
SEARCH_MECHANISMS, NEURON_CHOICES, SPARSITY_CHOICES, MUTATION_OPERATORS, REJECTION_REASONS, DESCRIPTOR_KEYS,
|
| 277 |
+
ARCHIVE_SCHEMA, CANDIDATE_RECEIPT_ID, MAX_BUDGET, SOURCE
|
| 278 |
+
|
| 279 |
+
Genome(mechanisms, topology, neurons, sparsity) .to_dict() / .from_dict(d) / .key / .to_spec(seed=, steps=)
|
| 280 |
+
GenomeSpace(mechanisms=..., topologies=..., neurons=..., sparsity=...)
|
| 281 |
+
.size / .contains(g) / .random_genome(rng) / .to_dict() / .from_dict(d)
|
| 282 |
+
applicable_operators(genome, space) -> tuple[str, ...]
|
| 283 |
+
mutate(genome, space, rng, *, extra_prob=0.25, max_operators=3) -> (Genome, operator_trail)
|
| 284 |
+
crossover(a, b, space, rng) -> Genome
|
| 285 |
+
dgm_parent_probabilities(fitness, children, *, sharpness=10.0, midpoint=0.5) -> np.ndarray
|
| 286 |
+
hoyer_sparseness(x) -> float | None
|
| 287 |
+
ActivityRecorder() # read-only EngineExtension, id 'qd_activity_recorder'
|
| 288 |
+
NeuroWeaveEvaluator(*, task='delayed_recall', steps=48, heldout_seeds=(100, 101), heldout_steps=24)
|
| 289 |
+
(genome, seed) -> sealed candidate receipt; .evaluate(genome, seed, *, heldout_seeds=None); .protocol()
|
| 290 |
+
LandscapeEvaluator(target, space, *, steps=16) # known-answer synthetic evaluator
|
| 291 |
+
candidate_metrics(receipt) -> dict # recomputed fitness, log loss and descriptors
|
| 292 |
+
verify_candidate(genome, receipt, *, seed, protocol, space) -> list[str]
|
| 293 |
+
EliteArchive(*, cost_bins=4, cost_range=(9.75, 11.75), activity_bins=4, activity_range=(0.0, 0.8), max_nodes=10000)
|
| 294 |
+
.record(...) / .cell_of(d) / .elites() / .elite_receipt(cell) / .best() / .pareto_front() / .qd_score()
|
| 295 |
+
.coverage() / .lineage() / .rejections() / .children_count(id) / .sha256 / .export_json() / .import_json(text)
|
| 296 |
+
EliteArchive.from_json(text)
|
| 297 |
+
QualityDiversitySearch(evaluator, *, seed=0, budget=32, method='qd'|'random', space=None, initial_random=8,
|
| 298 |
+
selection='dgm'|'uniform', crossover_rate=0.25, extra_mutation_prob=0.25, spot_check_every=4,
|
| 299 |
+
selection_sharpness=10.0, selection_midpoint=0.5, max_resample=16, cost_bins=4,
|
| 300 |
+
cost_range=(9.75, 11.75), activity_bins=4, activity_range=(0.0, 0.8), cache=None)
|
| 301 |
+
.step() / .run() -> summary / .summary() / .audit() / .parent_probabilities() / .config() / .done / .archive
|
| 302 |
+
illumination_metrics({run: {cell: fitness}}) -> {run: {reliability, precision, coverage_of_union}}
|
| 303 |
+
pareto_front(points) -> list[int]
|
| 304 |
+
```
|
| 305 |
+
|
| 306 |
+
Determinism and global state: all randomness comes from `numpy.random.default_rng(seed + offset)`. The random
|
| 307 |
+
genome stream uses offset 67,001 and the variation stream 67,013; the NEUROWEAVE runs are seeded by the engine. The
|
| 308 |
+
module does not import torch and never touches the global NumPy or `random` state; the tests compare the NumPy,
|
| 309 |
+
`random` and (when it is loaded) torch RNG and thread state before and after a search and `run_experiment`. The
|
| 310 |
+
same arguments give the same receipt digest and the same archive export.
|
| 311 |
+
|
| 312 |
+
Each search switch is tested for an effect: DGM vs uniform selection, sigmoid sharpness 0 (only the child-count
|
| 313 |
+
term is left, checked against `1 / (1 + n_i)`), crossover off, single-operator mutation (one operator per child),
|
| 314 |
+
the random method and the spot-check frequency all change the archive. The shared evaluation cache, by design,
|
| 315 |
+
leaves the archive byte-identical.
|
| 316 |
+
|
| 317 |
+
## Connection to Sonapse
|
| 318 |
+
|
| 319 |
+
* The module uses the NEUROWEAVE lab read-only: `make_spec`, `NeuroWeaveEngine`, `ReadoutHead`,
|
| 320 |
+
`run_task_phase`, `make_stream`, `clone_engine`, `_estimated_cost`, and the receipt helpers via
|
| 321 |
+
`frontier.harness`. It reproduces the protocol of `_task_arm`.
|
| 322 |
+
* Its only engine attachment is `ActivityRecorder`, a read-only extension, and only on the module's own
|
| 323 |
+
evaluation engines.
|
| 324 |
+
* It changes no Sonapse or NEUROWEAVE default and is not a live observer. The frontier lab picks it up from
|
| 325 |
+
`EXPERIMENTS`.
|
| 326 |
+
* Each elite is a complete `NeuroWeaveSpecV1` (`Genome.to_spec`) with a sealed receipt. Possible follow-ups, not
|
| 327 |
+
implemented: seed other lab experiments with archive elites, or search over topology-metric descriptors such as
|
| 328 |
+
modularity.
|
| 329 |
+
|
| 330 |
+
## Not implemented
|
| 331 |
+
|
| 332 |
+
* **From MAP-Elites:**
|
| 333 |
+
* any of the alternative variants discussed in the paper (Sec. 8);
|
| 334 |
+
* the paper's global-performance metric, which is normalised by the best value found;
|
| 335 |
+
* adaptive or centroidal grids. The descriptor ranges are fixed in the config.
|
| 336 |
+
* **From DGM:**
|
| 337 |
+
* self-modification of code, foundation-model-proposed changes, staged benchmark evaluation, and `k` parents each
|
| 338 |
+
producing their own child.
|
| 339 |
+
* Only the parent-selection rule and the idea of admitting changes after empirical validation are reused.
|
| 340 |
+
* **Statistical strength of fitness.**
|
| 341 |
+
* Fitness is held-out accuracy on one short stream per held-out seed. It is coarse (multiples of 1 / 48 by
|
| 342 |
+
default), often near the majority-class rate, and noisy, so elites are partly selected on noise.
|
| 343 |
+
* Candidates are not re-trained with other seeds.
|
| 344 |
+
* The `best_test` re-evaluation on fresh streams is the only guard against this optimism.
|
| 345 |
+
* **Equal budget means equal candidate counts, not equal compute.** Candidates differ in estimated cost. The
|
| 346 |
+
receipt reports the estimated ops of the verified candidates per arm.
|
| 347 |
+
* **Spot-check schedule.** It is periodic and deterministic, so an adversarial evaluator that knew `k` could cheat
|
| 348 |
+
on the other candidates. The gate is designed for detecting faults, not for security.
|
| 349 |
+
|
| 350 |
+
## Verified references
|
| 351 |
+
|
| 352 |
+
Each reference was checked on 2026-11-20 against the listed pages and, where noted, the paper's text.
|
| 353 |
+
|
| 354 |
+
1. Jean-Baptiste Mouret, Jeff Clune. **Illuminating search spaces by mapping elites.** arXiv:1504.04909
|
| 355 |
+
[cs.AI], v1 submitted 20 April 2015 (arXiv comment "Early draft"; no later version is listed).
|
| 356 |
+
<https://arxiv.org/abs/1504.04909>. Checked in the PDF:
|
| 357 |
+
* the Fig. 2 pseudocode: G random solutions, then a random elite, random variation, and a store when the cell
|
| 358 |
+
is empty or `P(b′) < p′`;
|
| 359 |
+
* the Sec. 5 criteria (global performance, global reliability, precision / opt-in reliability, coverage);
|
| 360 |
+
* the Sec. 9.4.1–9.4.3 formulas, with the best per cell taken over all runs of all treatments and unfilled
|
| 361 |
+
cells excluded.
|
| 362 |
+
2. Jenny Zhang, Shengran Hu, Cong Lu, Robert Lange, Jeff Clune. **Darwin Gödel Machine: Open-Ended Evolution of
|
| 363 |
+
Self-Improving Agents.** arXiv:2505.22954 (title spelled "Godel" on arXiv), v1 29 May 2025, v3 12 March 2026.
|
| 364 |
+
ICLR 2026 poster: <https://iclr.cc/virtual/2026/poster/10007327> (OpenReview
|
| 365 |
+
<https://openreview.net/forum?id=pUpzQZTvGY>). <https://arxiv.org/abs/2505.22954>. Checked in the v3 HTML,
|
| 366 |
+
App. C.2 "Parent Selection":
|
| 367 |
+
* the eligible set `α_i < 1`;
|
| 368 |
+
* `s_i = 1/(1 + exp(−λ(α_i − α_0)))`;
|
| 369 |
+
* `h_i = 1/(1 + n_i)`, with `n_i` the children with codebase-editing functionality;
|
| 370 |
+
* `p_i = w_i / Σ w_j`, with λ = 10 and α_0 = 0.5;
|
| 371 |
+
* `k` parents sampled with replacement: k = 2 for SWE-bench and 4 for Polyglot.
|
| 372 |
+
3. Justin K. Pugh, L. B. Soros, Paul A. Szerlip, Kenneth O. Stanley. **Confronting the Challenge of Quality
|
| 373 |
+
Diversity.** GECCO '15, Madrid, 11–15 July 2015, pp. 967–974. doi:10.1145/2739480.2754664,
|
| 374 |
+
<https://dl.acm.org/doi/10.1145/2739480.2754664>. Checked in the PDF: the QD score is the "total fitness across
|
| 375 |
+
all filled grid bins".
|
| 376 |
+
4. Justin K. Pugh, Lisa B. Soros, Kenneth O. Stanley. **Quality Diversity: A New Frontier for Evolutionary
|
| 377 |
+
Computation.** *Frontiers in Robotics and AI* 3, published 12 July 2016. doi:10.3389/frobt.2016.00040,
|
| 378 |
+
<https://www.frontiersin.org/articles/10.3389/frobt.2016.00040/full>. Checked on the publisher page: the
|
| 379 |
+
QD-score sums the highest fitness found in each grid bin, credited to Pugh et al. (2015).
|
| 380 |
+
5. Patrik O. Hoyer. **Non-negative Matrix Factorization with Sparseness Constraints.** *Journal of Machine
|
| 381 |
+
Learning Research* 5, 1457–1469, November 2004. <https://www.jmlr.org/papers/v5/hoyer04a.html>. Checked in
|
| 382 |
+
the PDF: `sparseness(x) = (√n − Σ|x_i| / √(Σ x_i²)) / (√n − 1)`.
|
| 383 |
+
|
| 384 |
+
The sibling projects were read from read-only clones on 2026-11-20; no code from them was executed or copied:
|
| 385 |
+
|
| 386 |
+
* SONAPSE-ORIGIN: `sonapse_origin/evolution/map_elites.py`, `search_engine.py` and `nsga2.py`. These hold a 2-D
|
| 387 |
+
grid with clipped bins and strict-improvement replacement, uniform elite sampling, mutation and crossover, and
|
| 388 |
+
NSGA-II fronts.
|
| 389 |
+
* sonapse-evo: `src/sonapse_evo/evolution/operators.py`, `evolution/transaction_manager.py` and
|
| 390 |
+
`discovery/pareto_optimizer.py`. These hold operators with `can_apply` preconditions, mutation receipts, a
|
| 391 |
+
`FailureArchive` with reasons, parent-digest checks before commit with rollback, and constrained Pareto sorting.
|
| 392 |
+
|
| 393 |
+
## Measured results
|
| 394 |
+
|
| 395 |
+
All runs were measured on 2026-11-20 on Windows 11 on ARM64, with Python 3.12.10, NumPy 2.4 and one BLAS/OpenMP
|
| 396 |
+
thread (`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1`). The machine was shared with other jobs, so
|
| 397 |
+
wall-clock times are indicative. Receipts are deterministic: six quick runs gave the same digest, and re-running
|
| 398 |
+
the default and `budget=48` experiments later the same day reproduced their digests exactly.
|
| 399 |
+
|
| 400 |
+
Each row compares MAP-Elites with DGM selection (QD) against random search; numbers are QD vs random.
|
| 401 |
+
|
| 402 |
+
| Run | Seeds | Verdict (QD-score) | Key numbers (QD vs random) | Wall-clock |
|
| 403 |
+
|---|---|---|---|---|
|
| 404 |
+
| `run_experiment(quick=True)` | 0, 1, 2 | `worse` | QD-score 1.917 vs 2.625; difference −0.708, CI [−1.067, −0.350]. Coverage 0.229 vs 0.313. Best held-out accuracy 0.625 vs 0.625. Best elite on the test stream 0.417 vs 0.333, below the majority-class rate (0.75). No rejections; 2 spot checks per arm and seed, all reproduced | 3.3–4.0 s (6 runs) |
|
| 405 |
+
| `run_experiment()` | 0, 1, 2 | `worse` | QD-score 3.736 vs 4.924; −1.188, CI [−2.289, −0.086]. Coverage 0.417 vs 0.563 (difference CI [−0.383, 0.091]). Precision 0.983 vs 0.986. Best held-out accuracy 0.674 vs 0.660. Best elite on test streams 0.590 vs 0.604 (majority-class rate 0.542). No rejections; 4 spot checks per arm and seed, all reproduced | 43.9 s |
|
| 406 |
+
| `run_experiment(budget=48, initial_random=12)` | 0, 1, 2 | `no_detectable_difference` | QD-score 7.521 vs 7.806; −0.285, CI [−2.991, 2.422]. Coverage 0.833 vs 0.854. Best held-out accuracy 0.660 vs 0.667. Best elite on test streams 0.583 vs 0.646; −0.063, CI [−0.114, −0.011], so `worse` on that metric (majority-class rate 0.542). No rejections; 12 spot checks per arm and seed, all reproduced | 146.7 s |
|
| 407 |
+
|
| 408 |
+
The receipt digests are tied to the NEUROWEAVE code of that date:
|
| 409 |
+
|
| 410 |
+
* quick: `11618e7bd20da10be677b4b48c7d40523cc479e2f5172d3d0998c72e89259d53`;
|
| 411 |
+
* default: `c5c757eb4f4cca55832d39434ad5d09ab21048318084fdee7a4f23c544a10555`;
|
| 412 |
+
* `budget=48`: `8453ba874164518d5b99a426bb758443f95f5d4f30c5e3ba8bee05482bd9e414`.
|
| 413 |
+
|
| 414 |
+
Neither arm learned the quick task: no best elite beat the test stream's majority-class rate.
|
| 415 |
+
|
| 416 |
+
**Known-answer landscape** (from the tests, `LandscapeEvaluator`). The space has 6 mechanisms × 3 topologies ×
|
| 417 |
+
2 neuron counts × 2 sparsities (768 genomes) and a hidden target. The budget is 80 candidates; seeds 0–4; 4 × 4
|
| 418 |
+
grid.
|
| 419 |
+
|
| 420 |
+
| | MAP-Elites with DGM selection | Random search |
|
| 421 |
+
|---|---|---|
|
| 422 |
+
| Reached the unique optimum | 4 of 5 seeds | 0 of 5 |
|
| 423 |
+
| Mean best fitness | 0.978 | 0.844 |
|
| 424 |
+
| Mean QD-score | 4.756 (higher on all 5 seeds) | 4.422 |
|
| 425 |
+
| Filled cells | 6 on every seed | 6–7 |
|
| 426 |
+
| Mean fitness of verified candidates | 0.613 | 0.493 |
|
| 427 |
+
|
| 428 |
+
**Reading.** On the known landscape, MAP-Elites with DGM selection climbed within cells and reached a higher
|
| 429 |
+
QD-score while filling slightly fewer cells.
|
| 430 |
+
|
| 431 |
+
In the NEUROWEAVE space at 5 and 16 candidates per arm, it was the other way round. Held-out accuracy differed
|
| 432 |
+
little between configurations and stayed near the majority-class rate, so climbing had little to gain. Random
|
| 433 |
+
search filled more cells, and coverage decided the QD-score; precision was about the same for both arms.
|
| 434 |
+
|
| 435 |
+
At 48 candidates per arm, both arms filled most of the 16 cells and the QD-score difference was not detectable.
|
| 436 |
+
However, the best elites found by MAP-Elites scored lower on fresh test streams. One possible reason is stronger
|
| 437 |
+
selection on held-out noise; this was not tested.
|
| 438 |
+
|
| 439 |
+
These statements cover these settings only and say nothing about other tasks, sizes or budgets.
|
docs/frontier/modules/recursive_refiner.md
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `recursive_refiner`: recursive latent refinement
|
| 2 |
+
|
| 3 |
+
Module file: `synapse/frontier/recursive_refiner.py` · tests: `tests/test_frontier_models.py` ·
|
| 4 |
+
experiment id: `recursive_refiner` · kind: standalone model (no engine extension, no live observer) ·
|
| 5 |
+
evidence tier: `synthetic_abstraction`.
|
| 6 |
+
|
| 7 |
+
The module implements a tiny recursive model in the style of the **Tiny Recursive Model** (TRM;
|
| 8 |
+
Jolicoeur-Martineau, 2025), which simplifies the **Hierarchical Reasoning Model** (HRM; Wang et al., 2025).
|
| 9 |
+
One small network repeatedly refines a latent state `z` and an answer state `y`. It is trained with deep
|
| 10 |
+
supervision: one loss and one optimiser step per supervision step, with the state detached in between. A halting
|
| 11 |
+
head is trained to predict whether the current answer is already correct. The benchmark is 4×4 Sudoku completion
|
| 12 |
+
on grids the model never saw during training.
|
| 13 |
+
|
| 14 |
+
The module is *inspired by* these papers and does not reproduce them. The papers use 9×9 Sudoku-Extreme, mazes
|
| 15 |
+
and ARC-AGI, 5–27 M parameters, EMA weights, heavy data augmentation and GPUs. This module uses 4×4 Sudoku,
|
| 16 |
+
about 1.8–3.5 k parameters, no EMA, no augmentation and one CPU thread.
|
| 17 |
+
|
| 18 |
+
## What it computes
|
| 19 |
+
|
| 20 |
+
**Model (`TinyRecursiveModel`).** States have shape `tokens × latent_dim`; for Sudoku there is one token per cell
|
| 21 |
+
(16 tokens). Each supervision step embeds the question once, `e = E x`, where `x` is the per-cell one-hot code
|
| 22 |
+
over {blank, 1, 2, 3, 4}. The single shared network is a residual mixer block:
|
| 23 |
+
|
| 24 |
+
```
|
| 25 |
+
f(s) = N( t + W2 relu(W1 t + b1) + b2 ) # channel MLP, hidden width `hidden`
|
| 26 |
+
t = N( s + Mix(s) ) # token-mixing MLP across the 16 positions (width `token_hidden`)
|
| 27 |
+
N = layer norm without learned scale or shift (keeps recursed states bounded)
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
`Mix` is skipped when `tokens == 1` (a plain vector model). TRM uses an MLP over the sequence instead of
|
| 31 |
+
self-attention for Sudoku, with RMSNorm and SwiGLU in 2-layer blocks. Here one block with ReLU and an affine-free
|
| 32 |
+
layer norm is used, which is cheaper on CPU.
|
| 33 |
+
|
| 34 |
+
One **latent recursion**:
|
| 35 |
+
|
| 36 |
+
```
|
| 37 |
+
repeat n times: z <- f(z + y + e) # latent reasoning: sees the question
|
| 38 |
+
once: y <- f(y + z) # answer refinement: no question
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
The same `f` performs both updates. Whether `e` is in the sum is what tells the network which update it is doing,
|
| 42 |
+
as in TRM.
|
| 43 |
+
|
| 44 |
+
One **supervision step** (TRM's "deep recursion"):
|
| 45 |
+
|
| 46 |
+
1. `T - 1` latent recursions without gradient (`recursions = T`), then one latent recursion with gradient.
|
| 47 |
+
2. Read-outs from `y`:
|
| 48 |
+
* answer logits `O y`, 4 digits per cell;
|
| 49 |
+
* halting logit `q = w · mean_cells(y) + b`, with `P(halt) = sigmoid(q)`.
|
| 50 |
+
3. `(y, z)` are detached before the next supervision step.
|
| 51 |
+
|
| 52 |
+
The initial states `y_init` and `z_init` are fixed truncated-normal vectors (std 1, cut at ±2), shared by all
|
| 53 |
+
cells and stored as non-trainable buffers. The halting head starts at `w = 0, b = -5`, so early training rarely
|
| 54 |
+
halts. Both choices follow the TRM code. `net_calls` counts applications of `f`; one supervision step is
|
| 55 |
+
`T (n + 1)` applications.
|
| 56 |
+
|
| 57 |
+
**Training (`train_recursive`): deep supervision with ACT-style halting.**
|
| 58 |
+
|
| 59 |
+
* A batch of `batch_size` slots is carried across optimiser updates. Each update runs one supervision step for
|
| 60 |
+
every slot.
|
| 61 |
+
* Each update takes one AdamW step (β = (0.9, 0.95), weight decay 0.01, gradient-norm clip 1.0) on
|
| 62 |
+
`L = CE(logits, solution) + BCE(sigmoid(q), 1[all 16 cells correct])`. These are the two loss terms of TRM's
|
| 63 |
+
Figure 3 pseudocode.
|
| 64 |
+
* A slot halts when `q > 0` (once its minimum step count is reached) or after `N_sup = supervision_steps` steps.
|
| 65 |
+
It is then refilled with the next example of a deterministic shuffled stream, and its `(y, z)` are reset to the
|
| 66 |
+
initial states. There is no Q-continue head, as in TRM.
|
| 67 |
+
* Exploration: with probability `halt_exploration` (0.1) a new example gets a minimum of 2..`N_sup` steps. This
|
| 68 |
+
is HRM's `M_min` rule. Here it is drawn once per example, as the HRM paper describes it; the reference code
|
| 69 |
+
redraws it at every step.
|
| 70 |
+
|
| 71 |
+
**Evaluation (`evaluate_recursive`).** All `N_sup` supervision steps are run, as TRM does at test time, and the
|
| 72 |
+
headline metrics use the last step:
|
| 73 |
+
|
| 74 |
+
* `exact_solve`: fraction of puzzles with all 16 cells right;
|
| 75 |
+
* `cell_accuracy`: fraction of *blank* cells right;
|
| 76 |
+
* `per_step_exact_solve`: exact-solve after each supervision step;
|
| 77 |
+
* `adaptive_*`: the answer taken at the first step with `P(halt) > 0.5` (or the last step), with the mean number
|
| 78 |
+
of steps used;
|
| 79 |
+
* `halting_brier` and `halting_decision_accuracy`: calibration of `P(halt)` against per-step correctness, and
|
| 80 |
+
`halt_prob_range`.
|
| 81 |
+
|
| 82 |
+
## Benchmark (`run_experiment`, `EXPERIMENTS = {'recursive_refiner': run_experiment}`)
|
| 83 |
+
|
| 84 |
+
Per seed (default `seeds=(0, 1, 2)`):
|
| 85 |
+
|
| 86 |
+
1. **Grids.** `enumerate_sudoku4()` returns all 288 valid 4×4 grids, found by backtracking. The tests check the
|
| 87 |
+
count, validity, distinctness and closure under digit relabelling.
|
| 88 |
+
2. **Disjoint split by grid.** The grids are permuted by `default_rng(seed + 31001)` and split into 160 training,
|
| 89 |
+
32 validation and 96 held-out grids. The receipt records the overlap between splits, which is 0 for every seed.
|
| 90 |
+
3. **Puzzles (`make_puzzles`).** Pick a grid of the split and draw a target of 8–12 blanks. Blank cells in random
|
| 91 |
+
order, skipping any removal that would admit a second solution. The check is an exact count of the grids
|
| 92 |
+
consistent with the givens, using bitsets over the 288 grids. Every puzzle therefore has exactly one solution.
|
| 93 |
+
The default sizes are 4096 training, 512 validation and 1024 held-out puzzles; the first 512 training puzzles
|
| 94 |
+
are re-scored as "train".
|
| 95 |
+
4. **Encoding.** One-hot per cell over {blank, 1, 2, 3, 4} (80 inputs); the targets are the 16 digits.
|
| 96 |
+
|
| 97 |
+
**Arms.** All arms share the data, the example stream (`torch.Generator(seed + 31301)`) and the number of AdamW
|
| 98 |
+
updates.
|
| 99 |
+
|
| 100 |
+
| arm | model | training |
|
| 101 |
+
|---|---|---|
|
| 102 |
+
| `trm` | `TinyRecursiveModel` | deep supervision with halting (`train_recursive`) |
|
| 103 |
+
| `unrolled` | the same network and initial weights, run to the same inference depth (`N_sup · T · (n + 1)` applications) | one loss at the end, full backpropagation through the whole unroll (`train_unrolled`); no deep supervision |
|
| 104 |
+
| `shallow` | the same network and initial weights with one latent recursion (`n + 1` applications) | one loss, full backpropagation |
|
| 105 |
+
| `mlp` | `SinglePassMLP`: flat 2-hidden-layer ReLU MLP on the 80 inputs | cross-entropy, single pass |
|
| 106 |
+
|
| 107 |
+
The MLP width is chosen by `matched_mlp_hidden` so that its trainable parameters are closest to `trm`'s. All
|
| 108 |
+
budgets are computed **before training**. If any arm is more than `param_tolerance` (10 %) away from `trm`,
|
| 109 |
+
`run_experiment` raises `ValueError`.
|
| 110 |
+
|
| 111 |
+
**Verdict.** The best baseline is the one with the highest mean *validation* exact-solve; held-out grids play no
|
| 112 |
+
part in that choice. `verdict = harness.compare(trm, best baseline)` on held-out exact-solve per seed, a paired
|
| 113 |
+
95 % t interval over seeds. The receipt also compares `trm` with each baseline separately, and with the best
|
| 114 |
+
baseline on cell accuracy:
|
| 115 |
+
|
| 116 |
+
* `trm_vs_unrolled` isolates deep supervision and the one-step gradient at equal depth;
|
| 117 |
+
* `trm_vs_shallow` isolates recursion depth;
|
| 118 |
+
* `trm_vs_mlp` mixes recursion with per-cell weight sharing.
|
| 119 |
+
|
| 120 |
+
**Receipt fields.**
|
| 121 |
+
|
| 122 |
+
* `config`, including `quick` and every option;
|
| 123 |
+
* `data`: overlap between splits, mean blanks, uniqueness note;
|
| 124 |
+
* `parameter_budget`: per-arm counts, MLP width, relative gap, tolerance;
|
| 125 |
+
* `arms`: per-seed train / validation / held-out metrics, training logs and summaries;
|
| 126 |
+
* `best_baseline`, `comparisons`, `verdict`, `verdict_basis`;
|
| 127 |
+
* `estimated_cost`: inference MACs per puzzle, network applications per puzzle, backpropagated applications per
|
| 128 |
+
update, examples drawn by `trm`;
|
| 129 |
+
* `measured_wallclock_s`, which is kept out of the digest;
|
| 130 |
+
* `notes`.
|
| 131 |
+
|
| 132 |
+
| option | default | quick |
|
| 133 |
+
|---|---|---|
|
| 134 |
+
| grids train / val / held-out | 160 / 32 / 96 | same |
|
| 135 |
+
| puzzles train / val / held-out / train-eval | 4096 / 512 / 1024 / 512 | 1024 / 128 / 256 / 128 |
|
| 136 |
+
| blanks per puzzle | 8–12 | same |
|
| 137 |
+
| `latent_dim` / `hidden` / `token_hidden` | 24 / 48 / 24 | 16 / 32 / 16 |
|
| 138 |
+
| `n_latent_steps` (n) / `recursions` (T) / `supervision_steps` (N_sup) | 2 / 2 / 4 | 1 / 2 / 2 |
|
| 139 |
+
| applications of `f` per puzzle (trm, unrolled) | 24 | 8 |
|
| 140 |
+
| AdamW updates / batch / lr | 600 / 32 / 2e-3 | 100 / 64 / 4e-3 |
|
| 141 |
+
| trainable parameters trm / mlp (MLP width) | 3,453 / 3,384 (20) | 1,797 / 1,791 (11) |
|
| 142 |
+
|
| 143 |
+
## Public API
|
| 144 |
+
|
| 145 |
+
```python
|
| 146 |
+
MODULE_ID = 'recursive_refiner'
|
| 147 |
+
EXPERIMENTS = {'recursive_refiner': run_experiment}
|
| 148 |
+
run_experiment(*, quick: bool = False, seeds=(0, 1, 2), **overrides) -> dict # overrides: any DEFAULTS key
|
| 149 |
+
|
| 150 |
+
TinyRecursiveModel(input_dim, answer_dim, latent_dim, hidden, n_latent_steps, supervision_steps, *,
|
| 151 |
+
recursions=2, tokens=1, token_hidden=None, seed=0)
|
| 152 |
+
.net(s) / .embed(x) / .initial_state(batch) / .latent_recursion(e, y, z) / .read_out(y)
|
| 153 |
+
.supervision_step(e, y, z) -> (y_detached, z_detached, logits, q)
|
| 154 |
+
.forward(x, *, steps=None) -> {'logits', 'step_logits', 'halt_prob'}
|
| 155 |
+
.unrolled(x) -> (logits, q) # same depth, gradient through every recursion
|
| 156 |
+
.halt_probability(y), .calls_per_supervision_step(), .parameter_count(), .inference_macs(), .net_calls
|
| 157 |
+
SinglePassMLP(input_dim, answer_dim, hidden, *, depth=2, seed=0)
|
| 158 |
+
matched_mlp_hidden(target_params, input_dim, answer_dim, depth=2) -> int
|
| 159 |
+
|
| 160 |
+
enumerate_sudoku4() -> np.ndarray (288, 16) is_valid_sudoku4(grid) -> bool
|
| 161 |
+
is_consistent_puzzle(puzzle) -> bool solution_count(puzzle) -> int
|
| 162 |
+
make_puzzles(grids, count, *, rng, min_blanks, max_blanks, max_attempts=64) -> (puzzles, solutions)
|
| 163 |
+
encode_puzzles(puzzles) -> torch.Tensor (n, 80)
|
| 164 |
+
train_recursive / train_unrolled / train_single_pass(model, x, target, cfg, generator) -> dict
|
| 165 |
+
evaluate_recursive / evaluate_single_pass(model, x, target, puzzles) -> dict
|
| 166 |
+
ARMS, GRID_COUNT (288), CELLS, DIGITS, INPUT_DIM (80), ANSWER_DIM (64), UNITS, DEFAULTS, QUICK
|
| 167 |
+
```
|
| 168 |
+
|
| 169 |
+
Determinism and global state:
|
| 170 |
+
|
| 171 |
+
* all initialisation uses `torch.Generator(seed + offset)` and all data uses `numpy.random.default_rng(seed + offset)`;
|
| 172 |
+
* the global torch RNG is never used;
|
| 173 |
+
* `run_experiment` runs on one torch thread and restores the caller's thread count afterwards.
|
| 174 |
+
|
| 175 |
+
The tests check that the global RNG state and the thread count are unchanged after a run.
|
| 176 |
+
|
| 177 |
+
## Connection to Sonapse
|
| 178 |
+
|
| 179 |
+
This is a standalone lab model (contract rule 3). It does not attach to a NEUROWEAVE engine, has no live
|
| 180 |
+
observer, and changes no Sonapse default. The frontier lab registry picks it up from `EXPERIMENTS`.
|
| 181 |
+
|
| 182 |
+
A possible follow-up, not implemented: use `TinyRecursiveModel` as a refinement readout over NEUROWEAVE
|
| 183 |
+
features, where `tokens=1` gives the plain-vector form.
|
| 184 |
+
|
| 185 |
+
## Not implemented
|
| 186 |
+
|
| 187 |
+
* **From the TRM paper and code:**
|
| 188 |
+
* 2-layer SwiGLU / RMSNorm blocks, self-attention and rotary embeddings;
|
| 189 |
+
* EMA of the weights (0.999);
|
| 190 |
+
* the 1000-fold data augmentation;
|
| 191 |
+
* the puzzle-identifier embedding token (TRM's halting head reads that first position; here it reads the
|
| 192 |
+
mean over cells);
|
| 193 |
+
* the 0.5 weight on the halting loss (here 1, as in the paper's pseudocode);
|
| 194 |
+
* the stable-max cross-entropy option;
|
| 195 |
+
* TRM's sizes (T = 3, n = 6, N_sup = 16, hidden 512).
|
| 196 |
+
* **From the HRM paper:**
|
| 197 |
+
* two separate networks at two frequencies;
|
| 198 |
+
* the Q-continue head and its Q-learning target;
|
| 199 |
+
* the fixed-point / one-step-gradient justification. TRM's recursion is used instead.
|
| 200 |
+
* **Datasets:** 9×9 Sudoku-Extreme, Maze-Hard and ARC-AGI. 4×4 Sudoku is far easier, so the numbers here say
|
| 201 |
+
nothing about those benchmarks.
|
| 202 |
+
* **A compute-matched protocol.** All arms get equal optimiser updates. `unrolled` therefore backpropagates
|
| 203 |
+
through `N_sup` times more network applications per update than `trm`, while `trm` draws fewer distinct
|
| 204 |
+
examples per update (`trm_examples_drawn` in the receipt).
|
| 205 |
+
|
| 206 |
+
## Verified references
|
| 207 |
+
|
| 208 |
+
Each was checked on 2026-11-17 against the arXiv abstract page and the paper's HTML text. TRM was also checked
|
| 209 |
+
against the authors' code. On 2026-11-20 (review) the TRM arXiv listing was re-checked (single author, v1 of
|
| 210 |
+
6 October 2025 is still the only version) and the recursion, deep-supervision loop and halting code paths of
|
| 211 |
+
this module were re-read against the Figure 3 pseudocode below.
|
| 212 |
+
|
| 213 |
+
* Alexia Jolicoeur-Martineau. **Less is More: Recursive Reasoning with Tiny Networks.** arXiv:2510.04871
|
| 214 |
+
[cs.LG], v1 submitted 6 October 2025. <https://arxiv.org/abs/2510.04871>.
|
| 215 |
+
* **Checked in the paper:**
|
| 216 |
+
* Figure 3 pseudocode: `latent_recursion` (n × `z = net(x, y, z)`, then `y = net(y, z)`) and
|
| 217 |
+
`deep_recursion` (T − 1 recursions under `no_grad`, one with gradient, return detached `(y, z)`, output
|
| 218 |
+
head and Q head);
|
| 219 |
+
* the deep-supervision loop: cross-entropy plus binary cross-entropy of `q_hat` against
|
| 220 |
+
`(y_hat == y_true)`, an optimiser step every supervision step, and early stop when `q_hat > 0`;
|
| 221 |
+
* the text forms `z ← f(x + y + z)` and `y ← f(y + z)`;
|
| 222 |
+
* the same network for both updates, distinguished by the presence of `x`;
|
| 223 |
+
* T = 3, n = 6, N_sup = 16, a 2-layer network, EMA 0.999;
|
| 224 |
+
* an MLP over the sequence instead of self-attention on Sudoku;
|
| 225 |
+
* no continue loss, a single forward pass;
|
| 226 |
+
* Sudoku-Extreme with 1K training examples and 1000 augmentations each.
|
| 227 |
+
* **Checked in the code**, <https://github.com/SamsungSAILMontreal/TinyRecursiveModels>
|
| 228 |
+
(`models/recursive_reasoning/trm.py`):
|
| 229 |
+
* `H_init` / `L_init` truncated-normal buffers with std 1;
|
| 230 |
+
* `q_head` with weight 0 and bias −5, reading `z_H[:, 0]`;
|
| 231 |
+
* injection `z_L ← L(z_L, z_H + input)` and `z_H ← L(z_H, z_L)`;
|
| 232 |
+
* training halts on `q_halt > 0` (`no_ACT_continue`), with exploration minimum steps drawn from
|
| 233 |
+
[2, `halt_max_steps`] with probability `halt_exploration_prob`;
|
| 234 |
+
* evaluation runs to `halt_max_steps`;
|
| 235 |
+
* post-norm RMSNorm blocks with SwiGLU.
|
| 236 |
+
* Guan Wang, Jin Li, Yuhao Sun, Xing Chen, Changling Liu, Yue Wu, Meng Lu, Sen Song, Yasin Abbasi Yadkori.
|
| 237 |
+
**Hierarchical Reasoning Model.** arXiv:2506.21734 [cs.AI], v1 submitted 26 June 2025, later revised.
|
| 238 |
+
<https://arxiv.org/abs/2506.21734>. Checked in the paper:
|
| 239 |
+
* deep supervision over segments, with the state detached between segments and an optimiser step per segment;
|
| 240 |
+
* the one-step gradient approximation;
|
| 241 |
+
* ACT: a Q-head on the final high-level state with halt / continue values;
|
| 242 |
+
* halting when the segment count exceeds `M_max`, or when `Q_halt > Q_continue` and the count is at least
|
| 243 |
+
`M_min`, where `M_min` is uniform on {2, …, M_max} with probability ε and 1 otherwise;
|
| 244 |
+
* the halt target 1[ŷ = y];
|
| 245 |
+
* Sudoku-Extreme with 1000 training examples.
|
| 246 |
+
|
| 247 |
+
## Measured results
|
| 248 |
+
|
| 249 |
+
Measured on **2026-11-20** (`quick=True`, `seeds=(0, 1, 2)`, single CPU thread `OPENBLAS_NUM_THREADS=1`, digest `79ccc3bbb0d6f94a`, wall-clock `8.63 s`):
|
| 250 |
+
|
| 251 |
+
| Arm | Train exact-solve | Val exact-solve | Held-out cell acc | Held-out exact-solve | Held-out Δ vs arm (95 % CI) |
|
| 252 |
+
|---|---:|---:|---:|---:|---|
|
| 253 |
+
| `trm` (candidate) | 0.2630 | 0.2734 | 0.8394 | 0.3242 | — (per-step: `0.2240 → 0.3242`, halting Brier `0.2236`) |
|
| 254 |
+
| `unrolled` (best baseline) | 0.4089 | 0.4089 | 0.8829 | 0.4245 | `trm − unrolled`: −0.1003 (`[-0.1999, -0.0007]`, `worse`) |
|
| 255 |
+
| `shallow` | 0.3073 | 0.2943 | 0.8503 | 0.3112 | `trm − shallow`: +0.0130 (`[-0.0501, +0.0762]`, `no_detectable_difference`) |
|
| 256 |
+
| `mlp` | 0.0026 | 0.0000 | 0.3459 | 0.0000 | `trm − mlp`: +0.3242 (`[+0.2286, +0.4198]`, `improved`) |
|
| 257 |
+
|
| 258 |
+
* **Headline verdict (`trm_vs_best_baseline(unrolled)`):** `worse` on held-out exact-solve at the tiny quick-mode update budget, while clearly outperforming the flat `mlp` baseline (`improved`).
|
docs/frontier/modules/rigl_sparse.md
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `rigl_sparse`: dynamic sparse training (RigL)
|
| 2 |
+
|
| 3 |
+
Module file: `synapse/frontier/rigl.py` · tests: `tests/test_frontier_optim.py` ·
|
| 4 |
+
experiment id: `rigl_sparse` · kind: `tool` (a training-loop scheduler; no engine extension, no live observer) ·
|
| 5 |
+
evidence tier: `synthetic_abstraction`.
|
| 6 |
+
|
| 7 |
+
The module keeps the `nn.Linear` layers of a PyTorch model at a fixed number of active weights and, every
|
| 8 |
+
`delta_t` iterations until `t_end`, moves a cosine-decayed fraction of them: the smallest-magnitude active weights
|
| 9 |
+
are dropped and the same number of inactive weights with the largest gradient magnitude are grown, starting at
|
| 10 |
+
zero. It is *inspired by* **RigL** (Evci et al., ICML 2020) and by the `AuthenticRigL` class of the sibling
|
| 11 |
+
project `kai9987kai/sonapse-evo`. It does not reproduce the paper's ImageNet or CIFAR results, and it stores
|
| 12 |
+
weights densely with binary masks, so it saves no time or memory.
|
| 13 |
+
|
| 14 |
+
## What it computes
|
| 15 |
+
|
| 16 |
+
**Layer budgets.** For managed layers with weight shapes `(n_out, n_in)` and a target overall sparsity `S`:
|
| 17 |
+
|
| 18 |
+
* `'uniform'`: every layer has density `1 - S`.
|
| 19 |
+
* `'erk'` (Erdős–Rényi; for linear layers ERK and ER coincide): density `eps * (n_in + n_out) / (n_in * n_out)`,
|
| 20 |
+
with one scale `eps` chosen so the total number of active weights equals the uniform budget. A layer whose
|
| 21 |
+
density would exceed 1 is made dense and `eps` is recomputed for the others, as in the reference code.
|
| 22 |
+
|
| 23 |
+
A layer with `N` weights and density `d` keeps `a = N - floor((1 - d) N)` active weights (at least 1). The initial
|
| 24 |
+
masks are random (`numpy.random.default_rng(seed + offset)`), applied to the weights at construction, and every
|
| 25 |
+
inactive weight is exactly `0.0` from then on.
|
| 26 |
+
|
| 27 |
+
**Schedule.** Training iterations are counted `t = 1, 2, …`. Iteration `t` is a *connectivity update* when
|
| 28 |
+
|
| 29 |
+
```
|
| 30 |
+
t mod delta_t == 0 and t < t_end (RigL Algorithm 1)
|
| 31 |
+
f(t) = alpha / 2 * (1 + cos(pi * t / t_end)) (cosine update fraction of Evci et al.)
|
| 32 |
+
k = floor(f(t) * a) (per layer; a = active weights of the layer)
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
**Update (per sparse layer).**
|
| 36 |
+
|
| 37 |
+
1. *Drop* the `k` active weights with the smallest `|w|` (ties: lowest flat index).
|
| 38 |
+
2. *Grow* the `k` weights with the largest `|dL/dw|` among all weights that were not kept, i.e. the inactive ones
|
| 39 |
+
plus the ones just dropped (ties: lowest flat index). The gradient is the dense gradient of the current batch,
|
| 40 |
+
which autograd gives at every position because inactive weights are zeros of a dense tensor.
|
| 41 |
+
3. Newly activated weights are set to `0.0`, so the network output does not change. A weight that is dropped and
|
| 42 |
+
grown back in the same update keeps its value (the reference code's default, `reinit_when_same=False`).
|
| 43 |
+
4. Every per-element optimiser state tensor of the layer (SGD momentum, Adam moments) is zeroed at inactive and
|
| 44 |
+
newly activated positions.
|
| 45 |
+
5. No optimiser step is taken on an update iteration (Algorithm 1). On every other iteration the gradients of
|
| 46 |
+
inactive weights are zeroed before `optimizer.step()` and the masks are re-applied after it, so inactive
|
| 47 |
+
weights stay exactly zero even with weight decay or momentum.
|
| 48 |
+
|
| 49 |
+
The number of active weights per layer never changes. Biases stay dense.
|
| 50 |
+
|
| 51 |
+
## Public API
|
| 52 |
+
|
| 53 |
+
```python
|
| 54 |
+
MODULE_ID = 'rigl_sparse'
|
| 55 |
+
DISTRIBUTIONS = ('uniform', 'erk')
|
| 56 |
+
STATE_SCHEMA = 'RigLSchedulerStateV1'
|
| 57 |
+
ARMS = ('dense', 'static_sparse', 'rigl')
|
| 58 |
+
EXPERIMENTS = {'rigl_sparse': run_experiment}
|
| 59 |
+
|
| 60 |
+
cosine_drop_fraction(t, alpha, t_end) -> float
|
| 61 |
+
layer_densities(shapes, sparsity, distribution='erk') -> list[float]
|
| 62 |
+
layer_active_counts(shapes, sparsity, distribution='erk') -> list[int]
|
| 63 |
+
|
| 64 |
+
RigLScheduler(model, sparsity, delta_t=100, alpha=0.3, t_end=1000, distribution='erk', *,
|
| 65 |
+
layers=None, seed=0, dynamic=True, history=256)
|
| 66 |
+
.step(optimizer) -> bool # call once per iteration after loss.backward(); False = connectivity update
|
| 67 |
+
.update_connections(fraction, optimizer=None) -> dict
|
| 68 |
+
.apply_masks() .mask_gradients()
|
| 69 |
+
.is_update_step(t) -> bool .drop_fraction(t) -> float
|
| 70 |
+
.active_counts() -> list[int] .parameter_budget() -> dict .summary() -> dict
|
| 71 |
+
.masks (copies) .history (copies; at most `history` records)
|
| 72 |
+
.state_dict() -> dict .load_state_dict(state)
|
| 73 |
+
|
| 74 |
+
run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed receipt
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
`layers` selects which `nn.Linear` modules are managed (default: all, in `model.modules()` order; pass a subset to
|
| 78 |
+
keep, for example, the first layer dense). `dynamic=False` keeps the initial masks for the whole run (static sparse
|
| 79 |
+
training with identical masks). Inputs are validated before anything changes: `update_connections` refuses
|
| 80 |
+
missing, sparse or non-finite gradients without touching masks, weights or optimiser state, and
|
| 81 |
+
`load_state_dict` checks the schema, the configuration, the counters and every mask's dtype, shape and active
|
| 82 |
+
count before loading. The scheduler state holds the masks, counters and history, not the optimiser state.
|
| 83 |
+
|
| 84 |
+
## Benchmark (`run_experiment`)
|
| 85 |
+
|
| 86 |
+
* **Task (`sparse_teacher`).** Gaussian inputs (`n_inputs = 64`), of which only a seeded subset of
|
| 87 |
+
`n_informative = 8` drives the label: the label is the argmax of a fixed random tanh teacher on those inputs
|
| 88 |
+
(4 classes, logits centred on the training split). The other 56 inputs are distractors, so which connections
|
| 89 |
+
exist matters.
|
| 90 |
+
* **Model.** ReLU MLP `64-hidden-hidden-4` with PyTorch's default `nn.Linear` initialisation drawn from a private
|
| 91 |
+
`torch.Generator` (the global RNG is untouched).
|
| 92 |
+
* **Arms.** `dense`; `static_sparse` (the scheduler with `dynamic=False`); `rigl`. Per seed all three share the
|
| 93 |
+
initial weights, the minibatch sequence, `torch.optim.SGD(lr, momentum, weight_decay)` and the number of
|
| 94 |
+
training iterations; `static_sparse` and `rigl` also share the initial masks (checked in the receipt).
|
| 95 |
+
* **Verdict.** `harness.compare` (paired 95 % t interval over seeds) of held-out test accuracy, `rigl` minus
|
| 96 |
+
`static_sparse`: the two arms have the same parameter budget, so a win cannot come from capacity. `rigl` vs
|
| 97 |
+
`dense` and `static_sparse` vs `dense` are reported as context. If a sparse arm diverges, the verdict basis
|
| 98 |
+
becomes `training_diverged`.
|
| 99 |
+
* **Receipt.** `config` (every size and hyper-parameter, `t_end`), per-arm `per_seed` results (accuracies, final
|
| 100 |
+
loss, optimiser steps, mask digests, update trace, connections activated, the share of first-layer
|
| 101 |
+
connections that read an informative input), `budget` (active and dense parameters, per-layer densities, shared
|
| 102 |
+
masks, constant budget, zero inactive weights), `estimated_cost` (analytic FLOPs for ideal sparse kernels,
|
| 103 |
+
apart from `measured_wallclock_s`), `comparisons`, `verdict`, `verdict_basis` and `notes`.
|
| 104 |
+
|
| 105 |
+
| Setting | quick | default |
|
| 106 |
+
|---|---|---|
|
| 107 |
+
| `hidden`, train / val / test examples | 64, 1024 / 256 / 512 | 128, 4096 / 1024 / 2048 |
|
| 108 |
+
| iterations, batch, SGD lr / momentum / weight decay | 300, 64, 0.05 / 0.9 / 1e-4 | 2000, 64, 0.05 / 0.9 / 1e-4 |
|
| 109 |
+
| sparsity, distribution | 0.9, `erk` | 0.9, `erk` |
|
| 110 |
+
| `delta_t`, `alpha`, `t_end` | 25, 0.3, 225 (0.75 × iterations) | 50, 0.3, 1500 |
|
| 111 |
+
|
| 112 |
+
The paper uses `delta_t = 100`, `alpha = 0.3` and `T_end` at about 75 % of training; the shorter runs here use a
|
| 113 |
+
smaller `delta_t` so that several updates happen.
|
| 114 |
+
|
| 115 |
+
## Connection to Sonapse
|
| 116 |
+
|
| 117 |
+
A standalone lab tool (`EXPERIMENTS['rigl_sparse']`). Nothing in Sonapse or NEUROWEAVE calls it, and no default
|
| 118 |
+
training loop, graft schedule, API or checkpoint format changes. `sonapse-evo`'s `AuthenticRigL`
|
| 119 |
+
(`src/sonapse_evo/evaluation/rigl.py`, read in the local read-only clone) applies the same cosine drop/regrow idea
|
| 120 |
+
to a single recurrent edge vector and regrows weights at `±0.05` with a random sign; this module follows the
|
| 121 |
+
paper instead (per-layer masks, ERK budgets, zero-initialised growth, no optimiser step on update iterations).
|
| 122 |
+
|
| 123 |
+
## Not implemented, and differences from the paper
|
| 124 |
+
|
| 125 |
+
* **No sparse kernels.** Masks over dense tensors: no measured speed-up or memory saving is claimed.
|
| 126 |
+
`estimated_cost` gives analytic FLOPs for ideal sparse kernels.
|
| 127 |
+
* **`nn.Linear` only.** No convolutions, so ERK equals ER here.
|
| 128 |
+
* **Tie-breaking.** Ties go to the lowest flat index; the reference code adds small Gaussian noise
|
| 129 |
+
(std `1e-5`) to the drop scores.
|
| 130 |
+
* **Update condition.** Algorithm 1's `t mod delta_t == 0 and t < t_end`. The reference code's TensorFlow
|
| 131 |
+
scheduler also allows an update at `t = t_end` and uses a `begin_step`.
|
| 132 |
+
* **Optimiser state.** All per-element state at inactive and newly grown positions is zeroed (the reference
|
| 133 |
+
resets the momentum of new connections; inactive positions have zero gradient here anyway).
|
| 134 |
+
* **First layer under `'uniform'`.** The paper keeps the first layer dense for the uniform distribution; here
|
| 135 |
+
that is the caller's choice (`layers=`). The benchmark uses ERK and sparsifies every layer.
|
| 136 |
+
* **Not attempted.** SET (random growth) and SNFS (momentum growth), the ImageNet/ResNet-50, CIFAR-10 and
|
| 137 |
+
character-level experiments, and the paper's longer training schedules.
|
| 138 |
+
|
| 139 |
+
## Verified references
|
| 140 |
+
|
| 141 |
+
* Utku Evci, Trevor Gale, Jacob Menick, Pablo Samuel Castro, Erich Elsen. **Rigging the Lottery: Making All
|
| 142 |
+
Tickets Winners.** *Proceedings of the 37th International Conference on Machine Learning (ICML 2020)*, PMLR
|
| 143 |
+
vol. 119, pp. 2943–2952, July 2020. <https://proceedings.mlr.press/v119/evci20a.html> · arXiv:1911.11134,
|
| 144 |
+
<https://arxiv.org/abs/1911.11134>. Checked on 2026-11-20 against the PMLR page (title, authors, volume, pages,
|
| 145 |
+
date) and the arXiv text: Algorithm 1 (update condition, `k = f_decay(t) (1 - s) N`, drop by `ArgTopK(-|θ|)`,
|
| 146 |
+
grow by gradient magnitude among the non-kept connections, plain gradient step otherwise), the cosine
|
| 147 |
+
`f_decay(t; α, T_end) = α/2 (1 + cos(tπ / T_end))`, the defaults `ΔT = 100`, `α = 0.3`, `T_end` ≈ 75 % of
|
| 148 |
+
training, zero-initialised growth, the ER/ERK distributions, and the dense first layer under the uniform
|
| 149 |
+
distribution.
|
| 150 |
+
* Reference code: <https://github.com/google-research/rigl>, `rigl/sparse_optimizers_base.py`, read on
|
| 151 |
+
2026-11-20: `n_prune` is a truncating cast of `n_ones * drop_fraction`; kept connections get the lowest grow
|
| 152 |
+
score; `reinit_when_same=False` by default, with new connections defined as grown and previously inactive;
|
| 153 |
+
`grow_init='zeros'`; momentum of new connections reset to zero; cosine decay over `end_step - begin_step`.
|
| 154 |
+
* Portfolio provenance: `kai9987kai/sonapse-evo`, `src/sonapse_evo/evaluation/rigl.py` (`AuthenticRigL`).
|
| 155 |
+
|
| 156 |
+
## Measured results
|
| 157 |
+
|
| 158 |
+
Measured on **2026-11-20**, Windows 11 on ARM64, Python 3.12.10, torch 2.11 CPU, NumPy 2.4,
|
| 159 |
+
`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1` (the experiment also runs torch on one thread). The
|
| 160 |
+
machine was shared with other jobs, so wall-clock is indicative only. Receipts are deterministic: two calls in
|
| 161 |
+
one process gave the same digest, and the quick digest was identical in two separate processes run about twelve
|
| 162 |
+
hours apart that day.
|
| 163 |
+
|
| 164 |
+
**Quick** (`run_experiment(quick=True)`, seeds 0, 1, 2; digest `906545bf0ed9d08c`; 6.7–7.4 s):
|
| 165 |
+
|
| 166 |
+
| Arm | Parameters (active weights + biases) | Train acc | Held-out test acc | First-layer informative share (chance 0.125) |
|
| 167 |
+
|---|---:|---:|---:|---:|
|
| 168 |
+
| `dense` | 8580 | 0.9997 | 0.6986 | 0.125 |
|
| 169 |
+
| `static_sparse` | 980 | 0.6849 | 0.6510 | 0.117 (unchanged) |
|
| 170 |
+
| `rigl` | 980 | 0.8128 | 0.7357 | 0.117 → 0.186 |
|
| 171 |
+
|
| 172 |
+
* Realised density 0.100 (848 of 8448 weights); ERK gives the per-layer densities 0.082, 0.082 and 0.695.
|
| 173 |
+
RigL made 8 connectivity updates (t = 25 … 200) and 292 optimiser steps per run; it activated 710–780
|
| 174 |
+
connections per run, and its first-layer share of informative inputs rose on every seed
|
| 175 |
+
(0.099 → 0.158, 0.134 → 0.194, 0.119 → 0.206).
|
| 176 |
+
* `rigl − static_sparse`: +0.0846, 95 % CI [−0.0126, +0.1818] → **`no_detectable_difference`** (verdict).
|
| 177 |
+
`rigl − dense`: +0.0371, CI [−0.0282, +0.1024]; `static_sparse − dense`: −0.0475, CI [−0.1806, +0.0856].
|
| 178 |
+
* Quick mode is a pipeline check with three seeds; its interval is wide.
|
| 179 |
+
|
| 180 |
+
**Default** (`run_experiment()`, seeds 0, 1, 2; digest `555ce009ccb76e7b`; 51.6 s; hidden 128, 2000 iterations,
|
| 181 |
+
`delta_t = 50`, `t_end = 1500`):
|
| 182 |
+
|
| 183 |
+
| Arm | Parameters (active weights + biases) | Train acc | Held-out test acc (per seed) | Mean | First-layer informative share |
|
| 184 |
+
|---|---:|---:|---|---:|---:|
|
| 185 |
+
| `dense` | 25348 | 0.9928 | 0.714, 0.767, 0.766 | 0.7492 | 0.125 |
|
| 186 |
+
| `static_sparse` | 2772 | 0.8805 | 0.758, 0.813, 0.818 | 0.7961 | 0.110, 0.149, 0.142 (unchanged) |
|
| 187 |
+
| `rigl` | 2772 | 0.9107 | 0.809, 0.795, 0.824 | 0.8091 | 0.110 → 0.165, 0.149 → 0.207, 0.142 → 0.182 |
|
| 188 |
+
|
| 189 |
+
* Realised density 0.100 (2512 of 25088 weights); ERK gives 0.105, 0.070 and 1.0 (the 128 × 4 output layer is
|
| 190 |
+
dense). RigL made 29 connectivity updates (t = 50 … 1450) and 1971 optimiser steps per run and activated
|
| 191 |
+
6203–6636 connections per run.
|
| 192 |
+
* `rigl − static_sparse`: +0.0130, 95 % CI [−0.0733, +0.0993] → **`no_detectable_difference`** (verdict).
|
| 193 |
+
`rigl − dense`: +0.0599, CI [−0.0227, +0.1425]; `static_sparse − dense`: +0.0469, CI [+0.0361, +0.0577]. On this
|
| 194 |
+
distractor-heavy task the dense network fits the training set almost perfectly and generalises worse than
|
| 195 |
+
both sparse arms. Static random masks alone already beat it at this size, so that gap does not depend on mask
|
| 196 |
+
updates, and the mask updates add no detectable accuracy over the static masks.
|
| 197 |
+
|
| 198 |
+
Unit tests with known answers (`tests/test_frontier_optim.py`): the cosine fraction at fixed points; the ERK
|
| 199 |
+
ratios and budget; a hand-worked drop/grow example (including a tie, a regrown-same weight that keeps its value,
|
| 200 |
+
zero-initialised growth and optimiser-state zeroing); constant budgets, exactly-zero inactive weights and the
|
| 201 |
+
update trace over a training run; static masks never moving; growth moving first-layer connections toward the
|
| 202 |
+
inputs that carry the signal on a planted regression (measured share 0.107 → 0.369, full-data MSE 0.0016 vs
|
| 203 |
+
0.0039 for static masks); refusal of bad gradients without any change; and state round-trips that continue
|
| 204 |
+
identically.
|
docs/frontier/modules/sparse_dictionary.md
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `sparse_dictionary`: sparse dictionary of brain activity
|
| 2 |
+
|
| 3 |
+
Module file: `synapse/frontier/sparse_dictionary.py` · tests: `tests/test_frontier_sae.py` ·
|
| 4 |
+
experiment id: `sparse_dictionary` · live observer: `SparseDictionaryObserver` ·
|
| 5 |
+
evidence tier: `synthetic_abstraction`.
|
| 6 |
+
|
| 7 |
+
The module learns an online **TopK sparse autoencoder** (a sparse dictionary) of unit activity. It also runs a
|
| 8 |
+
lab experiment that asks whether the dictionary features that best predict a task target matter more to a
|
| 9 |
+
frozen readout than random features do. The dictionary is *inspired by* the TopK autoencoders of Gao et al.
|
| 10 |
+
(2024). It does not reproduce that paper's setting or results: the paper trains on language-model activations
|
| 11 |
+
with millions of latents on GPUs, while this module uses float64 NumPy with tens of units and latents on one
|
| 12 |
+
CPU thread. Dictionary features are directions in a toy model's activity space. They are not cell types or
|
| 13 |
+
biological circuits.
|
| 14 |
+
|
| 15 |
+
## What it computes
|
| 16 |
+
|
| 17 |
+
**Autoencoder (`TopKSAE`).** For an input `x` (one activity vector, `d` units) and `n` latents:
|
| 18 |
+
|
| 19 |
+
```
|
| 20 |
+
z = ReLU( TopK_k( W_enc (x - b_pre) + b_enc ) ) # keep the k largest pre-activations, zero the rest
|
| 21 |
+
x_hat = W_dec z + b_pre # ||W_dec[:, j]||_2 = 1 for every latent j
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
* **TopK.** The k largest pre-activations of each row are kept and the rest are set to zero. Ties go to the
|
| 25 |
+
lower index. A ReLU on the kept values makes `L0 <= k`, with equality whenever the top k are positive.
|
| 26 |
+
`b_enc` is optional (`encoder_bias=True` by default): the paper's main equation leaves it out, its Appendix C.3
|
| 27 |
+
reports that it does not change the converged MSE, and the authors' reference code keeps it.
|
| 28 |
+
* **Initialisation.**
|
| 29 |
+
* Decoder columns are random unit vectors.
|
| 30 |
+
* The encoder is the decoder's transpose. The two are tied only at initialisation.
|
| 31 |
+
* `b_pre` is set to the geometric median of a data sample (Weiszfeld iterations).
|
| 32 |
+
* **Main loss.** `L = s * mean((x - x_hat)^2)`. The scale `s = 1 / Var(x)` is computed once, on the
|
| 33 |
+
initialisation sample.
|
| 34 |
+
* **Dead latents and AuxK.**
|
| 35 |
+
* A latent is *dead* once it has not fired (`z_j > 1e-3`) for `dead_after` training samples.
|
| 36 |
+
* The firing statistics are updated with the current batch before the dead mask is read.
|
| 37 |
+
* `e = x - x_hat` is the main residual, treated as a constant. `z_aux` keeps the top-`k_aux` dead latents by
|
| 38 |
+
pre-activation, with ReLU applied, and `e_hat = W_dec z_aux`.
|
| 39 |
+
* The auxiliary loss is `L_aux = mean_i ||e_i - e_hat_i||^2 / ||e_i||^2`. The paper (App. A.6) says the
|
| 40 |
+
AuxK normalisation is computed "per token" because the error scale changes during training, and
|
| 41 |
+
per-sample division by `||e_i||^2` is this module's reading of that. The authors' reference code does it
|
| 42 |
+
differently: its `normalized_mse` divides the batch MSE of the AuxK reconstruction by the MSE of
|
| 43 |
+
predicting the batch-mean residual (a per-batch, mean-centred normalisation; re-read on 2026-11-20 in
|
| 44 |
+
`sparse_autoencoder/kernels.py` and `train.py`). Both are scale-free; they are not numerically identical.
|
| 45 |
+
* The total loss is `L + alpha * L_aux`, with `alpha = 1/32` and `k_aux = d/2` by default. A non-finite AuxK
|
| 46 |
+
term is dropped.
|
| 47 |
+
* **Optimiser.**
|
| 48 |
+
* Adam with `beta = (0.9, 0.999)`, `eps = 6.25e-10` and a constant learning rate. Plain SGD is also available.
|
| 49 |
+
* The gradient component parallel to each decoder column is projected out before the step. The decoder
|
| 50 |
+
columns are renormalised to unit norm after every step.
|
| 51 |
+
* **Additions for bounded online use.** These are not from the paper: global gradient-norm clipping (default
|
| 52 |
+
1.0), parameter clipping (`max_param`), counter caps, and input validation (finite values, `|x| <= 1e6`).
|
| 53 |
+
* **Metrics** (`evaluate`):
|
| 54 |
+
* Fraction of variance unexplained, `FVU = sum ||x - x_hat||^2 / sum ||x - mean(x)||^2`. This is the paper's
|
| 55 |
+
"normalized MSE".
|
| 56 |
+
* MSE and mean `L0`.
|
| 57 |
+
* The fraction of features that never fired.
|
| 58 |
+
* Per-feature firing rate, and a usage histogram over the bins `never, (0,1e-3], (1e-3,1e-2], (1e-2,1e-1], (1e-1,1]`.
|
| 59 |
+
* The training dead fraction.
|
| 60 |
+
|
| 61 |
+
Training is fully deterministic. Initialisation uses `default_rng(seed + offset)`, and each epoch's shuffle uses
|
| 62 |
+
a generator keyed by `(seed + offset, epoch)`. The object holds no generator state, so `export_state` /
|
| 63 |
+
`import_state` round-trip exactly and `fit(2); fit(1)` equals `fit(3)`. `import_state` validates everything
|
| 64 |
+
before it changes anything: schema, configuration, shapes, finiteness, unit-norm decoder, integer counters and
|
| 65 |
+
non-negative Adam second moments.
|
| 66 |
+
|
| 67 |
+
**Live observer (`SparseDictionaryObserver(n_units, *, seed=7, history=256, features=64, k=8, ...)`).**
|
| 68 |
+
`observe(x)` follows these steps:
|
| 69 |
+
|
| 70 |
+
1. It copies the activity vector into a fixed ring buffer of `history` rows. The caller's array is never aliased
|
| 71 |
+
or written.
|
| 72 |
+
2. Once `min(history, 32)` rows exist, it initialises `b_pre` from their geometric median.
|
| 73 |
+
3. Every `train_every` observations it takes one optimiser step on the new vector plus `batch_size - 1` replayed
|
| 74 |
+
buffer rows. The replay positions come from a generator keyed by `(seed + offset, observation count)`.
|
| 75 |
+
4. Its statistics are prequential: they are measured on each new vector before the update that uses it.
|
| 76 |
+
* `fvu_ema` is the exponential moving average (EMA) of the per-element squared error, divided by the EMA
|
| 77 |
+
variance of the units.
|
| 78 |
+
* `l0_ema` is the EMA of the number of active features.
|
| 79 |
+
* A per-feature usage EMA feeds the usage figures in the summary.
|
| 80 |
+
5. The default `dead_after` is `batch_size * history` samples, about one buffer's worth of observations.
|
| 81 |
+
|
| 82 |
+
`summary()` is JSON-safe, about 3 KB, and contains no wall-clock. It returns:
|
| 83 |
+
|
| 84 |
+
* `fvu_ema`, `mse_ema`, `l0_ema` and `dead_fraction`;
|
| 85 |
+
* `steps`, the optimiser updates;
|
| 86 |
+
* `observed` and `history_fill`;
|
| 87 |
+
* `top_features`, up to 8 features by usage EMA, each with its 5 units of largest absolute decoder weight;
|
| 88 |
+
* `usage_histogram`;
|
| 89 |
+
* `decoder_norm_max_error`;
|
| 90 |
+
* `evidence_tier`.
|
| 91 |
+
|
| 92 |
+
`export_state` / `import_state` validate fully and continue bit-identically. `reset()` returns the observer to
|
| 93 |
+
its constructed state. `from_spec(n_units, FrontierSpecV1)` maps `seed`, `history`, `sae_features` and `sae_k`
|
| 94 |
+
to the observer's arguments.
|
| 95 |
+
|
| 96 |
+
## Lab experiment (`run_experiment`, `EXPERIMENTS = {'sparse_dictionary': run_experiment}`)
|
| 97 |
+
|
| 98 |
+
Per training seed (default `seeds=(0, 1, 2)`):
|
| 99 |
+
|
| 100 |
+
1. **Train.** A NEUROWEAVE engine (`make_spec`, default `delayed_recall`, 48 neurons, `clustered`, no extra
|
| 101 |
+
mechanisms) and the lab `ReadoutHead` are trained prequentially on `make_stream(seed, steps)` with
|
| 102 |
+
`run_task_phase(..., learn=True)`.
|
| 103 |
+
2. **Record (training data only).** A frozen clone replays the training stream and records the first `n0` unit
|
| 104 |
+
outputs and the head's features. With `readout='refit'` (default), the head is refit on those features by
|
| 105 |
+
L2-regularised logistic regression (damped Newton) to give a competent frozen probe. `readout='online'`
|
| 106 |
+
keeps the online head. Held-out streams are never used for fitting.
|
| 107 |
+
3. **Dictionary.** A `TopKSAE` is fit to the recorded outputs (default 64 features, `k=8`, `dead_after` = one
|
| 108 |
+
pass over the training stream).
|
| 109 |
+
4. **Selection (training data only).** Only "alive" features are eligible: those that fired on at least
|
| 110 |
+
`min_fire_rate` of the rows. The `n_ablate` alive features with the largest `|Pearson r|` between activation
|
| 111 |
+
and the training target are *targeted*. `random_draws` uniform draws of the same number of alive features
|
| 112 |
+
form the random arm. A draw may overlap the targeted set, and the receipt reports the overlap.
|
| 113 |
+
5. **Causal ablation (held-out, frozen clones).** For every held-out stream, three arms run on fresh frozen
|
| 114 |
+
clones of the trained engine: **none**, **targeted** and **random**. After every engine step the chosen
|
| 115 |
+
features' decoder contributions `sum_j z_j W_dec[:, j]` are subtracted from the clone's
|
| 116 |
+
`engine.brain.cells.output` (clipped to the cells' `[-1, 1]` range) before the readout reads it. This is the
|
| 117 |
+
place where `run_task_phase`'s `silence` zeroes units, so the change also reaches the next step's recurrent
|
| 118 |
+
input. With no features, this phase reproduces `run_task_phase(..., learn=False)` number for number (tested).
|
| 119 |
+
The original engine is never stepped, and its state digest is checked before and after.
|
| 120 |
+
6. **Verdict.** The verdict uses `harness.compare` (paired 95 % t interval over seeds) on held-out log-loss of
|
| 121 |
+
targeted vs random ablation, and the receipt also reports Cohen's d_z.
|
| 122 |
+
**`improved` here means only that the targeted features matter more to the frozen readout than random
|
| 123 |
+
ones**: ablating them raised held-out log-loss more, and the interval excludes zero. `worse` means they
|
| 124 |
+
matter less. It does not mean that any model got better. The receipt also carries these supporting
|
| 125 |
+
comparisons:
|
| 126 |
+
* targeted vs random accuracy;
|
| 127 |
+
* targeted vs none log-loss;
|
| 128 |
+
* random vs none log-loss.
|
| 129 |
+
|
| 130 |
+
The receipt also reports:
|
| 131 |
+
|
| 132 |
+
* dictionary train and held-out FVU, L0, dead and never-fired fractions, and the usage histogram;
|
| 133 |
+
* the selected features with their correlation and fire counts;
|
| 134 |
+
* the energy that the targeted and random sets carry on the training data, and the per-step norm actually
|
| 135 |
+
removed;
|
| 136 |
+
* budgets, estimated operation counts and measured wall-clock.
|
| 137 |
+
|
| 138 |
+
Ablation can remove different amounts of activity in the two arms. Before reading a difference as
|
| 139 |
+
feature-specific, compare `selection.targeted_train_energy`, `selection.random_train_energy` and
|
| 140 |
+
`heldout.*.removed_norm`.
|
| 141 |
+
|
| 142 |
+
## Connection to Sonapse
|
| 143 |
+
|
| 144 |
+
* **Live (read-only).** `sparse_dictionary` is in `spec.OBSERVER_MODULE_IDS`. A runtime hook that receives
|
| 145 |
+
`FrontierSpecV1(enabled=True, modules=('sparse_dictionary', ...))` builds the observer with
|
| 146 |
+
`SparseDictionaryObserver.from_spec(n_units, spec)` and feeds it copies of the observed unit activity. The
|
| 147 |
+
observer never writes into the brain, graft bus, actor or any shared RNG. Wiring that hook into the Sonapse
|
| 148 |
+
runtime is outside this module.
|
| 149 |
+
* **Lab.** `EXPERIMENTS['sparse_dictionary']` is the frontier-lab entry. It uses the NEUROWEAVE lab helpers
|
| 150 |
+
(`make_spec`, `ReadoutHead`, `run_task_phase`, `clone_engine`) and `synapse.frontier.harness` (`base_receipt`,
|
| 151 |
+
`compare`, `seal`).
|
| 152 |
+
|
| 153 |
+
## Not implemented
|
| 154 |
+
|
| 155 |
+
* **From the paper.**
|
| 156 |
+
* Weight EMA (paper A.5).
|
| 157 |
+
* Encoder-magnitude matching at initialisation. The paper reports that it has no effect or a weak negative
|
| 158 |
+
effect.
|
| 159 |
+
* Rounding `k_aux` to a power of two.
|
| 160 |
+
* Multi-TopK.
|
| 161 |
+
* Sharded or fused kernels.
|
| 162 |
+
* Scaling laws.
|
| 163 |
+
* The paper's feature-quality metrics: probe recovery, explainability and downstream-effect sparsity.
|
| 164 |
+
* **In this module.**
|
| 165 |
+
* Energy-matched random controls.
|
| 166 |
+
* Any claim about biological interpretation.
|
| 167 |
+
|
| 168 |
+
## Verified references
|
| 169 |
+
|
| 170 |
+
* Leo Gao, Tom Dupré la Tour, Henk Tillman, Gabriel Goh, Rajan Troll, Alec Radford, Ilya Sutskever, Jan Leike,
|
| 171 |
+
Jeffrey Wu. **Scaling and evaluating sparse autoencoders.** arXiv:2406.04093 (submitted 6 June 2024);
|
| 172 |
+
International Conference on Learning Representations (ICLR) 2025. <https://arxiv.org/abs/2406.04093> ·
|
| 173 |
+
<https://proceedings.iclr.cc/paper_files/paper/2025/hash/42ef3308c230942d223c411adf182c88-Abstract-Conference.html>.
|
| 174 |
+
The following were checked against the paper text on 2026-11-17:
|
| 175 |
+
* TopK, eq. 2 and footnote 5 (ReLU in code);
|
| 176 |
+
* tied initialisation, Sec. 2.4 and A.1;
|
| 177 |
+
* geometric-median `b_pre` and the unit-norm decoder after each step, A.1;
|
| 178 |
+
* AuxK with "typically 1/32", zeroed when NaN, A.2;
|
| 179 |
+
* Adam settings and the parallel-gradient projection, A.3;
|
| 180 |
+
* normalisation, A.6;
|
| 181 |
+
* "power of two close to d_model/2", B.1;
|
| 182 |
+
* `b_enc`, C.3;
|
| 183 |
+
* normalized MSE, Sec. 2.1.
|
| 184 |
+
|
| 185 |
+
The firing threshold `1e-3` and the `latent_bias` follow the authors' reference code,
|
| 186 |
+
<https://github.com/openai/sparse_autoencoder>, read the same day.
|
| 187 |
+
* **Auxiliary dead-latent loss lineage.** Adam Jermyn and Adly Templeton. **Ghost Grads: An improvement on
|
| 188 |
+
resampling.** In *Circuits Updates – January 2024*, Transformer Circuits Thread, January 2024.
|
| 189 |
+
<https://transformer-circuits.pub/2024/jan-update/index.html#dict-learning-resampling>. Gao et al. describe
|
| 190 |
+
AuxK as similar to ghost grads. This module implements AuxK, not ghost grads.
|
| 191 |
+
* **TopK activation origin.** Alireza Makhzani and Brendan Frey. **k-Sparse Autoencoders.** arXiv:1312.5663
|
| 192 |
+
(December 2013, revised March 2014); listed by DBLP under ICLR 2014. <https://arxiv.org/abs/1312.5663>.
|
| 193 |
+
|
| 194 |
+
## Measured results
|
| 195 |
+
|
| 196 |
+
All numbers were measured on 2026-11-17 on Windows 11 ARM64 (Qualcomm ARMv8 CPU), Python 3.12.10, NumPy 2.4.3, with
|
| 197 |
+
`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1`. Other agents shared the CPU, so wall-clock is
|
| 198 |
+
indicative only.
|
| 199 |
+
|
| 200 |
+
**Quick mode** (`run_experiment(quick=True)`): seeds `(0, 1, 2)`, held-out seed `(100,)`, `delayed_recall`, 24
|
| 201 |
+
neurons, `clustered`, no mechanisms, 120 training / 60 held-out steps, 32 features, `k=4`, `n_ablate=3`,
|
| 202 |
+
`random_draws=2`, 40 dictionary epochs (batch 16, lr 3e-3), refit readout (L2 1e-2).
|
| 203 |
+
|
| 204 |
+
| | value |
|
| 205 |
+
|---|---|
|
| 206 |
+
| verdict | **no_detectable_difference** |
|
| 207 |
+
| targeted − random held-out log-loss | +0.0139, 95 % CI [−0.0579, 0.0857], d_z 0.48 |
|
| 208 |
+
| targeted − none held-out log-loss | +0.0236, 95 % CI [−0.0367, 0.0839] |
|
| 209 |
+
| random − none held-out log-loss | +0.0097, 95 % CI [−0.0238, 0.0433] |
|
| 210 |
+
| held-out log-loss (none / targeted / random) | 0.638 / 0.661 / 0.647; constant predictor 0.691 |
|
| 211 |
+
| held-out accuracy (none / targeted / random) | 0.628 / 0.567 / 0.625; chance 0.533 |
|
| 212 |
+
| dictionary FVU, train / held-out (per seed) | 0.047 / 0.126, 0.032 / 0.067, 0.032 / 0.183 |
|
| 213 |
+
| dead fraction at end of training (per seed) | 0.34, 0.31, 0.38 |
|
| 214 |
+
| original engines unchanged | true |
|
| 215 |
+
| digest (prefix) | `0562be1283cf59b4` (identical across two processes) |
|
| 216 |
+
| measured wall-clock | 2.70 s; 6.39 s in an earlier run under heavier CPU load |
|
| 217 |
+
|
| 218 |
+
**Default size** (`run_experiment()`): seeds `(0, 1, 2)`, held-out seeds `(100, 101)`, 48 neurons, 300 / 150
|
| 219 |
+
steps, 64 features, `k=8`, `n_ablate=4`, `random_draws=4`, 60 epochs (batch 32).
|
| 220 |
+
|
| 221 |
+
| | value |
|
| 222 |
+
|---|---|
|
| 223 |
+
| verdict | **no_detectable_difference** |
|
| 224 |
+
| targeted − random held-out log-loss | +0.0053, 95 % CI [−0.0373, 0.0478] |
|
| 225 |
+
| targeted − none held-out log-loss | +0.0350, 95 % CI [0.0085, 0.0616] (interval excludes zero) |
|
| 226 |
+
| random − none held-out log-loss | +0.0298, 95 % CI [−0.0367, 0.0962] |
|
| 227 |
+
| readout skill over the constant predictor (held-out, none arm) | 0.127 nats |
|
| 228 |
+
| dictionary FVU, train (per seed) | 0.013, 0.016, 0.014 |
|
| 229 |
+
| digest (prefix) | `93a7ef790ae2b8a9` |
|
| 230 |
+
| measured wall-clock | 28.9 s under concurrent load |
|
| 231 |
+
|
| 232 |
+
**Observer cost** at the default size: 256 units, 64 features, `k=8`, batch 8, train every observation.
|
| 233 |
+
|
| 234 |
+
* About 1.4 ms per `observe` and 0.6 ms per `summary()`.
|
| 235 |
+
* `summary()` JSON is 2.9 KB.
|
| 236 |
+
* `export_state()` JSON is 3.65 MB. That covers the ring buffer, parameters and Adam moments, which an exact
|
| 237 |
+
continuation needs.
|
| 238 |
+
* Measured over 500 observations on random dense activity. FVU EMA is 0.91 there, because that data has no
|
| 239 |
+
sparse structure.
|
| 240 |
+
|
| 241 |
+
Reading: in these small engines, removing the dictionary features most correlated with the delayed-recall target
|
| 242 |
+
does raise held-out log-loss at default size. The paired interval does not show that it raises log-loss more
|
| 243 |
+
than removing the same number of random alive features. The features selected by correlation are only weakly
|
| 244 |
+
predictive (|r| ≈ 0.14–0.26), and the readout has little skill to lose (0.05–0.13 nats over a constant).
|
| 245 |
+
|
| 246 |
+
Unit-level checks in `tests/test_frontier_sae.py` (21 tests, about 7 s single-threaded):
|
| 247 |
+
|
| 248 |
+
* TopK matches a brute-force sort exactly.
|
| 249 |
+
* Gradients, including AuxK, match central finite differences to within 1e-6.
|
| 250 |
+
* A planted dictionary is recovered. With 16 unit-norm atoms in 12 dimensions, 2 active per sample, 800 samples
|
| 251 |
+
and 30 epochs, FVU is below 0.1 and at least 14 of 16 atoms have a decoder column with cosine above 0.9.
|
| 252 |
+
* Decoder norms stay within 1e-12 of 1.
|
| 253 |
+
* AuxK revives latents whose encoder rows were shrunk 50×. With AuxK, at least 2 of 4 fire on more than 5 % of
|
| 254 |
+
samples and FVU is lower. Without AuxK they stay dead.
|
| 255 |
+
* Observer FVU EMA falls from above 0.5 to below 0.3 on planted data.
|
| 256 |
+
* Exact state round-trips with full validation.
|
| 257 |
+
* Ablation on clones only, with the original engine's digest unchanged.
|
| 258 |
+
* The quick receipt is sealed and deterministic.
|
docs/frontier/modules/synchrony.md
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `synchrony`: synchronisation representation and neuron-level models
|
| 2 |
+
|
| 3 |
+
Module file: `synapse/frontier/synchrony.py` · tests: `tests/test_frontier_synchrony.py` ·
|
| 4 |
+
experiment ids: `synchrony`, `synchrony_ctm` · engine extension: `SynchronyExtension` (id `synchrony`) ·
|
| 5 |
+
live observer: `SynchronyObserver` · standalone model: `MiniCTM` · evidence tier: `synthetic_abstraction`.
|
| 6 |
+
|
| 7 |
+
The module borrows three ideas from **Continuous Thought Machines** (CTM; Darlow et al., NeurIPS 2025) and uses
|
| 8 |
+
them at toy scale:
|
| 9 |
+
|
| 10 |
+
* **Synchronisation as a representation.** The exponentially decayed inner product of two units' activity
|
| 11 |
+
histories, kept by a two-number recursion per unit pair. It is used as extra readout features of a NEUROWEAVE
|
| 12 |
+
brain (engine extension) and as a read-only activity statistic (live observer).
|
| 13 |
+
* **Private neuron-level models (NLMs).** Every neuron of `MiniCTM` has its own tiny MLP over its last `M`
|
| 14 |
+
pre-activations.
|
| 15 |
+
* **Internal ticks with a tick-selecting loss.** `MiniCTM` "thinks" for `T` ticks per input and is trained
|
| 16 |
+
on the minimum-loss tick and the most-certain tick.
|
| 17 |
+
|
| 18 |
+
It is *inspired by* the CTM and does not reproduce it. The models here are thousands of parameters, not
|
| 19 |
+
millions. The benchmark is cumulative parity of 12-bit sequences (8 in quick mode), not 64. Nothing below says
|
| 20 |
+
anything about the paper's mazes, ImageNet or parity results, about biological synchrony, or about thought.
|
| 21 |
+
|
| 22 |
+
## What it computes
|
| 23 |
+
|
| 24 |
+
**Synchronisation (CTM Sec. 3.4, Eq. 10; App. H, Eqs. 13–17).** For a unit pair `(i, j)` with decay rate
|
| 25 |
+
`r >= 0` and activities `z^1 … z^t`:
|
| 26 |
+
|
| 27 |
+
```
|
| 28 |
+
S_ij^t = sum_{tau=1..t} e^{-r (t - tau)} z_i^tau z_j^tau / sqrt( sum_{tau=1..t} e^{-r (t - tau)} )
|
| 29 |
+
|
| 30 |
+
alpha <- e^{-r} alpha + z_i z_j beta <- e^{-r} beta + 1 S = alpha / sqrt(beta)
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
The recursion needs two numbers per pair and no stored history. `decayed_synchrony(history, left, right,
|
| 34 |
+
decay)` is the closed form. Tests check that the extension's recursion equals it on a hand-computed
|
| 35 |
+
three-step example, to 1e-12 relative error, and on a random 40-step history, to 1e-12 absolute. They also
|
| 36 |
+
check that `MiniCTM`'s batched recursion equals it at every tick for both of its synchronisation
|
| 37 |
+
representations.
|
| 38 |
+
|
| 39 |
+
**Bounds.** With `|z| <= 1`, `|alpha| <= beta`, so `|S| <= sqrt(beta) < 1 / sqrt(1 - e^{-r})`. For a steady
|
| 40 |
+
product, `S` grows like the square root of the effective window; that is the paper's normalisation. The
|
| 41 |
+
optional "unit" scale `S * sqrt(1 - e^{-r})` stays in `[-1, 1]`; with `z = 1` everywhere it equals
|
| 42 |
+
`sqrt(1 - e^{-r t})` exactly (tested).
|
| 43 |
+
|
| 44 |
+
**Pair sampling (CTM App. C.2, "random pairing").** `sample_pairs(n, pairs, self_pairs, rng)` returns
|
| 45 |
+
`self_pairs` self pairs `(i, i)` first, then distinct unordered cross pairs `i < j`. The CTM adds self pairs
|
| 46 |
+
so the representation can recover a snapshot of single-unit activity. One difference from the reference code:
|
| 47 |
+
it samples indices with replacement, while here self pairs use distinct units and cross pairs repeat only
|
| 48 |
+
when more are requested than `n (n - 1) / 2` exist.
|
| 49 |
+
|
| 50 |
+
**Timescales.** The CTM learns one rate `r_ij` per pair, starting at 0 (no decay). The extension and the
|
| 51 |
+
observer fix the rates instead: `log_uniform_timescales` spreads `tau_p = 1 / r_p` log-uniformly (stratified,
|
| 52 |
+
in a seeded order) over a range, so features cover several timescales at once.
|
| 53 |
+
|
| 54 |
+
## Engine extension (`SynchronyExtension`, id `synchrony`)
|
| 55 |
+
|
| 56 |
+
```python
|
| 57 |
+
SynchronyExtension(pairs=32, *, seed=0, self_pairs=None, timescales=(1.0, 32.0), feature_scale='ctm')
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
* `bind(engine)` samples `pairs` unit pairs (default `self_pairs = pairs // 8`) from the `engine.n` units
|
| 61 |
+
present at bind time. It keeps no reference to the engine. Units born later are ignored and missing units
|
| 62 |
+
count as silent, so the feature shape never changes.
|
| 63 |
+
* `after_step(output, ctx)` runs the recursion on the brain output `z` (clipped to `[-1, 1]`; brain outputs
|
| 64 |
+
already lie there). Pair `p` has the fixed decay `exp(-1 / tau_p)`, with `tau_p` log-uniform over
|
| 65 |
+
`timescales` steps.
|
| 66 |
+
* `features()` returns the `pairs` values of `S` (`feature_scale='ctm'`), or `S * sqrt(1 - decay)` (`'unit'`),
|
| 67 |
+
clipped to `[-10, 10]`. Before the first step it returns zeros.
|
| 68 |
+
* Nothing adapts: there are no trainable parameters (`parameter_count() == 0`), and `ctx['learn']` changes
|
| 69 |
+
nothing. The accumulators still follow activity, which is inference. `transform_drive` is not overridden,
|
| 70 |
+
so the brain's drive and outputs are bit-identical with and without the extension (tested).
|
| 71 |
+
* `export_state()` / `import_state()` round-trip exactly. `import_state` validates everything before it
|
| 72 |
+
changes anything: the configuration and pair indices must match, the arrays must be finite and of the
|
| 73 |
+
right shape, `beta` must equal its closed form `(1 - d^steps) / (1 - d)`, and `|alpha| <= beta`.
|
| 74 |
+
* `copy.deepcopy` gives an independent clone. `telemetry()` reports mean and max `|S|`.
|
| 75 |
+
|
| 76 |
+
## Live observer (`SynchronyObserver`)
|
| 77 |
+
|
| 78 |
+
```python
|
| 79 |
+
SynchronyObserver(n_units, *, seed=7, history=256, pairs=64, self_pairs=None, zclip=5.0)
|
| 80 |
+
SynchronyObserver.from_spec(n_units, spec) # FrontierSpecV1: seed, history, sync_pairs
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
* **z-scoring.** Each unit has a running mean and variance. They are exact (Welford) for the first `history`
|
| 84 |
+
observations and exponentially weighted with rate `1/history` afterwards. z-scores are clipped to
|
| 85 |
+
`[-zclip, zclip]`.
|
| 86 |
+
* **Timescales.** `observer_timescales(history)` gives `2 * 4^k` steps up to `history / 2`, so
|
| 87 |
+
`(2, 8, 32, 128)` for `history = 256`. At each timescale every sampled pair keeps the recursion above on
|
| 88 |
+
z-scores, and every unit in a pair keeps `q_u <- d q_u + z_u^2`.
|
| 89 |
+
* **Two measures per pair and timescale.** `S` is the CTM-scaled synchrony. The decayed correlation
|
| 90 |
+
`C = alpha / sqrt(q_i q_j)` lies in `[-1, 1]` by Cauchy–Schwarz.
|
| 91 |
+
* **`summary()`** (JSON-safe, no wall-clock, under 16 KB even at 4096 pairs; tested):
|
| 92 |
+
`module`, `n_units`, `pairs`, `self_pairs`, `cross_pairs`, `timescales`, `zscore_window`,
|
| 93 |
+
`observed_steps`;
|
| 94 |
+
`per_timescale` (one row per timescale with `tau`, `mean_abs_S`, `max_abs_S`, `mean_abs_corr` and
|
| 95 |
+
`max_abs_corr` over cross pairs);
|
| 96 |
+
`global_synchrony_index` (mean `|C|` over cross pairs at the slowest timescale);
|
| 97 |
+
`top_pairs` (the 8 cross pairs with the largest `|C|` at the slowest timescale, each with `i` and `j`
|
| 98 |
+
indices into the observed units, plus `corr`, `corr_by_tau` and `S_by_tau`);
|
| 99 |
+
`synchrony_entropy` (Shannon entropy of the `|C|` distribution over cross pairs divided by `log(cross pairs)`:
|
| 100 |
+
1 when synchrony is spread evenly, lower when it is concentrated; `None` when undefined).
|
| 101 |
+
* **Known answers (tested).** Identical units give `C = 1` on every pair and timescale and entropy 1. A planted
|
| 102 |
+
in-phase pair and two planted anti-phase pairs are the top three pairs, with `C = +1` and `C = -1`. For
|
| 103 |
+
independent noise, mean `|C|` falls monotonically with the timescale and is below 0.15 at `tau = 128`.
|
| 104 |
+
* The observer copies its input and never writes to it. Every buffer has a fixed size: `O(n_units)` moments
|
| 105 |
+
and `O(timescales × pairs)` accumulators, with no activity history. `import_state` validates fully before
|
| 106 |
+
mutating, including the `beta`/`steps` identity and the Cauchy–Schwarz bound.
|
| 107 |
+
|
| 108 |
+
## `MiniCTM` (PyTorch)
|
| 109 |
+
|
| 110 |
+
```python
|
| 111 |
+
MiniCTM(seq_len, *, vocab=2, classes=2, d_model=32, memory=4, nlm_hidden=4, ticks=8, d_input=16,
|
| 112 |
+
n_sync_out=32, n_sync_action=16, self_pairs=4, decay_init=(0.03, 1.0), seed=0)
|
| 113 |
+
model(tokens, ticks=None, *, track=False) -> (logits (B, T, L, C), certainty (B, T)) [, record]
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
The input (token ids, shape `(B, L)`) is read whole. Token and learned position embeddings pass through
|
| 117 |
+
Linear and LayerNorm to give identical keys and values (as in the paper's parity setup, App. F.4). From learnable
|
| 118 |
+
start states `z^0` and pre-activation history `A^0`, each tick `t = 1 … T` runs, in the reference code's order:
|
| 119 |
+
|
| 120 |
+
```
|
| 121 |
+
q = W_in S_action action synchrony -> attention query (Eq. 7)
|
| 122 |
+
o = softmax(kv q / sqrt(d_input)) kv single-head attention over the input (Eq. 8)
|
| 123 |
+
a = LayerNorm(GLU(W_syn [z ; o] + b)) synapse model, depth 1 (Eq. 1)
|
| 124 |
+
A = [A[:, 1:], a] last M pre-activations per neuron (Eq. 2)
|
| 125 |
+
z_d = GLU(GLU(A_d W1_d + b1_d) W2_d + b2_d) private NLM of neuron d (Eq. 3)
|
| 126 |
+
alpha <- e^{-r} alpha + z_i z_j ; S_out = alpha / sqrt(beta)
|
| 127 |
+
y_t = W_out S_out per-tick logits for all L positions (Eq. 6)
|
| 128 |
+
```
|
| 129 |
+
|
| 130 |
+
* **NLMs** (`NeuronLevelModels`). The weights `W1` with shape `(D, M, 2H)` and `W2` with shape `(D, H, 2)`
|
| 131 |
+
hold one private slice per neuron. Each layer is one batched einsum over the neuron axis
|
| 132 |
+
(`'dbm,dmh->dbh'`), the reference's `einsum('BDM,MHD->BDH')` with the neuron axis first. A test checks the
|
| 133 |
+
two contractions agree. It also checks privacy: the gradient of neuron `k`'s output reaches only neuron
|
| 134 |
+
`k`'s weights and history, and changing every other neuron's history leaves neuron `k`'s output and
|
| 135 |
+
weight gradients bit-identical.
|
| 136 |
+
* **Synchronisation** uses random pairing with `self_pairs` self pairs per representation. Each pair has a
|
| 137 |
+
learnable rate `r = softplus(rho)`, initialised log-uniform over `decay_init`, which gives timescales of
|
| 138 |
+
1–33 ticks. The action pairs and the output pairs share one recursion state, because both read the same
|
| 139 |
+
post-activations. The action representation at tick `t` is therefore built from `z^0 … z^{t-1}`, and the
|
| 140 |
+
output representation from `z^0 … z^t`. Both start from the learnable `z^0`, as in the reference code.
|
| 141 |
+
* **Certainty** `C_t` is 1 minus the normalised entropy, averaged over output positions.
|
| 142 |
+
* **Loss** (`ctm_tick_loss`, Sec. 3.5, Eq. 11). `L_t` is the cross-entropy averaged over positions. Per sample,
|
| 143 |
+
`t1 = argmin_t L_t` and `t2 = argmax_t C_t`, and `loss = (L_t1 + L_t2) / 2`. With one tick it reduces to
|
| 144 |
+
plain cross-entropy (tested). Evaluation reads each sample's most-certain tick.
|
| 145 |
+
* **Tested.** Output shapes. A 1-tick run equals the first tick of a longer run. Logits differ across ticks.
|
| 146 |
+
Parameter counts match the analytic formula. Construction never touches the global torch RNG, and the same
|
| 147 |
+
seed gives the same weights whatever the global RNG state. The fused attention equals explicit softmax
|
| 148 |
+
attention in values and gradients.
|
| 149 |
+
|
| 150 |
+
**Baselines.** `AttentiveGRU` is a `GRUCell` unrolled for the same `T` ticks. It reads the input through the
|
| 151 |
+
same attention reader, with the query taken from its hidden state, and is trained with the same tick loss. It
|
| 152 |
+
stands in for the paper's parameter-matched LSTMs run for the same number of ticks. `ParityMLP` is one hidden
|
| 153 |
+
ReLU layer over the whole ±1 sequence, with one tick.
|
| 154 |
+
|
| 155 |
+
## CTM benchmark (`run_ctm_benchmark`, id `synchrony_ctm`)
|
| 156 |
+
|
| 157 |
+
* **Task.** Cumulative parity (CTM Sec. 6, App. F.3): the target at position `l` is the parity of bits
|
| 158 |
+
`0 … l`, and the whole sequence is presented at once. `cumulative_parity_data(L, seed, heldout)` enumerates
|
| 159 |
+
all `2^L` sequences and splits off `heldout` of them by a seeded permutation, so held-out sequences are
|
| 160 |
+
never trained on.
|
| 161 |
+
* **Arms.** `MiniCTM`, `AttentiveGRU` and `ParityMLP`. The GRU and MLP widths are chosen so their trainable
|
| 162 |
+
parameter counts match `MiniCTM`'s within 10 % (else `ValueError`). Counts are computed analytically and
|
| 163 |
+
checked against the instantiated models.
|
| 164 |
+
* **Protocol.** Per seed, all three models share the split, the minibatch index sequence (NumPy generator),
|
| 165 |
+
AdamW (fused CPU kernel where available), the learning rate, weight decay 0.01, gradient clipping at 1.0
|
| 166 |
+
and the step count. PyTorch runs on one thread, and the caller's thread count is restored. The global torch
|
| 167 |
+
RNG is never used.
|
| 168 |
+
* **Verdict.** `harness.compare` on per-seed held-out per-position accuracy (mean over positions and held-out
|
| 169 |
+
sequences), MiniCTM against the best baseline. The best baseline is the one with the higher mean, chosen
|
| 170 |
+
after the fact, which favours the baseline. `verdict_basis` names it. Comparisons against both baselines are
|
| 171 |
+
also stored.
|
| 172 |
+
* **Receipt.** `config` (every size, the optimiser, the readout, the loss, the torch version and threads);
|
| 173 |
+
`models.<name>` with `trainable_parameters`, `per_seed` (held-out and train accuracy, per-position accuracy,
|
| 174 |
+
whole-sequence accuracy, last-tick accuracy, mean most-certain tick, a loss curve, the optimiser
|
| 175 |
+
implementation and wall-clock) and a `summary`; `parameter_budget`; `comparisons`; `verdict`;
|
| 176 |
+
`verdict_basis`; `estimated_cost` (forward multiply-accumulates per sequence and for training), kept apart
|
| 177 |
+
from `measured_wallclock_s`; and `notes`.
|
| 178 |
+
|
| 179 |
+
| Setting | quick | default |
|
| 180 |
+
|---|---|---|
|
| 181 |
+
| `seq_len` L / held-out of 2^L | 8 / 64 of 256 | 12 / 512 of 4096 |
|
| 182 |
+
| `ticks`, `d_model`, `d_input`, `memory`, `nlm_hidden` | 4, 24, 12, 4, 4 | 8, 32, 16, 4, 4 |
|
| 183 |
+
| `n_sync_action`, `n_sync_out`, `self_pairs` | 12, 24, 3 | 16, 32, 4 |
|
| 184 |
+
| steps × batch, learning rate | 100 × 32, 0.01 | 800 × 64, 0.01 |
|
| 185 |
+
| trainable parameters: MiniCTM / GRU / MLP | 4036 / 3978 (h 25) / 4041 (h 161) | 6600 / 6680 (h 32) / 6610 (h 178) |
|
| 186 |
+
|
| 187 |
+
## Lab experiment (`run_experiment`, id `synchrony`)
|
| 188 |
+
|
| 189 |
+
`harness.run_extension_experiment('synchrony', factory, task='rhythm', control='random_trace',
|
| 190 |
+
metric='accuracy', ...)` runs three arms: the NEUROWEAVE baseline readout, the baseline plus
|
| 191 |
+
`SynchronyExtension` features, and the baseline plus the same number of random leaky-trace features (the
|
| 192 |
+
capacity-matched control). All arms share seeds, streams and the readout protocol, and held-out streams are
|
| 193 |
+
evaluated frozen. The verdict is `improved` only if the candidate beats both the baseline and the control. The
|
| 194 |
+
defaults are those of the harness (seeds 0, 1, 2; held-out seeds 100, 101; 300 steps; 48 neurons; clustered
|
| 195 |
+
topology; no extra mechanisms), with 32 pairs, `timescales=(1, 32)` and `feature_scale='unit'`, so the
|
| 196 |
+
features share the control's `[-1, 1]` range. Quick mode uses the harness `QUICK_ARGS` sizes with the
|
| 197 |
+
caller's seeds and 16 pairs. Overrides: `pairs`, `self_pairs`, `timescales`, `feature_scale`, `task`,
|
| 198 |
+
`heldout_seeds`, `steps`, `heldout_steps`, `neurons`, `topology`, `mechanisms`.
|
| 199 |
+
|
| 200 |
+
## Public API
|
| 201 |
+
|
| 202 |
+
```python
|
| 203 |
+
MODULE_ID = 'synchrony'
|
| 204 |
+
EXPERIMENTS = {'synchrony': run_experiment, 'synchrony_ctm': run_ctm_benchmark}
|
| 205 |
+
run_experiment(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed receipt
|
| 206 |
+
run_ctm_benchmark(*, quick=False, seeds=(0, 1, 2), **overrides) -> dict # sealed receipt
|
| 207 |
+
SynchronyExtension(pairs=32, *, seed=0, self_pairs=None, timescales=(1.0, 32.0), feature_scale='ctm')
|
| 208 |
+
SynchronyObserver(n_units, *, seed=7, history=256, pairs=64, self_pairs=None, zclip=5.0)
|
| 209 |
+
sample_pairs(n, pairs, self_pairs, rng); log_uniform_timescales(count, low, high, rng)
|
| 210 |
+
decayed_synchrony(history, left, right, decay); observer_timescales(history)
|
| 211 |
+
cumulative_parity_data(seq_len, seed, heldout); ctm_tick_loss(logits, targets, certainty=None)
|
| 212 |
+
# PyTorch classes, created on first attribute access (importing the module does not import torch):
|
| 213 |
+
MiniCTM, NeuronLevelModels, SequenceReader, AttentiveGRU, ParityMLP
|
| 214 |
+
```
|
| 215 |
+
|
| 216 |
+
NumPy randomness comes from `numpy.random.default_rng(seed + offset)`. PyTorch parameters are drawn from
|
| 217 |
+
private seeded `torch.Generator` objects by small private layer classes (linear, layer norm, GRU cell) that
|
| 218 |
+
create their own parameters with PyTorch's default initialisation distributions instead of calling the
|
| 219 |
+
`torch.nn` constructors, so the global torch RNG is never read or advanced. Tests check each layer against its
|
| 220 |
+
`torch.nn` counterpart and check that construction leaves the global RNG state unchanged. Every public function
|
| 221 |
+
and constructor validates its input and raises `ValueError` on bad input.
|
| 222 |
+
|
| 223 |
+
## Connection to Sonapse
|
| 224 |
+
|
| 225 |
+
* **Live observer.** `synchrony` is in `spec.OBSERVER_MODULE_IDS`, so a `FrontierSpecV1` may list it in
|
| 226 |
+
`modules`. `SynchronyObserver.from_spec(n_units, spec)` takes `seed`, `history` and `sync_pairs` from the
|
| 227 |
+
spec. The observer reads a copy of activity and never writes to the brain, graft bus, actor or any shared
|
| 228 |
+
RNG. This module does not wire it into the live runtime; the runtime hook lives elsewhere.
|
| 229 |
+
* **Engine extension.** It influences nothing unless attached to a NEUROWEAVE engine with
|
| 230 |
+
`attach_extension`, as in the lab experiment. Even then it only adds readout features.
|
| 231 |
+
* **Standalone model.** `MiniCTM` and its baselines exist only inside `run_ctm_benchmark`.
|
| 232 |
+
* **Defaults.** No Sonapse or NEUROWEAVE default, API or checkpoint format changes.
|
| 233 |
+
|
| 234 |
+
## Not implemented, and differences from the paper
|
| 235 |
+
|
| 236 |
+
* **Decay rates.** They are fixed in the extension and the observer; the CTM learns them. In `MiniCTM` they
|
| 237 |
+
are learned as `r = softplus(rho)` with a log-uniform start. The reference code clamps `r` to `[0, 15]` and
|
| 238 |
+
starts it at 0.
|
| 239 |
+
* **Attention.** It is single-head, without the separate query/key/value and output projections of the
|
| 240 |
+
reference's `nn.MultiheadAttention`; the paper's parity models used 8 heads. Keys and values come from a
|
| 241 |
+
learned embedding reader, not a convolutional backbone.
|
| 242 |
+
* **Synapse model.** Only the depth-1 Linear–GLU–LayerNorm block is implemented, not the U-Net synapse.
|
| 243 |
+
* **NLMs.** They omit the reference `SuperLinear`'s learnable output temperature, its optional LayerNorm and
|
| 244 |
+
dropout.
|
| 245 |
+
* **Pairing.** Only random pairing is implemented; the paper's parity runs used semi-dense pairing.
|
| 246 |
+
* **Training schedule.** Constant learning rate, with no warmup or cosine schedule (the paper used both).
|
| 247 |
+
* **Scale.** The paper used 64-bit sequences, `d_model` 1024, `d_input` 512, up to 100 ticks and 200,000
|
| 248 |
+
iterations. Here L is 12 or 8, `d_model` is 32 or 24, there are 4–8 ticks and 100–800 AdamW
|
| 249 |
+
steps. These runs measure early learning of short parities. They are not a test of the
|
| 250 |
+
paper's claim.
|
| 251 |
+
* **Baselines.** The GRU replaces the paper's LSTM. It is trained with the same tick loss and read at its
|
| 252 |
+
most certain tick; the paper trained its LSTMs on the final tick, reporting that both losses were unstable
|
| 253 |
+
for them.
|
| 254 |
+
* **Not attempted.** Adaptive halting by certainty threshold at inference, and any of the paper's other tasks
|
| 255 |
+
(mazes, ImageNet, sorting, Q&A, RL).
|
| 256 |
+
|
| 257 |
+
## Verified references
|
| 258 |
+
|
| 259 |
+
Checked on 2026-11-17 against the arXiv listing, the NeurIPS virtual-conference page, the paper's full text
|
| 260 |
+
(arXiv PDF) and the reference code. Re-checked on 2026-11-20 (review) against the reference code: the
|
| 261 |
+
`compute_synchronisation` recursion (`alpha <- r alpha + z_i z_j`, `beta <- r beta + 1`, `S = alpha / sqrt(beta)`),
|
| 262 |
+
the decay clamp to `[0, 15]`, the initial output-synchronisation call before the tick loop, the loop order
|
| 263 |
+
(action synchronisation, attention, synapses, trace, neuron-level models, output synchronisation, prediction)
|
| 264 |
+
and `parity_loss` (per-position mean, `argmin` loss tick, `argmax` of `1 - normalised entropy`, mean of the
|
| 265 |
+
two); `MiniCTM` and `ctm_tick_loss` match them.
|
| 266 |
+
|
| 267 |
+
1. Luke Darlow, Ciaran Regan, Sebastian Risi, Jeffrey Seely, Llion Jones (Sakana AI). **Continuous Thought
|
| 268 |
+
Machines.** *Advances in Neural Information Processing Systems (NeurIPS) 2025*, spotlight poster.
|
| 269 |
+
arXiv:2505.05522 (v1 8 May 2025, v4 3 October 2025). https://arxiv.org/abs/2505.05522 ·
|
| 270 |
+
https://neurips.cc/virtual/2025/loc/san-diego/poster/115192. Checked against the full text: Sec. 3.2–3.5
|
| 271 |
+
(Eqs. 1–11: synapse, pre-activation history, NLMs, synchronisation and its decay rescaling, the
|
| 272 |
+
min-loss/max-certainty loss); App. C.2 (random pairing with `n_self` self pairs); App. F.3–F.5 (parity
|
| 273 |
+
data, architecture, optimisation and parameter-matched LSTM baselines); and App. H (Eqs. 12–17, the
|
| 274 |
+
recursive computation).
|
| 275 |
+
2. Reference implementation: **SakanaAI/continuous-thought-machines**,
|
| 276 |
+
https://github.com/SakanaAI/continuous-thought-machines. Read on 2026-11-17: `models/ctm.py`
|
| 277 |
+
(`compute_synchronisation` recursion; decay parameters initialised at 0 and clamped to `[0, 15]`;
|
| 278 |
+
random-pairing selection with self pairs; depth-1 synapse; tick-loop order), `models/modules.py`
|
| 279 |
+
(`SuperLinear`: per-neuron `einsum('BDM,MHD->BDH')` and a learnable temperature) and `utils/losses.py`
|
| 280 |
+
(`parity_loss`: cross-entropy averaged over positions, then the mean of the min-loss and most-certain
|
| 281 |
+
ticks).
|
| 282 |
+
|
| 283 |
+
## Measured results
|
| 284 |
+
|
| 285 |
+
All runs were measured on **2026-11-20** on Windows 11 on ARM64, with Python 3.12.10, torch 2.11 (CPU), NumPy 2.4
|
| 286 |
+
and `OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1` (the CTM benchmark also runs torch on one thread).
|
| 287 |
+
The machine was shared with other jobs, so wall-clock is indicative only. Receipts are deterministic: two calls
|
| 288 |
+
in one process gave the same digest, and the quick digests below were identical in two separate processes that
|
| 289 |
+
day. Seeds are `(0, 1, 2)` throughout.
|
| 290 |
+
|
| 291 |
+
**CTM benchmark, quick** (`run_ctm_benchmark(quick=True)`; digest `c24433021c0c76a0`; 17.8 s under load).
|
| 292 |
+
Cumulative parity of 8 bits, 64 held-out of 256 sequences, 100 steps × 32.
|
| 293 |
+
|
| 294 |
+
| Model | Parameters | Held-out per-position accuracy (per seed) | Mean | Train accuracy (mean) |
|
| 295 |
+
|---|---:|---|---:|---:|
|
| 296 |
+
| `MiniCTM` (4 ticks) | 4036 | 0.553, 0.572, 0.576 | 0.567 | 0.611 |
|
| 297 |
+
| `AttentiveGRU` (4 ticks) | 3978 | 0.537, 0.572, 0.596 | 0.568 | 0.591 |
|
| 298 |
+
| `ParityMLP` | 4041 | 0.658, 0.678, 0.662 | 0.666 | 0.841 |
|
| 299 |
+
|
| 300 |
+
* `mini_ctm − gru`: −0.0013, 95 % CI [−0.0451, +0.0425]; `mini_ctm − mlp`: −0.0990, CI [−0.1270, −0.0709].
|
| 301 |
+
The verdict compares against the MLP (the higher held-out mean): **`worse`**.
|
| 302 |
+
|
| 303 |
+
**CTM benchmark, default** (`run_ctm_benchmark()`; digest `d838aee28cb46d8e`; 228.9 s under load). 12 bits, 512
|
| 304 |
+
held-out of 4096 sequences, 800 steps × 64.
|
| 305 |
+
|
| 306 |
+
| Model | Parameters | Held-out per-position accuracy (per seed) | Mean | Whole-sequence accuracy (mean) |
|
| 307 |
+
|---|---:|---|---:|---:|
|
| 308 |
+
| `MiniCTM` (8 ticks) | 6600 | 0.639, 0.648, 0.668 | 0.652 | 0.003 |
|
| 309 |
+
| `AttentiveGRU` (8 ticks) | 6680 | 0.622, 0.652, 0.708 | 0.660 | 0.005 |
|
| 310 |
+
| `ParityMLP` | 6610 | 0.908, 0.877, 0.889 | 0.891 | 0.210 |
|
| 311 |
+
|
| 312 |
+
* `mini_ctm − gru`: −0.0087, CI [−0.0806, +0.0631]; `mini_ctm − mlp`: −0.2399, CI [−0.3043, −0.1754] →
|
| 313 |
+
**`worse`**.
|
| 314 |
+
* Per position, `MiniCTM` is at 1.0 for the first three positions, 0.89 for the fourth and near 0.5 (chance)
|
| 315 |
+
from the fifth on: at this size and training budget it does not learn cumulative parity beyond a few bits.
|
| 316 |
+
Its most certain tick varies by seed (mean tick 2.4, 4.5 and 6.4 of 8). The paper's parity models are far
|
| 317 |
+
larger and trained far longer; this run says nothing about them.
|
| 318 |
+
|
| 319 |
+
**Lab experiment** (`run_experiment`, task `rhythm`, metric held-out accuracy).
|
| 320 |
+
|
| 321 |
+
| Run | Digest | Held-out accuracy: baseline / candidate / control | Candidate − baseline | Candidate − control | Verdict | Wall-clock |
|
| 322 |
+
|---|---|---|---|---|---|---|
|
| 323 |
+
| quick (24 neurons, 24 / 12 steps, 16 pairs) | `94d638da05ea2d3e` | 0.750 / 0.750 / 0.750 (chance 0.75) | 0.000 (all seeds equal) | 0.000 | `no_detectable_difference` | 1.9 s |
|
| 324 |
+
| default (48 neurons, 300 / 150 steps, 32 pairs) | `dfaebbab4e3fcbae` | 0.799 / 0.809 / 0.797 (chance 0.80) | +0.010, CI [−0.015, +0.035] | +0.012, CI [−0.021, +0.046] | `no_detectable_difference` | 17.9 s |
|
| 325 |
+
|
| 326 |
+
In quick mode every arm predicts the majority class on the 12 held-out steps, so accuracies tie exactly; the
|
| 327 |
+
synchrony features do change the readout (held-out log-loss 0.624 / 0.576 / 0.559 for the baseline and
|
| 328 |
+
0.635 / 0.580 / 0.559 for the candidate, per seed). At the default size the readout is close to the
|
| 329 |
+
majority-class rate for all arms; the features neither help nor hurt measurably.
|
| 330 |
+
|
| 331 |
+
**Observer cost.** `SynchronyObserver.from_spec(256, FrontierSpecV1())` (64 pairs, `history = 256`): 0.09 ms
|
| 332 |
+
per `observe()` (mean of 300 calls on uniform random activity), and a `summary()` of 2.9 KB of JSON.
|
| 333 |
+
|
| 334 |
+
Unit tests (`tests/test_frontier_synchrony.py`, 36 tests) check, among other things: the recursion against the
|
| 335 |
+
closed form `decayed_synchrony`; the CTM loss against a hand-computed min-loss / max-certainty selection; the
|
| 336 |
+
`MiniCTM` synchronisation against a direct sum over ticks; identical, in-phase and anti-phase units in the
|
| 337 |
+
observer; validated state round-trips; and sealed, deterministic receipts that leave the global RNGs and thread
|
| 338 |
+
count unchanged.
|
docs/neuroweave/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,64 @@
|
|
| 1 |
# NEUROWEAVE changelog
|
| 2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
## [Unreleased] — NEUROWEAVE evolution v1 (2026-11-15)
|
| 4 |
|
| 5 |
Baseline: git tag `sonapse-pre-neuroweave-baseline` (commit `6f2761b`). All
|
|
@@ -97,7 +156,7 @@ checkpoint namespace or test was removed or changed in behaviour.
|
|
| 97 |
### Known limitations
|
| 98 |
|
| 99 |
- `associative_memory` and `fast_weights` are declared in the spec but not
|
| 100 |
-
consumed by the runtime.
|
| 101 |
- Every verdict so far for the 24 registered experiments (quick mode only) is
|
| 102 |
`no_detectable_difference`; the full-size experiments have not been run.
|
| 103 |
The supplementary sequence-variant search reports `worse` overall and
|
|
|
|
| 1 |
# NEUROWEAVE changelog
|
| 2 |
|
| 3 |
+
## [Unreleased] — associative trace memory and fast weights (2026-11-19)
|
| 4 |
+
|
| 5 |
+
### Added
|
| 6 |
+
|
| 7 |
+
- `associative_memory` and `fast_weights` are now implemented as engine-level
|
| 8 |
+
mechanisms. Before this change they were declared in the spec but not
|
| 9 |
+
consumed by the runtime.
|
| 10 |
+
- `engine.AssociativeTraceMemory`: a bounded FIFO of 32 episodes, recalled
|
| 11 |
+
by cosine similarity.
|
| 12 |
+
- `engine.FastWeightMemory`: a reward-gated 8×8 value/key matrix.
|
| 13 |
+
- Both reads feed a new optional per-unit input,
|
| 14 |
+
`NeuroWeaveBrain.step(unit_input=...)`.
|
| 15 |
+
- The rules, constants and their source are in README section 6.
|
| 16 |
+
- The new state is exported under `export_state()['associative_memory']` and
|
| 17 |
+
`['fast_weights']` only when the flag is on. `import_state` validates both
|
| 18 |
+
before swapping, including the counts the rules imply (README section 6).
|
| 19 |
+
Older states without these keys still import, with fresh memories. This was
|
| 20 |
+
also checked with a real state exported by the pre-change package
|
| 21 |
+
(README section 12).
|
| 22 |
+
- New tests: `tests/test_neuroweave_assoc_fastweights.py`, 25 tests.
|
| 23 |
+
|
| 24 |
+
### Changed
|
| 25 |
+
|
| 26 |
+
- With neither flag, engine outputs, states and observatories are unchanged.
|
| 27 |
+
A 2026-11-20 check against the committed NEUROWEAVE package (commit
|
| 28 |
+
`b9d8270`) found them bit-identical for three mechanism sets (README
|
| 29 |
+
section 12).
|
| 30 |
+
- With either flag on, outputs change from the step after the first store or
|
| 31 |
+
write. Specs that enable them change behaviour, including the Max Mode preset
|
| 32 |
+
(every mechanism) and the `associative_memory` and `cross_modal_learning`
|
| 33 |
+
experiments.
|
| 34 |
+
- In the 8-step `associative_memory` lab run (seeds 0 and 1, held-out seed 100,
|
| 35 |
+
4 held-out steps, 16 neurons), only `associative_memory` is still inert;
|
| 36 |
+
`fast_weights` now gets an ablation verdict. The expectation in
|
| 37 |
+
`tests/test_neuroweave_review_fixes.py::test_inert_ablation_is_flagged_not_reported_as_a_verdict`
|
| 38 |
+
that both are inert there therefore no longer holds. That test was not
|
| 39 |
+
edited in this change: it still expects both and fails until it is changed
|
| 40 |
+
to expect `associative_memory` alone (the new
|
| 41 |
+
`test_lab_associative_experiment_measures_fast_weights_and_flags_the_short_run_store_as_inert`
|
| 42 |
+
covers the new expectation).
|
| 43 |
+
- `standalone.py`: the not-executed reasons for the two mechanisms now say
|
| 44 |
+
that their state is engine state that the package does not carry. The JS
|
| 45 |
+
page still runs neither.
|
| 46 |
+
|
| 47 |
+
### Known limitations
|
| 48 |
+
|
| 49 |
+
- No benefit is shown. Quick-mode receipts re-run on 2026-11-20 (settings in
|
| 50 |
+
README section 12) gave `no_detectable_difference` for `associative_memory`
|
| 51 |
+
and `cross_modal_learning`.
|
| 52 |
+
- In runs of 12 or fewer training steps the lab never stores an episode, so
|
| 53 |
+
`associative_memory` is reported as `inert_in_this_configuration` there.
|
| 54 |
+
`fast_weights` is written on the first learning step with non-zero reward and
|
| 55 |
+
acts from the next step. At the reference constants its effect on outputs is
|
| 56 |
+
small in short runs, and with `q88_state` on Q8.8 rounding can absorb it
|
| 57 |
+
entirely (README section 12).
|
| 58 |
+
- `experiments._budget` does not count the fast-weight matrix or the episode
|
| 59 |
+
store in `trainable_parameters`. Counted, the quick `associative_memory`
|
| 60 |
+
receipt's parameter ratio would be 258/194 instead of 194/194.
|
| 61 |
+
|
| 62 |
## [Unreleased] — NEUROWEAVE evolution v1 (2026-11-15)
|
| 63 |
|
| 64 |
Baseline: git tag `sonapse-pre-neuroweave-baseline` (commit `6f2761b`). All
|
|
|
|
| 156 |
### Known limitations
|
| 157 |
|
| 158 |
- `associative_memory` and `fast_weights` are declared in the spec but not
|
| 159 |
+
consumed by the runtime. (Implemented on 2026-11-19; see the entry above.)
|
| 160 |
- Every verdict so far for the 24 registered experiments (quick mode only) is
|
| 161 |
`no_detectable_difference`; the full-size experiments have not been run.
|
| 162 |
The supplementary sequence-variant search reports `worse` overall and
|
docs/neuroweave/FEATURE_MATRIX.md
CHANGED
|
@@ -57,8 +57,8 @@ NEUROWEAVE versions are separate, independent implementations.
|
|
| 57 |
|
| 58 |
| NEUROWEAVE 0.4.0 feature | Sonapse status | Where / notes |
|
| 59 |
|---|---|---|
|
| 60 |
-
| Associative trace memory | **
|
| 61 |
-
| Universal fast weights (8×8) | **
|
| 62 |
| Hierarchical temporal memory (fast/mid/slow per unit) | **Adapted** | `cells.py` |
|
| 63 |
| — | **Newly added** | `memory_ecology` (`memory.py`): provenance-tagged (sensory/predicted/external/experience/synthetic), FlyHash-indexed, interference tracking, confirm-to-promote; related pre-existing module: `synapse/multiscale_memory.py` |
|
| 64 |
|
|
|
|
| 57 |
|
| 58 |
| NEUROWEAVE 0.4.0 feature | Sonapse status | Where / notes |
|
| 59 |
|---|---|---|
|
| 60 |
+
| Associative trace memory | **Adapted** (engine-level, since 2026-11-19; declared only before that) | `engine.py` `AssociativeTraceMemory` (`associative_memory`). A FIFO of at most 32 (external-drive key, unit output) episodes. Episodes are stored on learning steps whose reward exceeds 0.35, on every 12th step. Each step recalls the best cosine match; above 0.35 it adds `0.11·sim·state` per unit. Separate from `memory_ecology`. Not executed by the standalone page. Rules: README section 6. Tests: `tests/test_neuroweave_assoc_fastweights.py`. |
|
| 61 |
+
| Universal fast weights (8×8) | **Adapted** in NEUROWEAVE (engine-level, since 2026-11-19; declared only before that); **already present** in Sonapse | `engine.py` `FastWeightMemory` (`fast_weights`). Write on learning steps with reward `R ≠ 0`: `M ← clip(0.999·M + 0.0012·\|R\|·R·v kᵀ, −1, 1)`. Read: each unit gets `0.03·(M k)[i mod 8]`. Not executed by the standalone page. Tests: `tests/test_neuroweave_assoc_fastweights.py`. Related pre-existing module (unchanged): `synapse/fast_weight_memory.py`. |
|
| 62 |
| Hierarchical temporal memory (fast/mid/slow per unit) | **Adapted** | `cells.py` |
|
| 63 |
| — | **Newly added** | `memory_ecology` (`memory.py`): provenance-tagged (sensory/predicted/external/experience/synthetic), FlyHash-indexed, interference tracking, confirm-to-promote; related pre-existing module: `synapse/multiscale_memory.py` |
|
| 64 |
|
docs/neuroweave/README.md
CHANGED
|
@@ -68,7 +68,7 @@ The pre-NEUROWEAVE system is frozen at git tag
|
|
| 68 |
| Packets / events | `packets.py`, `events.py` | typed representation packets, fusion, event bus |
|
| 69 |
| Ecology | `ecology.py` | 1200×660 arena with 7 configs; Sonapse 155-d observation adapter |
|
| 70 |
| Hardware / packages | `hardware.py`, `package.py` | INT8/Q8.8, tile schedule, FPGA mapping manifest, `SONAPSE_NEUROWEAVE_PACKAGE`, legacy import |
|
| 71 |
-
| Engine | `engine.py` | `NeuroWeaveEngine` composes all subsystems |
|
| 72 |
| Sonapse bridge | `bridge.py` (the only torch module) | `NeuroWeaveBusChannel`, `obs_to_sensory` |
|
| 73 |
| Laboratory | `tasks.py`, `experiments.py`, `lesion.py`, `promotion.py` | 24 experiments, lesion assay, promotion ledger |
|
| 74 |
| Standalone runner | `standalone.py` | offline HTML page with JS frozen inference |
|
|
@@ -154,9 +154,10 @@ extensions.
|
|
| 154 |
- `connectome`: `brain.CONNECTOME_FLAGS`
|
| 155 |
- `engine`: `engine.ENGINE_FLAGS`
|
| 156 |
|
| 157 |
-
The union of these sets
|
| 158 |
-
|
| 159 |
-
|
|
|
|
| 160 |
|
| 161 |
**Tests:** abbreviations for the test files.
|
| 162 |
- `core` = `tests/test_neuroweave_core.py`
|
|
@@ -164,6 +165,7 @@ are declared in the spec but no runtime code reads them.** They are marked
|
|
| 164 |
- `ms` = `test_neuroweave_modulation_sensory.py`
|
| 165 |
- `mm` = `test_neuroweave_micro_memory.py`
|
| 166 |
- `pp` = `test_neuroweave_prediction_packets.py`
|
|
|
|
| 167 |
- `hw` = `test_neuroweave_hardware_package.py`
|
| 168 |
- `sa` = `test_neuroweave_standalone.py`
|
| 169 |
|
|
@@ -180,7 +182,7 @@ against Python for the four mechanism sets in that file.
|
|
| 180 |
| 1 | `multi_soma` | neuroweave | implemented | cells | core::each_neuron_flag, core::each_consumed |
|
| 181 |
| 2 | `structural_encoder` | neuroweave | implemented | brain | core::each_consumed; sa (embedded weights) |
|
| 182 |
| 3 | `sparse_code` | neuroweave | implemented | cells, brain | core::each_neuron_flag, `test_q88_and_sparse` |
|
| 183 |
-
| 4 | `associative_memory` | neuroweave |
|
| 184 |
| 5 | `reward_plasticity` | neuroweave | implemented | connectome | `core::test_reward_update_bounded_sign_preserving_and_meta`, core::each_consumed |
|
| 185 |
| 6 | `synaptic_delays` | neuroweave | implemented | connectome | `core::test_delay_ring_buffer`, core::each_consumed |
|
| 186 |
| 7 | `homeostatic_governor` | neuroweave | implemented | cells | core::each_neuron_flag |
|
|
@@ -194,7 +196,7 @@ against Python for the four mechanism sets in that file.
|
|
| 194 |
| 15 | `adaptive_conduction` | neuroweave | implemented | connectome | core::each_consumed, `core::test_frozen_step_does_not_change_synaptic_myelin` |
|
| 195 |
| 16 | `quantised_synapses` | neuroweave | implemented | connectome | `core::test_quantised_int8`, `hw::test_quantise_int8_symmetric_and_bounded` |
|
| 196 |
| 17 | `axonal_branches` | neuroweave | implemented | cells | core::each_neuron_flag, `core::test_cell_myelin_sets_axonal_release_efficacy` |
|
| 197 |
-
| 18 | `fast_weights` | neuroweave |
|
| 198 |
| 19 | `efference_self_model` | neuroweave | implemented | engine / prediction | `eng::test_engine_level_mechanism_changes_outputs`, `pp::test_efference_*` (4 tests) |
|
| 199 |
| 20 | `predictive_coding` | neuroweave | implemented | cells | core::each_neuron_flag |
|
| 200 |
| 21 | `stdp` | neuroweave | implemented | connectome | `core::test_stdp_traces_bounded_and_timing_rule`, `core::test_stdp_learns_with_membrane_spikes` |
|
|
@@ -306,8 +308,92 @@ source sign is never flipped. Rows marked *(core)* are covered by
|
|
| 306 |
| Specialist graft | A separate small recurrent predictor trained only through its own interface. Its coupling starts at 0. `detach()` removes it without residue. |
|
| 307 |
| Representation fusion | Configured or delta-rule learned fusion weights. With zero weights or no packets the input passes through unchanged. |
|
| 308 |
| Memory ecology | Store, retrieve, confirm, replay, forgetting and downscaling. `PREDICTED` items are never returned as verified and are promoted only by `confirm()`. |
|
|
|
|
|
|
|
| 309 |
| Neuromodulation controls | `learning_rate_scale`, `plasticity_scale`, `attention`, `threshold_shift`, `gain`, `sensory_weight`, … are consumed by the engine. `controls['applied_to_brain']` is reported per step. |
|
| 310 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 311 |
## 7. Experiments (24) and methodology
|
| 312 |
|
| 313 |
`spec.EXPERIMENTS` lists 24 experiments in six kinds. Each experiment's
|
|
@@ -479,7 +565,14 @@ setting and does not generalise.
|
|
| 479 |
`neuroweave=NeuroWeaveSpecV1.max_preset(seed=seed, neurons=min(256, max(48, total_neurons // 32)))`.
|
| 480 |
|
| 481 |
The preset:
|
| 482 |
-
- turns every mechanism on
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 483 |
- sets `gain=0.02`, `max_gain=0.1`, `ramp_steps=32`
|
| 484 |
- uses topology `dense_multi_region`
|
| 485 |
- sets `max_neurons = min(4096, 2·neurons)` and `max_synapses = min(250000, max(8192, 48·neurons))`
|
|
@@ -571,7 +664,9 @@ one of three lists:
|
|
| 571 |
- **not executed:**
|
| 572 |
- the learning-only mechanisms
|
| 573 |
- the engine-level subsystems
|
| 574 |
-
- `associative_memory` and `fast_weights`
|
|
|
|
|
|
|
| 575 |
|
| 576 |
**Abstain / review outcome (heuristic, not calibrated).** Each step also
|
| 577 |
reports `selective`: `margin = |2p−1|`, `risk = clip(router_entropy, 0, 1)`
|
|
@@ -691,6 +786,11 @@ to 1 (`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1`).
|
|
| 691 |
- The core of Max Mode section 06 (`run_neuroweave_laboratory` at the max
|
| 692 |
preset, 256 neurons, 16 steps, no opt-in extras) took 2.6–2.8 s over three
|
| 693 |
runs on 2026-11-16, on one CPU thread on the same machine.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 694 |
|
| 695 |
**Estimates (not measurements):**
|
| 696 |
- The brain's own profile estimates state memory as `synapses·40 + n·224`
|
|
@@ -717,9 +817,81 @@ to 1 (`OPENBLAS_NUM_THREADS=OMP_NUM_THREADS=MKL_NUM_THREADS=1`).
|
|
| 717 |
full-size experiments have not been run. The supplementary sequence-variant
|
| 718 |
search reports `worse` overall and `improved` only for sparse vs random in
|
| 719 |
one synthetic setting. Complexity is not evidence of improvement.
|
| 720 |
-
- **
|
| 721 |
-
|
| 722 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 723 |
- **Sonapse sensory mapping is approximate.** Three channels have no source,
|
| 724 |
and `audio_mid` is a speed proxy.
|
| 725 |
- **Not tested here:**
|
|
|
|
| 68 |
| Packets / events | `packets.py`, `events.py` | typed representation packets, fusion, event bus |
|
| 69 |
| Ecology | `ecology.py` | 1200×660 arena with 7 configs; Sonapse 155-d observation adapter |
|
| 70 |
| Hardware / packages | `hardware.py`, `package.py` | INT8/Q8.8, tile schedule, FPGA mapping manifest, `SONAPSE_NEUROWEAVE_PACKAGE`, legacy import |
|
| 71 |
+
| Engine | `engine.py` | `NeuroWeaveEngine` composes all subsystems; engine-level `AssociativeTraceMemory` and `FastWeightMemory` (added 2026-11-19) |
|
| 72 |
| Sonapse bridge | `bridge.py` (the only torch module) | `NeuroWeaveBusChannel`, `obs_to_sensory` |
|
| 73 |
| Laboratory | `tasks.py`, `experiments.py`, `lesion.py`, `promotion.py` | 24 experiments, lesion assay, promotion ledger |
|
| 74 |
| Standalone runner | `standalone.py` | offline HTML page with JS frozen inference |
|
|
|
|
| 154 |
- `connectome`: `brain.CONNECTOME_FLAGS`
|
| 155 |
- `engine`: `engine.ENGINE_FLAGS`
|
| 156 |
|
| 157 |
+
The union of these sets covers all 45 ids. Until 2026-11-19
|
| 158 |
+
`associative_memory` and `fast_weights` were declared in the spec but read by
|
| 159 |
+
no runtime code. They are now engine-level mechanisms (rows 4 and 18; rules in
|
| 160 |
+
section 6). `memory_ecology` is still a separate store.
|
| 161 |
|
| 162 |
**Tests:** abbreviations for the test files.
|
| 163 |
- `core` = `tests/test_neuroweave_core.py`
|
|
|
|
| 165 |
- `ms` = `test_neuroweave_modulation_sensory.py`
|
| 166 |
- `mm` = `test_neuroweave_micro_memory.py`
|
| 167 |
- `pp` = `test_neuroweave_prediction_packets.py`
|
| 168 |
+
- `af` = `test_neuroweave_assoc_fastweights.py`
|
| 169 |
- `hw` = `test_neuroweave_hardware_package.py`
|
| 170 |
- `sa` = `test_neuroweave_standalone.py`
|
| 171 |
|
|
|
|
| 182 |
| 1 | `multi_soma` | neuroweave | implemented | cells | core::each_neuron_flag, core::each_consumed |
|
| 183 |
| 2 | `structural_encoder` | neuroweave | implemented | brain | core::each_consumed; sa (embedded weights) |
|
| 184 |
| 3 | `sparse_code` | neuroweave | implemented | cells, brain | core::each_neuron_flag, `test_q88_and_sparse` |
|
| 185 |
+
| 4 | `associative_memory` | neuroweave | implemented (engine-level, since 2026-11-19; not executed by the standalone page) | engine (`AssociativeTraceMemory`) | `af::test_each_flag_alone_changes_outputs_from_the_step_after_the_first_write`, `af::test_associative_recall_picks_best_cosine_match_and_scales_the_stored_state`, `af::test_associative_store_gating_fifo_capacity_and_clipping`, `af::test_engine_step_feeds_exactly_recall_plus_fast_read_into_the_brain` |
|
| 186 |
| 5 | `reward_plasticity` | neuroweave | implemented | connectome | `core::test_reward_update_bounded_sign_preserving_and_meta`, core::each_consumed |
|
| 187 |
| 6 | `synaptic_delays` | neuroweave | implemented | connectome | `core::test_delay_ring_buffer`, core::each_consumed |
|
| 188 |
| 7 | `homeostatic_governor` | neuroweave | implemented | cells | core::each_neuron_flag |
|
|
|
|
| 196 |
| 15 | `adaptive_conduction` | neuroweave | implemented | connectome | core::each_consumed, `core::test_frozen_step_does_not_change_synaptic_myelin` |
|
| 197 |
| 16 | `quantised_synapses` | neuroweave | implemented | connectome | `core::test_quantised_int8`, `hw::test_quantise_int8_symmetric_and_bounded` |
|
| 198 |
| 17 | `axonal_branches` | neuroweave | implemented | cells | core::each_neuron_flag, `core::test_cell_myelin_sets_axonal_release_efficacy` |
|
| 199 |
+
| 18 | `fast_weights` | neuroweave | implemented (engine-level, since 2026-11-19; not executed by the standalone page) | engine (`FastWeightMemory`) | `af::test_each_flag_alone_changes_outputs_from_the_step_after_the_first_write`, `af::test_fast_weight_write_and_read_follow_the_rule_exactly`, `af::test_fast_weights_store_reward_signed_value_key_associations`, `af::test_engine_step_feeds_exactly_recall_plus_fast_read_into_the_brain` |
|
| 200 |
| 19 | `efference_self_model` | neuroweave | implemented | engine / prediction | `eng::test_engine_level_mechanism_changes_outputs`, `pp::test_efference_*` (4 tests) |
|
| 201 |
| 20 | `predictive_coding` | neuroweave | implemented | cells | core::each_neuron_flag |
|
| 202 |
| 21 | `stdp` | neuroweave | implemented | connectome | `core::test_stdp_traces_bounded_and_timing_rule`, `core::test_stdp_learns_with_membrane_spikes` |
|
|
|
|
| 308 |
| Specialist graft | A separate small recurrent predictor trained only through its own interface. Its coupling starts at 0. `detach()` removes it without residue. |
|
| 309 |
| Representation fusion | Configured or delta-rule learned fusion weights. With zero weights or no packets the input passes through unchanged. |
|
| 310 |
| Memory ecology | Store, retrieve, confirm, replay, forgetting and downscaling. `PREDICTED` items are never returned as verified and are promoted only by `confirm()`. |
|
| 311 |
+
| Associative trace memory (`associative_memory`; engine, not synaptic) | **Key:** the first 32 values of the step's external drive, zero-padded and clipped to [−1, 1], taken before any attached extension. The external drive is the composed 40-value drive, or the task input when none of `multimodal_sensory`, `memory_ecology` or `representation_fusion` is on. **Store** (learning steps only): when the raw reward, clipped to [−1, 1], exceeds 0.35 and the step index is a multiple of 12, append `(key, unit outputs)`. The store is a FIFO of at most 32 episodes. **Recall** (every step, including frozen steps): take the episode with the highest cosine similarity `k·q / (‖k‖‖q‖ + 1e-9)`, the earliest on ties. If that similarity exceeds 0.35, unit *i* receives `0.11·sim·state_i`, with the state zero-padded or truncated to the current population. An empty store or a weak match adds nothing. Keys and states are clipped, so one recall adds at most 0.11 per unit. |
|
| 312 |
+
| Universal fast weights (`fast_weights`; engine, not synaptic) | **Key `k`:** the first 8 drive values, clipped. **Read** (every step, including frozen steps): `f = M k`, and unit *i* receives `0.03·f[i mod 8]`, at most 0.24 in magnitude. **Write** (learning steps whose raw reward `R`, clipped to [−1, 1], is non-zero): `M ← clip(0.999·M + 0.0012·\|R\|·R·v kᵀ, −1, 1)`. Here `v` is the first 8 pooled readout features after the step, clipped. A zero matrix adds nothing. |
|
| 313 |
| Neuromodulation controls | `learning_rate_scale`, `plasticity_scale`, `attention`, `threshold_shift`, `gain`, `sensory_weight`, … are consumed by the engine. `controls['applied_to_brain']` is reported per step. |
|
| 314 |
|
| 315 |
+
**Associative trace memory and fast weights (engine-level, added 2026-11-19).**
|
| 316 |
+
These are `AssociativeTraceMemory` and `FastWeightMemory` in `engine.py`. The
|
| 317 |
+
recall and the fast-weight read are summed into one per-unit input,
|
| 318 |
+
`NeuroWeaveBrain.step(unit_input=...)`. That input is added to the
|
| 319 |
+
feed-forward drive after any receptor gain.
|
| 320 |
+
|
| 321 |
+
Behaviour and tests (all in `af`):
|
| 322 |
+
- **Exact no-op when off.** Without either flag the engine never passes
|
| 323 |
+
`unit_input`, and states and observatories gain no new keys
|
| 324 |
+
(`test_neither_flag_keeps_the_previous_code_path`). With the flags on but
|
| 325 |
+
nothing written yet, outputs are bit-identical to the engine without them
|
| 326 |
+
(`test_empty_store_and_zero_matrix_contribute_exactly_nothing`).
|
| 327 |
+
- **Learning only with `learn=True`.** Only learning steps store or write.
|
| 328 |
+
Frozen steps still read what was learned
|
| 329 |
+
(`test_frozen_steps_read_but_never_write`).
|
| 330 |
+
- **Known-answer tests** for both rules:
|
| 331 |
+
`test_associative_recall_picks_best_cosine_match_and_scales_the_stored_state`,
|
| 332 |
+
`test_associative_store_gating_fifo_capacity_and_clipping`,
|
| 333 |
+
`test_fast_weight_write_and_read_follow_the_rule_exactly`,
|
| 334 |
+
`test_fast_weights_store_reward_signed_value_key_associations` and
|
| 335 |
+
`test_engine_step_feeds_exactly_recall_plus_fast_read_into_the_brain`.
|
| 336 |
+
- **Bounds and determinism.** Contributions and stored state stay bounded under
|
| 337 |
+
hostile inputs (`test_contributions_and_state_stay_bounded`). Same seed gives
|
| 338 |
+
the same outputs and state digest, a JSON round trip continues exactly, and
|
| 339 |
+
the global NumPy RNG is untouched
|
| 340 |
+
(`test_determinism_round_trip_and_no_global_rng_use`).
|
| 341 |
+
- **Persistence.** The state is in `export_state()['associative_memory']` and
|
| 342 |
+
`['fast_weights']`, present only when the flag is on. `import_state`
|
| 343 |
+
validates both before it swaps anything in
|
| 344 |
+
(`test_import_validates_everything_before_mutating`). Besides shapes and
|
| 345 |
+
bounds it checks what the rules imply: episode steps are increasing
|
| 346 |
+
multiples of 12 below the engine step, exactly `min(stores, 32)` episodes
|
| 347 |
+
remain, there is at most one recall hit and one fast-weight write per step,
|
| 348 |
+
`stores` does not exceed the number of scheduled store steps, and a non-zero
|
| 349 |
+
matrix has at least one recorded write
|
| 350 |
+
(`test_from_state_enforces_capacity_and_per_step_counts`). A state saved
|
| 351 |
+
without these keys imports with an empty store and a zero matrix
|
| 352 |
+
(`test_states_saved_before_the_mechanisms_existed_import_with_fresh_memories`).
|
| 353 |
+
- **Step results.** `step()` reports per-step `associative_memory` and
|
| 354 |
+
`fast_weights` records, and `observatory()['learning']` reports their
|
| 355 |
+
summaries.
|
| 356 |
+
|
| 357 |
+
**Where the constants come from.** They follow the NEUROWEAVE-LAB 0.4.0
|
| 358 |
+
`memory` and `fastWeights` switches as re-implemented in the sibling
|
| 359 |
+
SONAPSE-EVO port (`src/sonapse_evo/neuroweave/memory/associative.py` and
|
| 360 |
+
`memory/fast_weights.py`, read at commit `eb498fb`). All eleven constants
|
| 361 |
+
match that port. The original JavaScript was not available to this build. This
|
| 362 |
+
version differs from that port in four ways:
|
| 363 |
+
- keys are taken from the engine's external drive, not the port's observation
|
| 364 |
+
vector;
|
| 365 |
+
- keys, stored states and fast-weight values are clipped to [−1, 1];
|
| 366 |
+
- the stored state is the unit-output vector, not the port's rate vector;
|
| 367 |
+
- the fast-weight value is the first 8 of this engine's pooled readout
|
| 368 |
+
features (`NeuroWeaveBrain.readout_features`), not the port's
|
| 369 |
+
`pooled_features`.
|
| 370 |
+
|
| 371 |
+
**Related work (inspired by, not reproductions).**
|
| 372 |
+
- The fast weights are a hetero-associative, reward-signed variant of the
|
| 373 |
+
decaying outer-product fast weights of Ba et al. (2016),
|
| 374 |
+
`A(t) = λA(t−1) + η h(t)h(t)ᵀ`.
|
| 375 |
+
- The recall resembles the key-similarity lookup of Neural Episodic Control
|
| 376 |
+
(Pritzel et al., 2017). It uses a single best cosine match, not that paper's
|
| 377 |
+
kernel-weighted sum over the p nearest neighbours.
|
| 378 |
+
- Both writes are reward-gated, in the spirit of three-factor learning rules
|
| 379 |
+
(Frémaux & Gerstner, 2016).
|
| 380 |
+
|
| 381 |
+
References (titles, authors, venues and the two rules quoted above checked
|
| 382 |
+
against the publisher and arXiv pages on 2026-11-20):
|
| 383 |
+
- J. Ba, G. E. Hinton, V. Mnih, J. Z. Leibo, C. Ionescu, "Using Fast Weights to
|
| 384 |
+
Attend to the Recent Past", *Advances in Neural Information Processing
|
| 385 |
+
Systems 29* (NIPS 2016), Dec 2016.
|
| 386 |
+
<https://proceedings.neurips.cc/paper/2016/hash/9f44e956e3a2b7b5598c625fcc802c36-Abstract.html>
|
| 387 |
+
(arXiv:1610.06258; its rule, Eq. 1, is Hebbian and not reward-gated)
|
| 388 |
+
- A. Pritzel, B. Uria, S. Srinivasan, A. Puigdomènech Badia, O. Vinyals,
|
| 389 |
+
D. Hassabis, D. Wierstra, C. Blundell, "Neural Episodic Control", *Proc.
|
| 390 |
+
34th ICML*, PMLR 70:2827–2836, Aug 2017.
|
| 391 |
+
<https://proceedings.mlr.press/v70/pritzel17a.html> (arXiv:1703.01988; its
|
| 392 |
+
lookup uses p = 50 neighbours and an inverse-squared-distance kernel)
|
| 393 |
+
- N. Frémaux, W. Gerstner, "Neuromodulated Spike-Timing-Dependent Plasticity,
|
| 394 |
+
and Theory of Three-Factor Learning Rules", *Frontiers in Neural Circuits* 9,
|
| 395 |
+
published 19 Jan 2016. <https://doi.org/10.3389/fncir.2015.00085>
|
| 396 |
+
|
| 397 |
## 7. Experiments (24) and methodology
|
| 398 |
|
| 399 |
`spec.EXPERIMENTS` lists 24 experiments in six kinds. Each experiment's
|
|
|
|
| 565 |
`neuroweave=NeuroWeaveSpecV1.max_preset(seed=seed, neurons=min(256, max(48, total_neurons // 32)))`.
|
| 566 |
|
| 567 |
The preset:
|
| 568 |
+
- turns every mechanism on. Since 2026-11-19 this includes the engine-level
|
| 569 |
+
`associative_memory` and `fast_weights` (section 6). They can act only after
|
| 570 |
+
a learning step has written to them: any non-zero reward writes the fast
|
| 571 |
+
weights, and a reward above 0.35 on a step that is a multiple of 12 stores
|
| 572 |
+
an episode. Runs made after that date can therefore differ from earlier
|
| 573 |
+
ones. The preset also turns on `q88_state`, whose rounding can absorb the
|
| 574 |
+
small fast-weight read (section 12). The difference has not been measured in
|
| 575 |
+
a Max Mode run.
|
| 576 |
- sets `gain=0.02`, `max_gain=0.1`, `ramp_steps=32`
|
| 577 |
- uses topology `dense_multi_region`
|
| 578 |
- sets `max_neurons = min(4096, 2·neurons)` and `max_synapses = min(250000, max(8192, 48·neurons))`
|
|
|
|
| 664 |
- **not executed:**
|
| 665 |
- the learning-only mechanisms
|
| 666 |
- the engine-level subsystems
|
| 667 |
+
- `associative_memory` and `fast_weights`: their episode store and 8×8
|
| 668 |
+
matrix are engine state (`NeuroWeaveEngine.export_state`), which the
|
| 669 |
+
package does not carry, so the page runs neither read
|
| 670 |
|
| 671 |
**Abstain / review outcome (heuristic, not calibrated).** Each step also
|
| 672 |
reports `selective`: `margin = |2p−1|`, `risk = clip(router_entropy, 0, 1)`
|
|
|
|
| 786 |
- The core of Max Mode section 06 (`run_neuroweave_laboratory` at the max
|
| 787 |
preset, 256 neurons, 16 steps, no opt-in extras) took 2.6–2.8 s over three
|
| 788 |
runs on 2026-11-16, on one CPU thread on the same machine.
|
| 789 |
+
- These timings predate the engine-level `associative_memory` and
|
| 790 |
+
`fast_weights` (added 2026-11-19). In the "all 45 on" columns those two did
|
| 791 |
+
no work then. Per step they now add a cosine search over at most 32 stored
|
| 792 |
+
keys of 32 values, an 8×8 read and write, and one per-unit vector addition.
|
| 793 |
+
The table has not been re-measured.
|
| 794 |
|
| 795 |
**Estimates (not measurements):**
|
| 796 |
- The brain's own profile estimates state memory as `synapses·40 + n·224`
|
|
|
|
| 817 |
full-size experiments have not been run. The supplementary sequence-variant
|
| 818 |
search reports `worse` overall and `improved` only for sparse vs random in
|
| 819 |
one synthetic setting. Complexity is not evidence of improvement.
|
| 820 |
+
- **`associative_memory` and `fast_weights` are new and show no benefit
|
| 821 |
+
yet.** Before 2026-11-19 they were declared but not implemented. They are now
|
| 822 |
+
engine-level mechanisms (section 6). Quick-mode receipts were re-run on
|
| 823 |
+
2026-11-20 with `QUICK_ARGS`: seeds 0 and 1, held-out seed 100, 24 training
|
| 824 |
+
and 12 held-out steps, 24 neurons, one CPU thread. Each was run twice and
|
| 825 |
+
gave the same receipt digest both times. Other jobs were running on the
|
| 826 |
+
machine, so the wall-clock times are only indicative. Results:
|
| 827 |
+
- `associative_memory`: `no_detectable_difference` with reason
|
| 828 |
+
`degenerate_ci`; the held-out accuracy difference was 0 on both seeds. All
|
| 829 |
+
three ablations (`associative_memory`, `fast_weights`, `memory_ecology`)
|
| 830 |
+
are also `no_detectable_difference`, and none is inert. Wall-clock 2.30 s
|
| 831 |
+
and 1.91 s; digest `c331d9161422c3c8…`.
|
| 832 |
+
- `cross_modal_learning`, whose set includes `associative_memory`:
|
| 833 |
+
`no_detectable_difference`. The held-out accuracy difference was +0.042,
|
| 834 |
+
95% CI [−0.488, 0.571], over 2 seeds. Its three ablations are also
|
| 835 |
+
`no_detectable_difference`, and none is inert. Wall-clock 1.61 s and
|
| 836 |
+
1.96 s; digest `aa10527be1700e91…`.
|
| 837 |
+
|
| 838 |
+
Without either flag the engine matched the committed pre-change NEUROWEAVE
|
| 839 |
+
package (`synapse/neuroweave/` at commit `b9d8270`, loaded from a scratch
|
| 840 |
+
copy) bit for bit in a 2026-11-20 check: outputs, `export_state()` and
|
| 841 |
+
`observatory()['learning']` over 30 steps (24 learning and 6 frozen; seed 5;
|
| 842 |
+
spec and inputs as in the scratch checks below; a reward of 0.7 on every 4th
|
| 843 |
+
step and −0.5 otherwise). Three mechanism sets were checked: none;
|
| 844 |
+
`multi_soma`, `membrane_dynamics`, `synaptic_delays`, `reward_plasticity`,
|
| 845 |
+
`neuromodulator_field`, `multimodal_sensory`, `memory_ecology`,
|
| 846 |
+
`predictive_ensemble` and `micro_collective`; and all 43 others.
|
| 847 |
+
|
| 848 |
+
States saved by that pre-change package also import. In the same check, a
|
| 849 |
+
state exported by it after 25 rewarded steps, with both flags in the spec,
|
| 850 |
+
imported with an empty store and a zero matrix. Two engines that imported it
|
| 851 |
+
continued identically for 15 steps and then stored and wrote as usual. With
|
| 852 |
+
zero reward (so nothing is written), the new export equalled the old one
|
| 853 |
+
plus the two new keys.
|
| 854 |
+
|
| 855 |
+
Limits of these mechanisms:
|
| 856 |
+
- Runs of 12 or fewer training steps never store an episode. Stores happen
|
| 857 |
+
only on step indices that are multiples of 12, and the lab's step-0 reward
|
| 858 |
+
is 0, so the first possible store is on step 12. In such runs
|
| 859 |
+
`associative_memory` is reported as `inert_in_this_configuration`
|
| 860 |
+
(`af::test_lab_associative_experiment_measures_fast_weights_and_flags_the_short_run_store_as_inert`).
|
| 861 |
+
`fast_weights` is not inert there: with seeds 0 and 1, held-out seed 100,
|
| 862 |
+
8 training and 4 held-out steps and 16 neurons, its ablation verdict was
|
| 863 |
+
`no_detectable_difference` (2026-11-20).
|
| 864 |
+
- The lab's `trainable_parameters` budget (`experiments._budget`) counts
|
| 865 |
+
neither the 64 fast-weight entries nor the episode store. Both are counted
|
| 866 |
+
in `state_numbers`. So that receipt's `budget_matched_within_10pct: true`
|
| 867 |
+
(194 vs 194) leaves out 64 learned values on the candidate side. Counted,
|
| 868 |
+
the ratio would be 258/194 ≈ 1.33, outside the 10% band.
|
| 869 |
+
- At the reference constants (η = 0.0012, read gain 0.03) the fast-weight
|
| 870 |
+
read is small. Scratch checks on 2026-11-20 used
|
| 871 |
+
`NeuroWeaveSpecV1(neurons=24, max_neurons=48, structural_interval=5,
|
| 872 |
+
sleep_interval=10)`, with the task inputs and sensory vectors of
|
| 873 |
+
`tasks.make_stream(seed, steps)`, compared against the same spec without
|
| 874 |
+
the flag. Over 30 learning steps (seed 11, with `multi_soma`,
|
| 875 |
+
`membrane_dynamics`, `reward_plasticity`, `multimodal_sensory` and
|
| 876 |
+
`memory_ecology` on, and a reward of 0.7 on every 4th step from step 0 and
|
| 877 |
+
−0.5 otherwise):
|
| 878 |
+
- `fast_weights` alone: largest output change 4.7e-4; the largest matrix
|
| 879 |
+
entry was 1.6e-3 after 30 writes;
|
| 880 |
+
- `associative_memory` alone: largest output change 0.117, from 3 stores
|
| 881 |
+
and 28 recall hits;
|
| 882 |
+
- both first differed at step 1.
|
| 883 |
+
- With `q88_state` on, Q8.8 rounding can absorb that read entirely. Setup:
|
| 884 |
+
the other 43 mechanisms on, seed 5, a reward of 0 on step 0, then 0.7 on
|
| 885 |
+
every 4th step and −0.5 otherwise. Results:
|
| 886 |
+
- adding `fast_weights` changed no output in 40 steps with the inputs of
|
| 887 |
+
`make_stream(5, 40)`;
|
| 888 |
+
- with the inputs of `make_stream(5, 400)`, outputs first differed at
|
| 889 |
+
step 11;
|
| 890 |
+
- without `q88_state`, the 40-step comparison differed from step 2
|
| 891 |
+
(largest change 2.5e-5);
|
| 892 |
+
- adding `associative_memory` instead changed outputs from step 13, the
|
| 893 |
+
step after the first store.
|
| 894 |
+
- The standalone page and the package carry neither memory.
|
| 895 |
- **Sonapse sensory mapping is approximate.** Three channels have no source,
|
| 896 |
and `audio_mid` is a speed proxy.
|
| 897 |
- **Not tested here:**
|
pyproject.toml
CHANGED
|
@@ -1,20 +1,49 @@
|
|
| 1 |
[build-system]
|
| 2 |
-
|
|
|
|
| 3 |
build-backend = "setuptools.build_meta"
|
| 4 |
|
| 5 |
[project]
|
| 6 |
name = "synapse-connectome-lab"
|
| 7 |
-
version = "0.
|
| 8 |
description = "Integrated connectome, weight-programming and bounded RSI research workbench"
|
| 9 |
-
|
|
|
|
|
|
|
| 10 |
requires-python = ">=3.10"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
dependencies = ["torch>=2.4", "numpy>=1.26", "scipy>=1.11"]
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
[project.optional-dependencies]
|
| 14 |
test = ["pytest>=8"]
|
| 15 |
connectomes = ["pyarrow>=14", "pandas>=2"]
|
| 16 |
yaml = ["PyYAML>=6.0"]
|
| 17 |
|
|
|
|
|
|
|
|
|
|
| 18 |
[project.scripts]
|
| 19 |
synapse-lab = "synapse.cli:main"
|
| 20 |
|
|
@@ -24,6 +53,29 @@ include = ["synapse*"]
|
|
| 24 |
[tool.setuptools.package-data]
|
| 25 |
synapse = ["web/*", "source_manifest.json", "_vendor/**/*"]
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
[tool.pytest.ini_options]
|
| 28 |
testpaths = ["tests"]
|
| 29 |
addopts = "-ra"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
[build-system]
|
| 2 |
+
# setuptools>=77 implements PEP 639 (SPDX `license` expression + `license-files`).
|
| 3 |
+
requires = ["setuptools>=77", "wheel"]
|
| 4 |
build-backend = "setuptools.build_meta"
|
| 5 |
|
| 6 |
[project]
|
| 7 |
name = "synapse-connectome-lab"
|
| 8 |
+
version = "0.3.0"
|
| 9 |
description = "Integrated connectome, weight-programming and bounded RSI research workbench"
|
| 10 |
+
readme = "README.md"
|
| 11 |
+
license = "Apache-2.0"
|
| 12 |
+
license-files = ["LICENSE"]
|
| 13 |
requires-python = ">=3.10"
|
| 14 |
+
keywords = [
|
| 15 |
+
"computational-neuroscience",
|
| 16 |
+
"connectomics",
|
| 17 |
+
"neuromorphic-computing",
|
| 18 |
+
"spiking-neural-networks",
|
| 19 |
+
"reinforcement-learning",
|
| 20 |
+
"reproducibility",
|
| 21 |
+
]
|
| 22 |
+
classifiers = [
|
| 23 |
+
"Development Status :: 4 - Beta",
|
| 24 |
+
"Intended Audience :: Science/Research",
|
| 25 |
+
"Operating System :: OS Independent",
|
| 26 |
+
"Programming Language :: Python :: 3",
|
| 27 |
+
"Programming Language :: Python :: 3 :: Only",
|
| 28 |
+
"Programming Language :: Python :: 3.10",
|
| 29 |
+
"Programming Language :: Python :: 3.12",
|
| 30 |
+
"Programming Language :: Python :: 3.13",
|
| 31 |
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
| 32 |
+
]
|
| 33 |
dependencies = ["torch>=2.4", "numpy>=1.26", "scipy>=1.11"]
|
| 34 |
|
| 35 |
+
[project.urls]
|
| 36 |
+
Homepage = "https://github.com/kai9987kai/Sonapse-LAB"
|
| 37 |
+
"Model card" = "https://huggingface.co/Kai9987kai/Sonapse-LAB"
|
| 38 |
+
|
| 39 |
[project.optional-dependencies]
|
| 40 |
test = ["pytest>=8"]
|
| 41 |
connectomes = ["pyarrow>=14", "pandas>=2"]
|
| 42 |
yaml = ["PyYAML>=6.0"]
|
| 43 |
|
| 44 |
+
[dependency-groups]
|
| 45 |
+
dev = ["pytest>=8", "ruff>=0.8", "pip-audit>=2.7", "hypothesis>=6"]
|
| 46 |
+
|
| 47 |
[project.scripts]
|
| 48 |
synapse-lab = "synapse.cli:main"
|
| 49 |
|
|
|
|
| 53 |
[tool.setuptools.package-data]
|
| 54 |
synapse = ["web/*", "source_manifest.json", "_vendor/**/*"]
|
| 55 |
|
| 56 |
+
[tool.setuptools.exclude-package-data]
|
| 57 |
+
"*" = ["*.pyc", "*.pyo", "**/*.pyc", "**/*.pyo"]
|
| 58 |
+
|
| 59 |
+
[tool.setuptools.data-files]
|
| 60 |
+
"share/synapse-connectome-lab" = ["artifacts/tidal_core.pt"]
|
| 61 |
+
|
| 62 |
[tool.pytest.ini_options]
|
| 63 |
testpaths = ["tests"]
|
| 64 |
addopts = "-ra"
|
| 65 |
+
|
| 66 |
+
[tool.ruff]
|
| 67 |
+
target-version = "py310"
|
| 68 |
+
line-length = 140
|
| 69 |
+
extend-exclude = ["synapse/_vendor"]
|
| 70 |
+
|
| 71 |
+
[tool.ruff.lint]
|
| 72 |
+
# Correctness checks
|
| 73 |
+
# (syntax errors, version-incompatible syntax, broken format strings, undefined
|
| 74 |
+
# exports, duplicate keys, invalid escapes, pylint errors, high-signal bugbear).
|
| 75 |
+
# The broader F,E,W,B,UP backlog is recorded in docs/ENGINEERING.md.
|
| 76 |
+
select = [
|
| 77 |
+
"E9", "F63", "F7", "F50", "F52", "F601", "F602", "F621", "F622", "F821", "F822", "F823", "F901",
|
| 78 |
+
"W605", "PLE",
|
| 79 |
+
"B002", "B003", "B004", "B011", "B012", "B013", "B014", "B015", "B016", "B019", "B020",
|
| 80 |
+
"B021", "B022", "B025", "B026", "B029", "B030", "B031", "B032", "B033", "B034", "B035", "B039",
|
| 81 |
+
]
|
scripts/neuroweave_compat_manifest.py
CHANGED
|
@@ -1,19 +1,43 @@
|
|
| 1 |
-
"""Build or verify
|
| 2 |
|
| 3 |
The manifest is an additive-only contract: every public surface recorded here
|
| 4 |
-
(config fields and defaults, CLI sub-commands, HTTP routes, workbench
|
| 5 |
-
checkpoint namespaces
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
Usage::
|
| 9 |
|
| 10 |
-
python scripts/neuroweave_compat_manifest.py --
|
| 11 |
-
python scripts/neuroweave_compat_manifest.py --
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
"""
|
| 13 |
from __future__ import annotations
|
| 14 |
|
| 15 |
import argparse
|
| 16 |
import json
|
|
|
|
| 17 |
import re
|
| 18 |
import subprocess
|
| 19 |
import sys
|
|
@@ -27,6 +51,12 @@ BASELINE_COMMIT = '6f2761b'
|
|
| 27 |
|
| 28 |
# Checkpoint namespaces written by Agent.export_state before NEUROWEAVE.
|
| 29 |
_STATE_KEY = re.compile(r"state\[['\"]([A-Za-z0-9_]+)['\"]\]\s*=")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
|
| 32 |
def _json_default(value):
|
|
@@ -37,40 +67,102 @@ def _json_default(value):
|
|
| 37 |
return repr(value)
|
| 38 |
|
| 39 |
|
| 40 |
-
def
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
|
| 76 |
def check(manifest: dict, current: dict) -> list[str]:
|
|
@@ -88,25 +180,40 @@ def check(manifest: dict, current: dict) -> list[str]:
|
|
| 88 |
|
| 89 |
|
| 90 |
def main(argv=None) -> int:
|
| 91 |
-
parser = argparse.ArgumentParser(description=__doc__)
|
| 92 |
group = parser.add_mutually_exclusive_group(required=True)
|
| 93 |
group.add_argument('--write', action='store_true')
|
| 94 |
group.add_argument('--check', action='store_true')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
args = parser.parse_args(argv)
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
| 97 |
if args.write:
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
try:
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
pass
|
| 105 |
-
MANIFEST.write_text(json.dumps(current, indent=2, sort_keys=True) + '\n', encoding='utf-8')
|
| 106 |
-
print(f'wrote {MANIFEST.relative_to(ROOT)}')
|
| 107 |
return 0
|
| 108 |
-
manifest = json.loads(
|
| 109 |
problems = check(manifest, current)
|
|
|
|
|
|
|
|
|
|
| 110 |
for problem in problems:
|
| 111 |
print(problem)
|
| 112 |
print('compatibility manifest OK' if not problems else f'{len(problems)} compatibility problem(s)')
|
|
|
|
| 1 |
+
"""Build or verify a Sonapse additive-compatibility manifest.
|
| 2 |
|
| 3 |
The manifest is an additive-only contract: every public surface recorded here
|
| 4 |
+
(config fields and defaults, CLI sub-commands and flags, HTTP routes, workbench
|
| 5 |
+
DOM ids, checkpoint namespaces, test modules and Max Mode features) must remain
|
| 6 |
+
present in later trees. New surfaces may be added freely.
|
| 7 |
+
|
| 8 |
+
Two manifests are maintained:
|
| 9 |
+
|
| 10 |
+
* ``docs/neuroweave/compatibility-manifest.json`` (default; tag
|
| 11 |
+
``sonapse-pre-neuroweave-baseline``) - the pre-NEUROWEAVE contract.
|
| 12 |
+
* ``docs/compatibility/manifest-pre-frontier.json`` (tag
|
| 13 |
+
``sonapse-pre-frontier-baseline``) - the pre-Frontier contract.
|
| 14 |
|
| 15 |
Usage::
|
| 16 |
|
| 17 |
+
python scripts/neuroweave_compat_manifest.py --check # default manifest
|
| 18 |
+
python scripts/neuroweave_compat_manifest.py --write # regenerate default
|
| 19 |
+
python scripts/neuroweave_compat_manifest.py --check \\
|
| 20 |
+
--manifest docs/compatibility/manifest-pre-frontier.json \\
|
| 21 |
+
--baseline-tag sonapse-pre-frontier-baseline
|
| 22 |
+
|
| 23 |
+
To (re)build a manifest for a historical tag, inspect a worktree of that tag
|
| 24 |
+
in a fresh interpreter::
|
| 25 |
+
|
| 26 |
+
git worktree add <dir> sonapse-pre-frontier-baseline
|
| 27 |
+
python scripts/neuroweave_compat_manifest.py --write --root <dir> \\
|
| 28 |
+
--manifest docs/compatibility/manifest-pre-frontier.json \\
|
| 29 |
+
--baseline-tag sonapse-pre-frontier-baseline
|
| 30 |
+
git worktree remove --force <dir>
|
| 31 |
+
|
| 32 |
+
``--baseline-tag`` labels a written manifest; on ``--check`` it additionally
|
| 33 |
+
requires the manifest to record that tag. Defaults are unchanged, so a bare
|
| 34 |
+
``--check`` behaves exactly as before.
|
| 35 |
"""
|
| 36 |
from __future__ import annotations
|
| 37 |
|
| 38 |
import argparse
|
| 39 |
import json
|
| 40 |
+
import os
|
| 41 |
import re
|
| 42 |
import subprocess
|
| 43 |
import sys
|
|
|
|
| 51 |
|
| 52 |
# Checkpoint namespaces written by Agent.export_state before NEUROWEAVE.
|
| 53 |
_STATE_KEY = re.compile(r"state\[['\"]([A-Za-z0-9_]+)['\"]\]\s*=")
|
| 54 |
+
_ROUTE = re.compile(r"['\"](/api/[A-Za-z0-9_/.-]*)['\"]")
|
| 55 |
+
# Modules that register arguments on the main parser besides synapse/cli.py.
|
| 56 |
+
_EXTRA_CLI_SOURCES = (
|
| 57 |
+
('synapse', 'neuroweave', 'cli_commands.py'),
|
| 58 |
+
('synapse', 'frontier', 'cli_commands.py'),
|
| 59 |
+
)
|
| 60 |
|
| 61 |
|
| 62 |
def _json_default(value):
|
|
|
|
| 67 |
return repr(value)
|
| 68 |
|
| 69 |
|
| 70 |
+
def _iter_synapse_py(root: Path) -> list[Path]:
|
| 71 |
+
"""Every ``synapse/**/*.py`` file except the vendored third-party tree."""
|
| 72 |
+
package = root / 'synapse'
|
| 73 |
+
return [path for path in sorted(package.rglob('*.py'))
|
| 74 |
+
if '_vendor' not in path.relative_to(package).parts]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _http_routes(root: Path) -> list[str]:
|
| 78 |
+
"""``/api/...`` string literals in every non-vendored ``synapse`` module."""
|
| 79 |
+
routes: set[str] = set()
|
| 80 |
+
for py_file in _iter_synapse_py(root):
|
| 81 |
+
routes.update(_ROUTE.findall(py_file.read_text(encoding='utf-8', errors='ignore')))
|
| 82 |
+
return sorted(routes)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _cli_sources(root: Path) -> list[Path]:
|
| 86 |
+
"""``synapse/cli.py`` plus the existing modules that register main-parser arguments."""
|
| 87 |
+
extras = (root.joinpath(*parts) for parts in _EXTRA_CLI_SOURCES)
|
| 88 |
+
return [root / 'synapse' / 'cli.py', *(path for path in extras if path.exists())]
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _cli_surfaces(sources: list[Path]) -> tuple[list[str], list[str]]:
|
| 92 |
+
"""Sub-command names and long flags registered in ``sources``."""
|
| 93 |
+
text = '\n'.join(path.read_text(encoding='utf-8') for path in sources)
|
| 94 |
+
commands = sorted(set(re.findall(r"add_parser\(\s*['\"]([A-Za-z0-9_-]+)['\"]", text)))
|
| 95 |
+
flags = sorted(set(re.findall(r"add_argument\(\s*['\"](--[A-Za-z0-9_-]+)['\"]", text)))
|
| 96 |
+
return commands, flags
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _same_path(a: Path, b: Path) -> bool:
|
| 100 |
+
return os.path.normcase(os.path.realpath(a)) == os.path.normcase(os.path.realpath(b))
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _git_rev(tag: str, cwd: Path, *, short: bool) -> str | None:
|
| 104 |
+
cmd = ['git', 'rev-parse', '--short', tag] if short else ['git', 'rev-parse', tag]
|
| 105 |
+
try:
|
| 106 |
+
out = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, check=True).stdout.strip()
|
| 107 |
+
except (OSError, subprocess.CalledProcessError):
|
| 108 |
+
return None
|
| 109 |
+
return out or None
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def collect(root: Path | None = None, *, baseline_tag: str = BASELINE_TAG) -> dict:
|
| 113 |
+
"""Collect the public surfaces of the tree at ``root`` (default: this checkout).
|
| 114 |
+
|
| 115 |
+
``root`` other than this checkout must be inspected in a fresh interpreter:
|
| 116 |
+
``SynapseConfig`` is imported from ``root`` and a ``RuntimeError`` is raised
|
| 117 |
+
if a different ``synapse`` package was already imported.
|
| 118 |
+
"""
|
| 119 |
+
explicit_root = root is not None
|
| 120 |
+
repo = ROOT if root is None else Path(root).resolve()
|
| 121 |
+
inserted = False
|
| 122 |
+
if str(repo) not in sys.path:
|
| 123 |
+
sys.path.insert(0, str(repo))
|
| 124 |
+
inserted = True
|
| 125 |
+
try:
|
| 126 |
+
from synapse.config import SynapseConfig
|
| 127 |
+
|
| 128 |
+
if explicit_root:
|
| 129 |
+
loaded = Path(sys.modules['synapse.config'].__file__).resolve().parent
|
| 130 |
+
if not _same_path(loaded, repo / 'synapse'):
|
| 131 |
+
raise RuntimeError(
|
| 132 |
+
f'synapse.config was imported from {loaded}, not {repo / "synapse"}; '
|
| 133 |
+
'inspect another tree in a fresh interpreter (use --root)')
|
| 134 |
+
cfg = SynapseConfig()
|
| 135 |
+
config_defaults = {
|
| 136 |
+
f.name: _json_default(getattr(cfg, f.name)) for f in fields(SynapseConfig)
|
| 137 |
+
}
|
| 138 |
+
cli_commands, cli_flags = _cli_surfaces(_cli_sources(repo))
|
| 139 |
+
routes = _http_routes(repo)
|
| 140 |
+
html = (repo / 'synapse' / 'web' / 'index.html').read_text(encoding='utf-8')
|
| 141 |
+
dom_ids = sorted(set(re.findall(r'\bid="([^"]+)"', html)))
|
| 142 |
+
agent_src = (repo / 'synapse' / 'agent.py').read_text(encoding='utf-8')
|
| 143 |
+
checkpoint_keys = sorted(set(_STATE_KEY.findall(agent_src)))
|
| 144 |
+
tests = sorted(p.name for p in (repo / 'tests').glob('test_*.py'))
|
| 145 |
+
max_cfg = SynapseConfig.max_tandem(total_neurons=48)
|
| 146 |
+
max_audit = max_cfg.max_tandem_feature_audit()
|
| 147 |
+
fallback = BASELINE_COMMIT if baseline_tag == BASELINE_TAG else 'unresolved'
|
| 148 |
+
commit_short = _git_rev(baseline_tag, repo, short=True) or fallback
|
| 149 |
+
return {
|
| 150 |
+
'schema': 'sonapse-compatibility-manifest-v1',
|
| 151 |
+
'baseline_tag': baseline_tag,
|
| 152 |
+
'baseline_commit': commit_short,
|
| 153 |
+
'contract': 'additive-only: every recorded item must remain present; defaults must stay equal',
|
| 154 |
+
'config_defaults': config_defaults,
|
| 155 |
+
'cli_commands': cli_commands,
|
| 156 |
+
'cli_flags': cli_flags,
|
| 157 |
+
'http_routes': routes,
|
| 158 |
+
'web_dom_ids': dom_ids,
|
| 159 |
+
'checkpoint_namespaces': checkpoint_keys,
|
| 160 |
+
'test_modules': tests,
|
| 161 |
+
'max_mode_enabled_features': sorted(max_audit['enabled_features']),
|
| 162 |
+
}
|
| 163 |
+
finally:
|
| 164 |
+
if inserted and str(repo) in sys.path:
|
| 165 |
+
sys.path.remove(str(repo))
|
| 166 |
|
| 167 |
|
| 168 |
def check(manifest: dict, current: dict) -> list[str]:
|
|
|
|
| 180 |
|
| 181 |
|
| 182 |
def main(argv=None) -> int:
|
| 183 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 184 |
group = parser.add_mutually_exclusive_group(required=True)
|
| 185 |
group.add_argument('--write', action='store_true')
|
| 186 |
group.add_argument('--check', action='store_true')
|
| 187 |
+
parser.add_argument('--manifest', type=Path, default=MANIFEST,
|
| 188 |
+
help='manifest JSON path, relative to the repository root '
|
| 189 |
+
'(default: docs/neuroweave/compatibility-manifest.json)')
|
| 190 |
+
parser.add_argument('--baseline-tag', default=None,
|
| 191 |
+
help=f'git tag the manifest describes (default for --write: {BASELINE_TAG}); '
|
| 192 |
+
'with --check, the manifest must record this tag')
|
| 193 |
+
parser.add_argument('--root', type=Path, default=None,
|
| 194 |
+
help='tree to inspect, e.g. a git worktree of the baseline tag (default: this checkout)')
|
| 195 |
args = parser.parse_args(argv)
|
| 196 |
+
manifest_path = args.manifest if args.manifest.is_absolute() else (ROOT / args.manifest)
|
| 197 |
+
tag = args.baseline_tag or BASELINE_TAG
|
| 198 |
+
root = None if args.root is None else args.root.resolve()
|
| 199 |
+
current = collect(root, baseline_tag=tag)
|
| 200 |
if args.write:
|
| 201 |
+
manifest_path.parent.mkdir(parents=True, exist_ok=True)
|
| 202 |
+
full = _git_rev(tag, ROOT if root is None else root, short=False)
|
| 203 |
+
if full:
|
| 204 |
+
current['baseline_commit_full'] = full
|
| 205 |
+
manifest_path.write_text(json.dumps(current, indent=2, sort_keys=True) + '\n', encoding='utf-8')
|
| 206 |
try:
|
| 207 |
+
rel = manifest_path.relative_to(ROOT)
|
| 208 |
+
except ValueError:
|
| 209 |
+
rel = manifest_path
|
| 210 |
+
print(f'wrote {rel}')
|
|
|
|
|
|
|
|
|
|
| 211 |
return 0
|
| 212 |
+
manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
|
| 213 |
problems = check(manifest, current)
|
| 214 |
+
if args.baseline_tag is not None and manifest.get('baseline_tag') != args.baseline_tag:
|
| 215 |
+
problems.insert(0, f'baseline tag mismatch: manifest records {manifest.get("baseline_tag")!r}, '
|
| 216 |
+
f'expected {args.baseline_tag!r}')
|
| 217 |
for problem in problems:
|
| 218 |
print(problem)
|
| 219 |
print('compatibility manifest OK' if not problems else f'{len(problems)} compatibility problem(s)')
|
synapse/__init__.py
CHANGED
|
@@ -1,2 +1,2 @@
|
|
| 1 |
"""SYNAPSE: integrated connectome and recursive improvement research workbench."""
|
| 2 |
-
__version__ = '0.
|
|
|
|
| 1 |
"""SYNAPSE: integrated connectome and recursive improvement research workbench."""
|
| 2 |
+
__version__ = '0.3.0'
|
synapse/adaptation_study.py
CHANGED
|
@@ -63,13 +63,13 @@ def _learned_hash(agent):
|
|
| 63 |
|
| 64 |
|
| 65 |
def _source_fingerprints():
|
| 66 |
-
from .config import
|
| 67 |
root = Path(__file__).resolve().parent
|
| 68 |
names = sorted(p.name for p in root.glob('*.py'))
|
| 69 |
names.extend(f'_vendor/graftbrain/graftbrain/{name}.py' for name in ('brain', 'plasticity', 'neuro_modules', 'world', 'connectomes', 'graft'))
|
| 70 |
names.append('_vendor/poseidon/poseidon/core.py')
|
| 71 |
values = {name: _file_hash(root/name) for name in names}
|
| 72 |
-
values['artifact:tidal_core.pt'] = _file_hash(
|
| 73 |
return values
|
| 74 |
|
| 75 |
|
|
|
|
| 63 |
|
| 64 |
|
| 65 |
def _source_fingerprints():
|
| 66 |
+
from .config import tidal_checkpoint_path
|
| 67 |
root = Path(__file__).resolve().parent
|
| 68 |
names = sorted(p.name for p in root.glob('*.py'))
|
| 69 |
names.extend(f'_vendor/graftbrain/graftbrain/{name}.py' for name in ('brain', 'plasticity', 'neuro_modules', 'world', 'connectomes', 'graft'))
|
| 70 |
names.append('_vendor/poseidon/poseidon/core.py')
|
| 71 |
values = {name: _file_hash(root/name) for name in names}
|
| 72 |
+
values['artifact:tidal_core.pt'] = _file_hash(tidal_checkpoint_path())
|
| 73 |
return values
|
| 74 |
|
| 75 |
|
synapse/agent.py
CHANGED
|
@@ -8,7 +8,7 @@ import torch
|
|
| 8 |
from torch import nn
|
| 9 |
from torch.nn import functional as F
|
| 10 |
from . import sources
|
| 11 |
-
from .config import
|
| 12 |
from graftbrain.brain import GraftedBrain
|
| 13 |
from graftbrain.connectomes import make_proxy
|
| 14 |
from graftbrain.graft import build
|
|
@@ -74,7 +74,7 @@ class IntegratedAgent:
|
|
| 74 |
# A small seeded projection gives camera input a measurable causal path.
|
| 75 |
visual_generator=torch.Generator(device='cpu').manual_seed(config.seed+1907)
|
| 76 |
nn.init.normal_(self.vis_to_sensory.weight,std=0.02,generator=visual_generator)
|
| 77 |
-
self.tidal,self.receipt=load_checkpoint(
|
| 78 |
h=self.tidal.config.hidden_size
|
| 79 |
self.encoder=nn.Linear(155+16+2,len(self.brain.sensory_idx))
|
| 80 |
self.donor_to_graph=nn.Linear(h+6,len(self.brain.sensory_idx),bias=False)
|
|
@@ -177,8 +177,12 @@ class IntegratedAgent:
|
|
| 177 |
self.preparation_updates=0; self.bridge_updates=0; self.episodic=[]; self.tool_memory=[]
|
| 178 |
self._camera_consumed_any=False
|
| 179 |
self.neural_graft=None
|
|
|
|
| 180 |
self.programmed_prior_status={'enabled':False}
|
| 181 |
self._setup_neural_graft()
|
|
|
|
|
|
|
|
|
|
| 182 |
self.reset_episode()
|
| 183 |
|
| 184 |
def _setup_frontier_extensions(self):
|
|
@@ -504,12 +508,19 @@ class IntegratedAgent:
|
|
| 504 |
self.auditory_encoder = AuditorySpikeEncoder(seed=self.config.seed)
|
| 505 |
self.chat_gateway = ConversationalChatGateway(embed_dim=64, seed=self.config.seed)
|
| 506 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 507 |
def _setup_neural_graft(self):
|
| 508 |
if not self.config.neural_graft:
|
| 509 |
return
|
| 510 |
from .neural_graft import NeuralResidualGraft
|
| 511 |
if self.neural_graft is None:
|
| 512 |
-
self.neural_graft=NeuralResidualGraft(seed=self.config.seed
|
|
|
|
| 513 |
self.modules['neural_graft']=self.neural_graft.network
|
| 514 |
if self.config.programmed_connectome and self.neural_graft.connectome is None:
|
| 515 |
try:
|
|
@@ -964,6 +975,9 @@ class IntegratedAgent:
|
|
| 964 |
if getattr(self, 'neuroweave_channel', None) is not None:
|
| 965 |
# No wall-clock: exact-replay receipts compare telemetry byte-for-byte.
|
| 966 |
self.last_telemetry['neuroweave'] = self.neuroweave_channel.get_telemetry_dict(include_timing=False)
|
|
|
|
|
|
|
|
|
|
| 967 |
if getattr(self, 'dpo_engine', None) is not None:
|
| 968 |
self.last_telemetry['verifiable_dpo']={'enabled':True,'pairs':len(self.dpo_engine.preference_buffer),'last_margin':getattr(self.dpo_engine,'last_margin',0.0)}
|
| 969 |
if getattr(self, 'sancf_fabric', None) is not None:
|
|
@@ -1495,6 +1509,8 @@ class IntegratedAgent:
|
|
| 1495 |
channels = fabric_state.get('channels')
|
| 1496 |
if isinstance(channels, dict):
|
| 1497 |
channels.pop('neuroweave', None)
|
|
|
|
|
|
|
| 1498 |
state['neurowave_x2']=self.neurowave_x2.export_state() if getattr(self,'neurowave_x2',None) is not None else None
|
| 1499 |
state['overflow_mini_brain']=self.overflow_mini_brain.state_dict() if getattr(self,'overflow_mini_brain',None) is not None else None
|
| 1500 |
state['selective_ssm']=self.selective_ssm.state_dict() if getattr(self,'selective_ssm',None) is not None else None
|
|
@@ -1639,7 +1655,8 @@ class IntegratedAgent:
|
|
| 1639 |
self.modules['neural_graft']=self.neural_graft.network
|
| 1640 |
else:
|
| 1641 |
from .neural_graft import NeuralResidualGraft
|
| 1642 |
-
self.neural_graft=NeuralResidualGraft(seed=self.config.seed
|
|
|
|
| 1643 |
self.modules['neural_graft']=self.neural_graft.network
|
| 1644 |
if getattr(self,'dendritic_ltc',None) is not None and state.get('dendritic_ltc') is not None:
|
| 1645 |
self.dendritic_ltc.import_state(state['dendritic_ltc'])
|
|
@@ -1695,6 +1712,9 @@ class IntegratedAgent:
|
|
| 1695 |
if state.get('neuroweave_v1') is not None:
|
| 1696 |
# Presence/config agreement was checked before any module was touched.
|
| 1697 |
self.neuroweave_channel.import_state(state['neuroweave_v1'])
|
|
|
|
|
|
|
|
|
|
| 1698 |
if getattr(self,'neurowave_x2',None) is not None and state.get('neurowave_x2') is not None:
|
| 1699 |
self.neurowave_x2.import_state(state['neurowave_x2'])
|
| 1700 |
if getattr(self,'overflow_mini_brain',None) is not None and state.get('overflow_mini_brain') is not None:
|
|
|
|
| 8 |
from torch import nn
|
| 9 |
from torch.nn import functional as F
|
| 10 |
from . import sources
|
| 11 |
+
from .config import tidal_checkpoint_path
|
| 12 |
from graftbrain.brain import GraftedBrain
|
| 13 |
from graftbrain.connectomes import make_proxy
|
| 14 |
from graftbrain.graft import build
|
|
|
|
| 74 |
# A small seeded projection gives camera input a measurable causal path.
|
| 75 |
visual_generator=torch.Generator(device='cpu').manual_seed(config.seed+1907)
|
| 76 |
nn.init.normal_(self.vis_to_sensory.weight,std=0.02,generator=visual_generator)
|
| 77 |
+
self.tidal,self.receipt=load_checkpoint(tidal_checkpoint_path())
|
| 78 |
h=self.tidal.config.hidden_size
|
| 79 |
self.encoder=nn.Linear(155+16+2,len(self.brain.sensory_idx))
|
| 80 |
self.donor_to_graph=nn.Linear(h+6,len(self.brain.sensory_idx),bias=False)
|
|
|
|
| 177 |
self.preparation_updates=0; self.bridge_updates=0; self.episodic=[]; self.tool_memory=[]
|
| 178 |
self._camera_consumed_any=False
|
| 179 |
self.neural_graft=None
|
| 180 |
+
self.frontier_hub=None
|
| 181 |
self.programmed_prior_status={'enabled':False}
|
| 182 |
self._setup_neural_graft()
|
| 183 |
+
if getattr(self.config, 'frontier', None) is not None:
|
| 184 |
+
from .frontier.bridge import attach_frontier_to_agent
|
| 185 |
+
attach_frontier_to_agent(self)
|
| 186 |
self.reset_episode()
|
| 187 |
|
| 188 |
def _setup_frontier_extensions(self):
|
|
|
|
| 508 |
self.auditory_encoder = AuditorySpikeEncoder(seed=self.config.seed)
|
| 509 |
self.chat_gateway = ConversationalChatGateway(embed_dim=64, seed=self.config.seed)
|
| 510 |
|
| 511 |
+
def _frontier_graft_optimizer(self):
|
| 512 |
+
spec = getattr(self.config, 'frontier', None)
|
| 513 |
+
if spec is not None and getattr(spec, 'enabled', False):
|
| 514 |
+
return getattr(spec, 'graft_optimizer', 'adam')
|
| 515 |
+
return 'adam'
|
| 516 |
+
|
| 517 |
def _setup_neural_graft(self):
|
| 518 |
if not self.config.neural_graft:
|
| 519 |
return
|
| 520 |
from .neural_graft import NeuralResidualGraft
|
| 521 |
if self.neural_graft is None:
|
| 522 |
+
self.neural_graft=NeuralResidualGraft(seed=self.config.seed,
|
| 523 |
+
optimizer_kind=self._frontier_graft_optimizer())
|
| 524 |
self.modules['neural_graft']=self.neural_graft.network
|
| 525 |
if self.config.programmed_connectome and self.neural_graft.connectome is None:
|
| 526 |
try:
|
|
|
|
| 975 |
if getattr(self, 'neuroweave_channel', None) is not None:
|
| 976 |
# No wall-clock: exact-replay receipts compare telemetry byte-for-byte.
|
| 977 |
self.last_telemetry['neuroweave'] = self.neuroweave_channel.get_telemetry_dict(include_timing=False)
|
| 978 |
+
if getattr(self, 'frontier_hub', None) is not None and self.frontier_hub.enabled:
|
| 979 |
+
from .frontier.bridge import step_agent_frontier
|
| 980 |
+
step_agent_frontier(self)
|
| 981 |
if getattr(self, 'dpo_engine', None) is not None:
|
| 982 |
self.last_telemetry['verifiable_dpo']={'enabled':True,'pairs':len(self.dpo_engine.preference_buffer),'last_margin':getattr(self.dpo_engine,'last_margin',0.0)}
|
| 983 |
if getattr(self, 'sancf_fabric', None) is not None:
|
|
|
|
| 1509 |
channels = fabric_state.get('channels')
|
| 1510 |
if isinstance(channels, dict):
|
| 1511 |
channels.pop('neuroweave', None)
|
| 1512 |
+
if getattr(self, 'frontier_hub', None) is not None and self.frontier_hub.enabled:
|
| 1513 |
+
state['frontier_v1'] = self.frontier_hub.export_state()
|
| 1514 |
state['neurowave_x2']=self.neurowave_x2.export_state() if getattr(self,'neurowave_x2',None) is not None else None
|
| 1515 |
state['overflow_mini_brain']=self.overflow_mini_brain.state_dict() if getattr(self,'overflow_mini_brain',None) is not None else None
|
| 1516 |
state['selective_ssm']=self.selective_ssm.state_dict() if getattr(self,'selective_ssm',None) is not None else None
|
|
|
|
| 1655 |
self.modules['neural_graft']=self.neural_graft.network
|
| 1656 |
else:
|
| 1657 |
from .neural_graft import NeuralResidualGraft
|
| 1658 |
+
self.neural_graft=NeuralResidualGraft(seed=self.config.seed,
|
| 1659 |
+
optimizer_kind=self._frontier_graft_optimizer())
|
| 1660 |
self.modules['neural_graft']=self.neural_graft.network
|
| 1661 |
if getattr(self,'dendritic_ltc',None) is not None and state.get('dendritic_ltc') is not None:
|
| 1662 |
self.dendritic_ltc.import_state(state['dendritic_ltc'])
|
|
|
|
| 1712 |
if state.get('neuroweave_v1') is not None:
|
| 1713 |
# Presence/config agreement was checked before any module was touched.
|
| 1714 |
self.neuroweave_channel.import_state(state['neuroweave_v1'])
|
| 1715 |
+
if state.get('frontier_v1') is not None or getattr(self, 'frontier_hub', None) is not None:
|
| 1716 |
+
from .frontier.bridge import import_agent_frontier
|
| 1717 |
+
import_agent_frontier(self, state)
|
| 1718 |
if getattr(self,'neurowave_x2',None) is not None and state.get('neurowave_x2') is not None:
|
| 1719 |
self.neurowave_x2.import_state(state['neurowave_x2'])
|
| 1720 |
if getattr(self,'overflow_mini_brain',None) is not None and state.get('overflow_mini_brain') is not None:
|
synapse/capabilities.py
CHANGED
|
@@ -14,7 +14,7 @@ from typing import Any, Dict, List, Optional, Tuple
|
|
| 14 |
import numpy as np
|
| 15 |
import torch
|
| 16 |
from torch import nn
|
| 17 |
-
from .config import ARTIFACTS, PACKAGE, VENDOR
|
| 18 |
from .sources import activate, manifest
|
| 19 |
|
| 20 |
activate()
|
|
@@ -281,7 +281,7 @@ def _handle_memory_nexus_search(payload: Dict[str, Any]) -> Dict[str, Any]:
|
|
| 281 |
# 3. CORE & CONTROLLERS
|
| 282 |
def _handle_core_scene(payload: Dict[str, Any]) -> Dict[str, Any]:
|
| 283 |
from poseidon.core import load_checkpoint
|
| 284 |
-
tidal_path =
|
| 285 |
if not tidal_path.is_file():
|
| 286 |
return {'status': 'unavailable', 'error': 'Tidal core artifact tidal_core.pt not found'}
|
| 287 |
tidal, _ = load_checkpoint(tidal_path)
|
|
@@ -317,7 +317,7 @@ def _handle_core_scene(payload: Dict[str, Any]) -> Dict[str, Any]:
|
|
| 317 |
|
| 318 |
def _handle_core_tidal(payload: Dict[str, Any]) -> Dict[str, Any]:
|
| 319 |
from poseidon.core import load_checkpoint
|
| 320 |
-
tidal_path =
|
| 321 |
if not tidal_path.is_file():
|
| 322 |
return {'status': 'unavailable', 'error': 'Tidal core artifact tidal_core.pt not found'}
|
| 323 |
tidal, receipt = load_checkpoint(tidal_path)
|
|
|
|
| 14 |
import numpy as np
|
| 15 |
import torch
|
| 16 |
from torch import nn
|
| 17 |
+
from .config import ARTIFACTS, PACKAGE, VENDOR, tidal_checkpoint_path
|
| 18 |
from .sources import activate, manifest
|
| 19 |
|
| 20 |
activate()
|
|
|
|
| 281 |
# 3. CORE & CONTROLLERS
|
| 282 |
def _handle_core_scene(payload: Dict[str, Any]) -> Dict[str, Any]:
|
| 283 |
from poseidon.core import load_checkpoint
|
| 284 |
+
tidal_path = tidal_checkpoint_path()
|
| 285 |
if not tidal_path.is_file():
|
| 286 |
return {'status': 'unavailable', 'error': 'Tidal core artifact tidal_core.pt not found'}
|
| 287 |
tidal, _ = load_checkpoint(tidal_path)
|
|
|
|
| 317 |
|
| 318 |
def _handle_core_tidal(payload: Dict[str, Any]) -> Dict[str, Any]:
|
| 319 |
from poseidon.core import load_checkpoint
|
| 320 |
+
tidal_path = tidal_checkpoint_path()
|
| 321 |
if not tidal_path.is_file():
|
| 322 |
return {'status': 'unavailable', 'error': 'Tidal core artifact tidal_core.pt not found'}
|
| 323 |
tidal, receipt = load_checkpoint(tidal_path)
|
synapse/cli.py
CHANGED
|
@@ -3,10 +3,12 @@ import argparse
|
|
| 3 |
import json
|
| 4 |
from dataclasses import replace
|
| 5 |
from pathlib import Path
|
|
|
|
| 6 |
from .config import SynapseConfig, ARTIFACTS
|
| 7 |
|
| 8 |
def main(argv=None):
|
| 9 |
parser=argparse.ArgumentParser(description='SYNAPSE integrated connectome research lab')
|
|
|
|
| 10 |
parser.add_argument('--output',type=Path,default=ARTIFACTS)
|
| 11 |
parser.add_argument('--seed',type=int,default=7)
|
| 12 |
parser.add_argument('--frontier-all',action='store_true',help='activate all frontier cognitive, planning, self-modeling, and neuromorphic features')
|
|
@@ -18,6 +20,8 @@ def main(argv=None):
|
|
| 18 |
parser.add_argument('--dsag-config',type=Path,help='load an explicit DSAGSpecV1 YAML/JSON configuration')
|
| 19 |
parser.add_argument('--neuroweave',dest='neuroweave_enabled',action=argparse.BooleanOptionalAction,default=None,help='opt in to the NEUROWEAVE residual channel for run, train and serve (off by default)')
|
| 20 |
parser.add_argument('--neuroweave-config',dest='neuroweave_config',type=Path,help='load an explicit NeuroWeaveSpecV1 JSON configuration (sets SynapseConfig.neuroweave)')
|
|
|
|
|
|
|
| 21 |
parser.add_argument('--programmed-connectome',action='store_true',help='bind the verified 128-neuron MaleCNS sparse prior')
|
| 22 |
parser.add_argument('--connectome-mode',choices=['proxy','prefer_authentic','strict_authentic'],help='connectome source mode')
|
| 23 |
size=parser.add_mutually_exclusive_group()
|
|
@@ -49,6 +53,15 @@ def main(argv=None):
|
|
| 49 |
nw_inspect=nw_sub.add_parser('inspect'); nw_inspect.add_argument('nw_file',type=Path)
|
| 50 |
nw_seq=nw_sub.add_parser('sequence-search',help='supplementary budget-matched synthetic sequence-variant search (not protein modelling)'); nw_seq.add_argument('--quick',dest='nw_quick',action='store_true'); nw_seq.add_argument('--landscapes',dest='nw_landscapes',type=int); nw_seq.add_argument('--seeds-per-landscape',dest='nw_seq_seeds',type=int); nw_seq.add_argument('--budget',dest='nw_budget',type=int)
|
| 51 |
nw_legacy=nw_sub.add_parser('import-legacy'); nw_legacy.add_argument('nw_file',type=Path); nw_legacy.add_argument('--out',dest='nw_out',type=Path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
for name in ('run','train'):
|
| 53 |
p=sub.add_parser(name); p.add_argument('--steps',type=int,default=100); p.add_argument('--save')
|
| 54 |
p=sub.add_parser('serve'); p.add_argument('--port',type=int,default=8765); p.add_argument('--host',default='127.0.0.1')
|
|
@@ -151,6 +164,14 @@ def main(argv=None):
|
|
| 151 |
if args.neuroweave_enabled is not None or args.neuroweave_config is not None:
|
| 152 |
from .neuroweave.cli_commands import cli_neuroweave_spec
|
| 153 |
config=replace(config,neuroweave=cli_neuroweave_spec(args.neuroweave_enabled,args.neuroweave_config,args.seed))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
if args.command=='serve' and args.nodes is None and not getattr(args, 'frontier_all', False):
|
| 155 |
import os
|
| 156 |
config=replace(config,
|
|
@@ -236,6 +257,9 @@ def main(argv=None):
|
|
| 236 |
elif args.command=='neuroweave':
|
| 237 |
from .neuroweave.cli_commands import run_neuroweave_command
|
| 238 |
result=run_neuroweave_command(args,config)
|
|
|
|
|
|
|
|
|
|
| 239 |
elif args.command=='connectome-inventory':
|
| 240 |
from .connectome_assets import get_source_inventory
|
| 241 |
result={'sources':get_source_inventory()}
|
|
@@ -636,7 +660,7 @@ def main(argv=None):
|
|
| 636 |
result={**result,'measured':False,'evidence_kind':'illustrative',
|
| 637 |
'scope':'standalone synthetic inputs; no measured embodied performance; use planning-study or evidence for actual world trials'}
|
| 638 |
print(json.dumps(result,indent=2,allow_nan=False,default=str))
|
| 639 |
-
return 1 if (args.command in ('verify','adaptation-verify','planning-verify') and not result.get('ok',False)) or (args.command
|
| 640 |
except (ValueError,TypeError,KeyError,OSError,RuntimeError) as exc:
|
| 641 |
parser.exit(2,f'Error: {exc}\n')
|
| 642 |
|
|
|
|
| 3 |
import json
|
| 4 |
from dataclasses import replace
|
| 5 |
from pathlib import Path
|
| 6 |
+
from . import __version__
|
| 7 |
from .config import SynapseConfig, ARTIFACTS
|
| 8 |
|
| 9 |
def main(argv=None):
|
| 10 |
parser=argparse.ArgumentParser(description='SYNAPSE integrated connectome research lab')
|
| 11 |
+
parser.add_argument('--version',action='version',version=f'synapse-connectome-lab {__version__}')
|
| 12 |
parser.add_argument('--output',type=Path,default=ARTIFACTS)
|
| 13 |
parser.add_argument('--seed',type=int,default=7)
|
| 14 |
parser.add_argument('--frontier-all',action='store_true',help='activate all frontier cognitive, planning, self-modeling, and neuromorphic features')
|
|
|
|
| 20 |
parser.add_argument('--dsag-config',type=Path,help='load an explicit DSAGSpecV1 YAML/JSON configuration')
|
| 21 |
parser.add_argument('--neuroweave',dest='neuroweave_enabled',action=argparse.BooleanOptionalAction,default=None,help='opt in to the NEUROWEAVE residual channel for run, train and serve (off by default)')
|
| 22 |
parser.add_argument('--neuroweave-config',dest='neuroweave_config',type=Path,help='load an explicit NeuroWeaveSpecV1 JSON configuration (sets SynapseConfig.neuroweave)')
|
| 23 |
+
from .frontier.cli_commands import register_frontier_cli
|
| 24 |
+
register_frontier_cli(parser)
|
| 25 |
parser.add_argument('--programmed-connectome',action='store_true',help='bind the verified 128-neuron MaleCNS sparse prior')
|
| 26 |
parser.add_argument('--connectome-mode',choices=['proxy','prefer_authentic','strict_authentic'],help='connectome source mode')
|
| 27 |
size=parser.add_mutually_exclusive_group()
|
|
|
|
| 53 |
nw_inspect=nw_sub.add_parser('inspect'); nw_inspect.add_argument('nw_file',type=Path)
|
| 54 |
nw_seq=nw_sub.add_parser('sequence-search',help='supplementary budget-matched synthetic sequence-variant search (not protein modelling)'); nw_seq.add_argument('--quick',dest='nw_quick',action='store_true'); nw_seq.add_argument('--landscapes',dest='nw_landscapes',type=int); nw_seq.add_argument('--seeds-per-landscape',dest='nw_seq_seeds',type=int); nw_seq.add_argument('--budget',dest='nw_budget',type=int)
|
| 55 |
nw_legacy=nw_sub.add_parser('import-legacy'); nw_legacy.add_argument('nw_file',type=Path); nw_legacy.add_argument('--out',dest='nw_out',type=Path)
|
| 56 |
+
fp=sub.add_parser('frontier',help='Frontier pack catalog, observers and experiments (opt-in; JSON to stdout)')
|
| 57 |
+
fp.add_argument('frontier_action',choices=('catalog','experiment','observe','laboratory'),nargs='?',default='catalog')
|
| 58 |
+
fp.add_argument('--id',dest='frontier_id',type=str,default='all',help='Experiment id to run (or "all")')
|
| 59 |
+
fp.add_argument('--quick',dest='frontier_quick',action='store_true',default=False,help='Run experiment(s) in fast quick mode')
|
| 60 |
+
fp.add_argument('--seeds',dest='frontier_seeds',type=str,default='0,1,2',help='Comma-separated integer seeds')
|
| 61 |
+
fp.add_argument('--modules',dest='frontier_sub_modules',type=str,default='all',help='Observer modules for observe/laboratory')
|
| 62 |
+
fp.add_argument('--steps',dest='frontier_steps',type=int,default=32,help='Synthetic observation steps for "frontier observe"')
|
| 63 |
+
fp.add_argument('--units',dest='frontier_units',type=int,default=32,help='Synthetic unit count for "frontier observe"')
|
| 64 |
+
fp.add_argument('--out',dest='frontier_out',type=Path,default=None,help='Optional path to write the JSON receipt')
|
| 65 |
for name in ('run','train'):
|
| 66 |
p=sub.add_parser(name); p.add_argument('--steps',type=int,default=100); p.add_argument('--save')
|
| 67 |
p=sub.add_parser('serve'); p.add_argument('--port',type=int,default=8765); p.add_argument('--host',default='127.0.0.1')
|
|
|
|
| 164 |
if args.neuroweave_enabled is not None or args.neuroweave_config is not None:
|
| 165 |
from .neuroweave.cli_commands import cli_neuroweave_spec
|
| 166 |
config=replace(config,neuroweave=cli_neuroweave_spec(args.neuroweave_enabled,args.neuroweave_config,args.seed))
|
| 167 |
+
if (args.frontier_enabled is not None or args.frontier_config is not None
|
| 168 |
+
or args.frontier_modules is not None or args.frontier_graft_optimizer is not None):
|
| 169 |
+
from .frontier.cli_commands import cli_frontier_spec
|
| 170 |
+
frontier_spec=cli_frontier_spec(
|
| 171 |
+
args.frontier_enabled,args.frontier_config,args.seed,
|
| 172 |
+
modules=args.frontier_modules,graft_optimizer=args.frontier_graft_optimizer)
|
| 173 |
+
if frontier_spec is not None:
|
| 174 |
+
config=replace(config,frontier=frontier_spec)
|
| 175 |
if args.command=='serve' and args.nodes is None and not getattr(args, 'frontier_all', False):
|
| 176 |
import os
|
| 177 |
config=replace(config,
|
|
|
|
| 257 |
elif args.command=='neuroweave':
|
| 258 |
from .neuroweave.cli_commands import run_neuroweave_command
|
| 259 |
result=run_neuroweave_command(args,config)
|
| 260 |
+
elif args.command=='frontier':
|
| 261 |
+
from .frontier.cli_commands import run_frontier_command
|
| 262 |
+
result=run_frontier_command(args)
|
| 263 |
elif args.command=='connectome-inventory':
|
| 264 |
from .connectome_assets import get_source_inventory
|
| 265 |
result={'sources':get_source_inventory()}
|
|
|
|
| 660 |
result={**result,'measured':False,'evidence_kind':'illustrative',
|
| 661 |
'scope':'standalone synthetic inputs; no measured embodied performance; use planning-study or evidence for actual world trials'}
|
| 662 |
print(json.dumps(result,indent=2,allow_nan=False,default=str))
|
| 663 |
+
return 1 if (args.command in ('verify','adaptation-verify','planning-verify') and not result.get('ok',False)) or (args.command in ('neuroweave','frontier') and result.get('ok') is False) else 0
|
| 664 |
except (ValueError,TypeError,KeyError,OSError,RuntimeError) as exc:
|
| 665 |
parser.exit(2,f'Error: {exc}\n')
|
| 666 |
|
synapse/config.py
CHANGED
|
@@ -8,6 +8,26 @@ ROOT = Path(os.environ.get('SYNAPSE_HOME', str(PACKAGE.parent))).resolve()
|
|
| 8 |
VENDOR = PACKAGE / '_vendor'
|
| 9 |
ARTIFACTS = ROOT / 'artifacts'
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
@dataclass(frozen=True)
|
| 12 |
class SynapseConfig:
|
| 13 |
seed: int = 7
|
|
@@ -120,8 +140,14 @@ class SynapseConfig:
|
|
| 120 |
# NEUROWEAVE (synapse/neuroweave): same additive contract as DSAG. None is
|
| 121 |
# the default and is omitted from to_dict().
|
| 122 |
neuroweave: object | None = None
|
|
|
|
|
|
|
|
|
|
| 123 |
|
| 124 |
def __post_init__(self):
|
|
|
|
|
|
|
|
|
|
| 125 |
if self.neuroweave is not None:
|
| 126 |
from .neuroweave.spec import NeuroWeaveSpecV1
|
| 127 |
if isinstance(self.neuroweave, dict):
|
|
@@ -297,6 +323,7 @@ class SynapseConfig:
|
|
| 297 |
def max_tandem(cls, total_neurons: int = 9000, seed: int = 7, task: str = 'continental_biosphere', **kwargs) -> 'SynapseConfig':
|
| 298 |
"""Maximum configuration with every optional subsystem enabled."""
|
| 299 |
from .dsag.config import DSAGSpecV1
|
|
|
|
| 300 |
from .neuroweave.spec import NeuroWeaveSpecV1
|
| 301 |
|
| 302 |
cfg_dict = dict(
|
|
@@ -403,6 +430,8 @@ class SynapseConfig:
|
|
| 403 |
# Bounded population: Max Mode stays within the machine budget.
|
| 404 |
neuroweave=NeuroWeaveSpecV1.max_preset(
|
| 405 |
seed=seed, neurons=min(256, max(48, int(total_neurons) // 32))),
|
|
|
|
|
|
|
| 406 |
)
|
| 407 |
cfg_dict.update(kwargs)
|
| 408 |
return cls(**cfg_dict)
|
|
@@ -424,6 +453,10 @@ class SynapseConfig:
|
|
| 424 |
d.pop('neuroweave')
|
| 425 |
else:
|
| 426 |
d['neuroweave'] = self.neuroweave.to_dict()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 427 |
return d
|
| 428 |
|
| 429 |
def max_tandem_feature_audit(self):
|
|
@@ -453,6 +486,10 @@ class SynapseConfig:
|
|
| 453 |
enabled.append('neuroweave_v1')
|
| 454 |
enabled.extend(f'neuroweave_v1.{m}' for m in MECHANISM_IDS if m in neuroweave.mechanisms)
|
| 455 |
disabled.extend(f'neuroweave_v1.{m}' for m in MECHANISM_IDS if m not in neuroweave.mechanisms)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 456 |
return {
|
| 457 |
'schema': 'max-tandem-feature-audit-v1',
|
| 458 |
'enabled_count': len(enabled),
|
|
@@ -468,6 +505,7 @@ class SynapseConfig:
|
|
| 468 |
normalized = {
|
| 469 |
'dsag': None,
|
| 470 |
'neuroweave': None,
|
|
|
|
| 471 |
'experience_planning': False, 'surprise_memory': True, 'experience_horizon': 1,
|
| 472 |
'experimental_cognition': False, 'continual_backprop': False,
|
| 473 |
'fast_weight_memory': False, 'dormant_lifecycle': True,
|
|
@@ -527,6 +565,10 @@ class SynapseConfig:
|
|
| 527 |
return False
|
| 528 |
if not saved_nw_spec.enabled:
|
| 529 |
normalized['neuroweave'] = self.neuroweave
|
|
|
|
|
|
|
|
|
|
|
|
|
| 530 |
try:
|
| 531 |
restored = type(self)(**normalized)
|
| 532 |
except (TypeError, ValueError):
|
|
|
|
| 8 |
VENDOR = PACKAGE / '_vendor'
|
| 9 |
ARTIFACTS = ROOT / 'artifacts'
|
| 10 |
|
| 11 |
+
def tidal_checkpoint_path() -> Path:
|
| 12 |
+
"""Resolve the core in a source checkout, a configured home, or an installed wheel."""
|
| 13 |
+
source = ARTIFACTS / 'tidal_core.pt'
|
| 14 |
+
if source.is_file() or 'SYNAPSE_HOME' in os.environ:
|
| 15 |
+
return source
|
| 16 |
+
|
| 17 |
+
from importlib.metadata import PackageNotFoundError, distribution
|
| 18 |
+
relative = Path('share', 'synapse-connectome-lab', source.name)
|
| 19 |
+
target_install = PACKAGE.parent / relative
|
| 20 |
+
if target_install.is_file():
|
| 21 |
+
return target_install
|
| 22 |
+
try:
|
| 23 |
+
installed = distribution('synapse-connectome-lab')
|
| 24 |
+
except PackageNotFoundError:
|
| 25 |
+
return source
|
| 26 |
+
for entry in installed.files or ():
|
| 27 |
+
if entry.parts[-3:] == relative.parts:
|
| 28 |
+
return Path(installed.locate_file(entry))
|
| 29 |
+
return source
|
| 30 |
+
|
| 31 |
@dataclass(frozen=True)
|
| 32 |
class SynapseConfig:
|
| 33 |
seed: int = 7
|
|
|
|
| 140 |
# NEUROWEAVE (synapse/neuroweave): same additive contract as DSAG. None is
|
| 141 |
# the default and is omitted from to_dict().
|
| 142 |
neuroweave: object | None = None
|
| 143 |
+
# Frontier Pack (synapse/frontier): additive, default-off read-only
|
| 144 |
+
# observers and opt-in graft optimizer. Omitted from to_dict() when None.
|
| 145 |
+
frontier: object | None = None
|
| 146 |
|
| 147 |
def __post_init__(self):
|
| 148 |
+
if self.frontier is not None:
|
| 149 |
+
from .frontier.bridge import coerce_frontier_spec
|
| 150 |
+
object.__setattr__(self, 'frontier', coerce_frontier_spec(self.frontier))
|
| 151 |
if self.neuroweave is not None:
|
| 152 |
from .neuroweave.spec import NeuroWeaveSpecV1
|
| 153 |
if isinstance(self.neuroweave, dict):
|
|
|
|
| 323 |
def max_tandem(cls, total_neurons: int = 9000, seed: int = 7, task: str = 'continental_biosphere', **kwargs) -> 'SynapseConfig':
|
| 324 |
"""Maximum configuration with every optional subsystem enabled."""
|
| 325 |
from .dsag.config import DSAGSpecV1
|
| 326 |
+
from .frontier.spec import FrontierSpecV1
|
| 327 |
from .neuroweave.spec import NeuroWeaveSpecV1
|
| 328 |
|
| 329 |
cfg_dict = dict(
|
|
|
|
| 430 |
# Bounded population: Max Mode stays within the machine budget.
|
| 431 |
neuroweave=NeuroWeaveSpecV1.max_preset(
|
| 432 |
seed=seed, neurons=min(256, max(48, int(total_neurons) // 32))),
|
| 433 |
+
# Read-only frontier observers: strictly trajectory-neutral.
|
| 434 |
+
frontier=FrontierSpecV1.max_preset(seed=seed),
|
| 435 |
)
|
| 436 |
cfg_dict.update(kwargs)
|
| 437 |
return cls(**cfg_dict)
|
|
|
|
| 453 |
d.pop('neuroweave')
|
| 454 |
else:
|
| 455 |
d['neuroweave'] = self.neuroweave.to_dict()
|
| 456 |
+
if self.frontier is None:
|
| 457 |
+
d.pop('frontier')
|
| 458 |
+
else:
|
| 459 |
+
d['frontier'] = self.frontier.to_dict()
|
| 460 |
return d
|
| 461 |
|
| 462 |
def max_tandem_feature_audit(self):
|
|
|
|
| 486 |
enabled.append('neuroweave_v1')
|
| 487 |
enabled.extend(f'neuroweave_v1.{m}' for m in MECHANISM_IDS if m in neuroweave.mechanisms)
|
| 488 |
disabled.extend(f'neuroweave_v1.{m}' for m in MECHANISM_IDS if m not in neuroweave.mechanisms)
|
| 489 |
+
from .frontier.bridge import frontier_audit_entries
|
| 490 |
+
fr_on, fr_off = frontier_audit_entries(self.frontier)
|
| 491 |
+
enabled.extend(fr_on)
|
| 492 |
+
disabled.extend(fr_off)
|
| 493 |
return {
|
| 494 |
'schema': 'max-tandem-feature-audit-v1',
|
| 495 |
'enabled_count': len(enabled),
|
|
|
|
| 505 |
normalized = {
|
| 506 |
'dsag': None,
|
| 507 |
'neuroweave': None,
|
| 508 |
+
'frontier': None,
|
| 509 |
'experience_planning': False, 'surprise_memory': True, 'experience_horizon': 1,
|
| 510 |
'experimental_cognition': False, 'continual_backprop': False,
|
| 511 |
'fast_weight_memory': False, 'dormant_lifecycle': True,
|
|
|
|
| 565 |
return False
|
| 566 |
if not saved_nw_spec.enabled:
|
| 567 |
normalized['neuroweave'] = self.neuroweave
|
| 568 |
+
# Frontier observers follow the same additive rule when graft_optimizer stays default.
|
| 569 |
+
from .frontier.bridge import normalize_saved_frontier
|
| 570 |
+
if not normalize_saved_frontier(self.frontier, normalized):
|
| 571 |
+
return False
|
| 572 |
try:
|
| 573 |
restored = type(self)(**normalized)
|
| 574 |
except (TypeError, ValueError):
|
synapse/energy_efficiency_assay.py
CHANGED
|
@@ -45,7 +45,7 @@ class EnergyEfficiencyAssay:
|
|
| 45 |
self.num_steps = num_steps
|
| 46 |
self.seed = seed
|
| 47 |
|
| 48 |
-
def run_assay(self, thresholds:
|
| 49 |
if thresholds is None:
|
| 50 |
thresholds = [0.01, 0.05, 0.1, 0.2]
|
| 51 |
|
|
|
|
| 45 |
self.num_steps = num_steps
|
| 46 |
self.seed = seed
|
| 47 |
|
| 48 |
+
def run_assay(self, thresholds: list[float] | None = None) -> EnergyEfficiencyAssayReport:
|
| 49 |
if thresholds is None:
|
| 50 |
thresholds = [0.01, 0.05, 0.1, 0.2]
|
| 51 |
|
synapse/frontier/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Sonapse frontier pack: additive, default-off experimental modules (see ``spec.py``)."""
|
| 2 |
+
from .spec import (EVIDENCE_TIER, LAB_SCHEMA, MODULE_IDS, MODULES, OBSERVER_MODULE_IDS, FrontierSpecV1,
|
| 3 |
+
ModuleInfo, module_catalog)
|
| 4 |
+
from .extension import EXTENSION_INTERFACE_VERSION, EngineExtension, RandomTraceControl
|
| 5 |
+
|
| 6 |
+
__all__ = ['EVIDENCE_TIER', 'LAB_SCHEMA', 'MODULE_IDS', 'MODULES', 'OBSERVER_MODULE_IDS', 'FrontierSpecV1',
|
| 7 |
+
'ModuleInfo', 'module_catalog', 'EXTENSION_INTERFACE_VERSION', 'EngineExtension', 'RandomTraceControl']
|
synapse/frontier/anytime.py
ADDED
|
@@ -0,0 +1,511 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Anytime-valid inference (frontier module ``anytime_inference``).
|
| 2 |
+
|
| 3 |
+
Inspired by Ian Waudby-Smith and Aaditya Ramdas, *Estimating means of bounded random variables by
|
| 4 |
+
betting*, J. R. Stat. Soc. B 86(1):1-27 (February 2024), doi:10.1093/jrsssb/qkad009, and by Aaditya
|
| 5 |
+
Ramdas, Peter Grünwald, Vladimir Vovk and Glenn Shafer, *Game-theoretic statistics and safe
|
| 6 |
+
anytime-valid inference*, Statistical Science 38(4):576-601 (November 2023), doi:10.1214/23-STS894.
|
| 7 |
+
This module is a synthetic computational abstraction: it implements two constructions from the first
|
| 8 |
+
paper and checks their stated guarantees in seeded simulations; it reproduces none of the papers'
|
| 9 |
+
experiments. Full, verified references: ``docs/frontier/modules/anytime_inference.md``.
|
| 10 |
+
|
| 11 |
+
Betting confidence sequence (paper Sec. 4.4, Eqs. 24-26 and Theorem 3; section, equation and appendix
|
| 12 |
+
numbers follow arXiv:2010.09686v7, the version checked). Observations ``x_t`` in
|
| 13 |
+
``[lo, hi]`` are rescaled to ``X_t = (x_t - lo) / (hi - lo)`` in ``[0, 1]``; for each candidate mean ``m``
|
| 14 |
+
on a grid::
|
| 15 |
+
|
| 16 |
+
K+_t(m) = prod_{i<=t} (1 + lam+_i(m) (X_i - m)), K-_t(m) = prod_{i<=t} (1 - lam-_i(m) (X_i - m))
|
| 17 |
+
K±_t(m) = max{theta K+_t(m), (1 - theta) K-_t(m)}
|
| 18 |
+
lam+_t(m) = min(lam_t, c / m), lam-_t(m) = min(lam_t, c / (1 - m)) (Eq. 25)
|
| 19 |
+
lam_t = sqrt(2 log(2/alpha) / (sigma2_{t-1} t log(1 + t))) (Eq. 26)
|
| 20 |
+
mu_t = (1/2 + sum_{i<=t} X_i) / (t + 1), sigma2_t = (1/4 + sum_{i<=t} (X_i - mu_i)^2) / (t + 1)
|
| 21 |
+
CS_t = intersection_{i<=t} {m : K±_i(m) < 1/alpha}
|
| 22 |
+
|
| 23 |
+
The set is an interval (Theorem 3), so the grid search returns a conservative superset: each bound is
|
| 24 |
+
the first *excluded* grid point outside the included run (when no grid point is included, the excluded
|
| 25 |
+
neighbours of the grid minimisers of ``K±``, which bracket the set because ``K±`` is quasiconvex in ``m``).
|
| 26 |
+
|
| 27 |
+
Paired e-process for ``H0: E[D_t | D_1..D_{t-1}] = 0`` with ``|D_t| <= B``: with ``X_t = (1 + D_t/B)/2``
|
| 28 |
+
and ``m = 1/2``, ``E_t = (K+_t + K-_t) / 2`` (the paper's mixture ``M±`` with ``theta = 1/2``). Both
|
| 29 |
+
one-sided processes bet with the approximate-GRAPA rule (paper App. B.3) computed from the Eq. 26
|
| 30 |
+
estimators, split by sign: ``lam_t = clip((mu_{t-1} - m) / (sigma2_{t-1} + (mu_{t-1} - m)^2), -c/(1-m), c/m)``,
|
| 31 |
+
``lam+_t = max(lam_t, 0)``, ``lam-_t = max(-lam_t, 0)``. Every factor is at least ``1 - c > 0`` and the
|
| 32 |
+
bets are predictable, so under ``H0`` each one-sided process and their average are test martingales;
|
| 33 |
+
Ville's inequality gives ``P(exists t: E_t >= 1/alpha) <= alpha`` -- valid under optional stopping
|
| 34 |
+
(Ramdas et al. 2023).
|
| 35 |
+
|
| 36 |
+
All randomness comes from ``numpy.random.default_rng(seed + offset)``.
|
| 37 |
+
"""
|
| 38 |
+
from __future__ import annotations
|
| 39 |
+
|
| 40 |
+
import math
|
| 41 |
+
import time
|
| 42 |
+
from typing import Any, Mapping, Sequence
|
| 43 |
+
|
| 44 |
+
import numpy as np
|
| 45 |
+
|
| 46 |
+
from . import harness
|
| 47 |
+
|
| 48 |
+
__all__ = ['MODULE_ID', 'SOURCE', 'EXPERIMENTS', 'betting_confidence_sequence', 'paired_e_process',
|
| 49 |
+
'anytime_compare', 'naive_peeking_t_test', 'run_experiment']
|
| 50 |
+
|
| 51 |
+
MODULE_ID = 'anytime_inference'
|
| 52 |
+
SOURCE = ('Waudby-Smith & Ramdas, "Estimating means of bounded random variables by betting", J. R. Stat. Soc. B '
|
| 53 |
+
'86(1):1-27, February 2024, doi:10.1093/jrsssb/qkad009; Ramdas, Grünwald, Vovk & Shafer, '
|
| 54 |
+
'"Game-theoretic statistics and safe anytime-valid inference", Statistical Science 38(4):576-601, '
|
| 55 |
+
'November 2023, doi:10.1214/23-STS894')
|
| 56 |
+
|
| 57 |
+
_NULL_BERNOULLI_OFFSET = 83_003
|
| 58 |
+
_NULL_SKEWED_OFFSET = 83_011
|
| 59 |
+
_EFFECT_OFFSET = 83_021
|
| 60 |
+
_COVER_BETA_OFFSET = 83_029
|
| 61 |
+
_COVER_BERNOULLI_OFFSET = 83_041
|
| 62 |
+
_LOG_CAP = 690.0 # reported e-values are capped at exp(690) ~ 1e299, so every value stays finite
|
| 63 |
+
_MAX_N = 1_000_000
|
| 64 |
+
_MAX_CS_WORK = 200_000_000 # observations x grid points per confidence-sequence call
|
| 65 |
+
_MAX_SIM_CELLS = 4_000_000 # replicates x horizon per simulated scenario (about 20 such float64 arrays at peak)
|
| 66 |
+
_SKEW_A, _SKEW_B = 0.5, 4.0 # skewed null: D = Beta(0.5, 4) - 1/9 (mean exactly 0, values in [-1/9, 8/9])
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# ====================================================================== validation helpers
|
| 70 |
+
def _int(name: str, value: Any, low: int, high: int) -> int:
|
| 71 |
+
if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or not low <= int(value) <= high:
|
| 72 |
+
raise ValueError(f'{name} must be an int in [{low}, {high}]')
|
| 73 |
+
return int(value)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _num(name: str, value: Any, low: float, high: float, *, open_low: bool = False, open_high: bool = False) -> float:
|
| 77 |
+
if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)):
|
| 78 |
+
raise ValueError(f'{name} must be a number')
|
| 79 |
+
v = float(value)
|
| 80 |
+
if (not math.isfinite(v) or v < low or v > high or (open_low and v <= low) or (open_high and v >= high)):
|
| 81 |
+
raise ValueError(f'{name} must be a finite number in {"(" if open_low else "["}{low}, {high}{")" if open_high else "]"}')
|
| 82 |
+
return v
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _series(name: str, x: Any) -> np.ndarray:
|
| 86 |
+
if isinstance(x, (str, bytes)) or isinstance(x, Mapping):
|
| 87 |
+
raise ValueError(f'{name} must be a 1-D sequence of finite numbers')
|
| 88 |
+
try:
|
| 89 |
+
a = np.asarray(x, dtype=np.float64)
|
| 90 |
+
except (TypeError, ValueError) as exc:
|
| 91 |
+
raise ValueError(f'{name} must be a 1-D sequence of finite numbers') from exc
|
| 92 |
+
if a.ndim != 1 or a.size == 0 or a.size > _MAX_N or not np.all(np.isfinite(a)):
|
| 93 |
+
raise ValueError(f'{name} must be a non-empty 1-D sequence of at most {_MAX_N} finite numbers')
|
| 94 |
+
return a.copy()
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _alpha(alpha: Any) -> float:
|
| 98 |
+
return _num('alpha', alpha, 0.0, 1.0, open_low=True, open_high=True)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _c(c: Any) -> float:
|
| 102 |
+
return _num('c', c, 0.0, 1.0, open_low=True, open_high=True)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# ====================================================================== core (batched over rows)
|
| 106 |
+
def _plugin_moments(x: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
| 107 |
+
"""Predictable ``mu_{t-1}`` and ``sigma2_{t-1}`` (Eq. 26 estimators, priors 1/2 and 1/4) along the last axis."""
|
| 108 |
+
n = x.shape[-1]
|
| 109 |
+
t = np.arange(1, n + 1, dtype=np.float64)
|
| 110 |
+
mu = (0.5 + np.cumsum(x, axis=-1)) / (t + 1.0)
|
| 111 |
+
sig = (0.25 + np.cumsum((x - mu) ** 2, axis=-1)) / (t + 1.0)
|
| 112 |
+
lead = x.shape[:-1] + (1,)
|
| 113 |
+
mu_prev = np.concatenate([np.full(lead, 0.5), mu[..., :-1]], axis=-1)
|
| 114 |
+
sig_prev = np.concatenate([np.full(lead, 0.25), sig[..., :-1]], axis=-1)
|
| 115 |
+
return mu_prev, sig_prev
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _hedged_bounds(x: np.ndarray, alpha: float, grid_size: int, c: float,
|
| 119 |
+
theta: float) -> tuple[np.ndarray, np.ndarray]:
|
| 120 |
+
"""Per-time conservative bounds of ``{m : K±_t(m) < 1/alpha}`` for rows of ``x`` in [0, 1] (shape (R, n))."""
|
| 121 |
+
rows, n = x.shape
|
| 122 |
+
grid = np.linspace(0.0, 1.0, grid_size + 1)
|
| 123 |
+
with np.errstate(divide='ignore'):
|
| 124 |
+
cap_plus = np.where(grid > 0.0, c / np.where(grid > 0.0, grid, 1.0), np.inf)
|
| 125 |
+
cap_minus = np.where(grid < 1.0, c / np.where(grid < 1.0, 1.0 - grid, 1.0), np.inf)
|
| 126 |
+
_, sig_prev = _plugin_moments(x)
|
| 127 |
+
t = np.arange(1, n + 1, dtype=np.float64)
|
| 128 |
+
lam = np.sqrt(2.0 * math.log(2.0 / alpha) / (sig_prev * t * np.log1p(t)))
|
| 129 |
+
log_kp = np.zeros((rows, grid.size))
|
| 130 |
+
log_km = np.zeros((rows, grid.size))
|
| 131 |
+
thresh = math.log(1.0 / alpha)
|
| 132 |
+
log_theta, log_rest = math.log(theta), math.log(1.0 - theta)
|
| 133 |
+
lower = np.empty((rows, n))
|
| 134 |
+
upper = np.empty((rows, n))
|
| 135 |
+
last = grid.size - 1
|
| 136 |
+
rev = np.arange(grid.size)[::-1]
|
| 137 |
+
for i in range(n):
|
| 138 |
+
dev = x[:, i, None] - grid[None, :]
|
| 139 |
+
log_kp += np.log1p(np.minimum(lam[:, i, None], cap_plus) * dev)
|
| 140 |
+
log_km += np.log1p(-np.minimum(lam[:, i, None], cap_minus) * dev)
|
| 141 |
+
log_k = np.maximum(log_theta + log_kp, log_rest + log_km)
|
| 142 |
+
inside = log_k < thresh
|
| 143 |
+
any_in = inside.any(axis=1)
|
| 144 |
+
first = np.argmax(inside, axis=1)
|
| 145 |
+
final = last - np.argmax(inside[:, rev], axis=1)
|
| 146 |
+
# no grid point inside: bracket every grid minimiser (K± is quasiconvex in m, so the set lies there)
|
| 147 |
+
best_first = np.argmin(log_k, axis=1)
|
| 148 |
+
best_last = last - np.argmin(log_k[:, rev], axis=1)
|
| 149 |
+
lo_idx = np.where(any_in, first, best_first) - 1
|
| 150 |
+
hi_idx = np.where(any_in, final, best_last) + 1
|
| 151 |
+
lower[:, i] = grid[np.clip(lo_idx, 0, last)]
|
| 152 |
+
upper[:, i] = grid[np.clip(hi_idx, 0, last)]
|
| 153 |
+
return lower, upper
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def _paired_log_capital(y: np.ndarray, c: float) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 157 |
+
"""log K+, log K- and log E for rows of ``y = D / B`` in [-1, 1] (shape (R, n)); null mean m = 1/2 on X."""
|
| 158 |
+
x = 0.5 * (1.0 + y)
|
| 159 |
+
m = 0.5
|
| 160 |
+
mu_prev, sig_prev = _plugin_moments(x)
|
| 161 |
+
lam = np.clip((mu_prev - m) / (sig_prev + (mu_prev - m) ** 2), -c / (1.0 - m), c / m)
|
| 162 |
+
lam_plus = np.maximum(lam, 0.0)
|
| 163 |
+
lam_minus = np.maximum(-lam, 0.0)
|
| 164 |
+
log_kp = np.cumsum(np.log1p(lam_plus * (x - m)), axis=-1)
|
| 165 |
+
log_km = np.cumsum(np.log1p(-lam_minus * (x - m)), axis=-1)
|
| 166 |
+
log_e = np.logaddexp(log_kp, log_km) - math.log(2.0)
|
| 167 |
+
return log_kp, log_km, log_e
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def _cap_exp(log_v: np.ndarray) -> np.ndarray:
|
| 171 |
+
return np.exp(np.minimum(log_v, _LOG_CAP))
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
# ====================================================================== public API
|
| 175 |
+
def betting_confidence_sequence(x: Any, lo: float, hi: float, alpha: float = 0.05, *, grid_size: int = 1000,
|
| 176 |
+
c: float = 0.5, theta: float = 0.5) -> dict[str, Any]:
|
| 177 |
+
"""Hedged-capital betting confidence sequence for the mean of ``x`` (values in ``[lo, hi]``).
|
| 178 |
+
|
| 179 |
+
Returns ``lower``/``upper`` (running intersection, length ``n``), ``lower_raw``/``upper_raw`` (the set at
|
| 180 |
+
each time before intersecting), ``final`` = ``(lower[-1], upper[-1])`` and ``empty`` (the running
|
| 181 |
+
intersection became empty, which happens with probability at most ``alpha``). Bounds are conservative to
|
| 182 |
+
the grid resolution ``(hi - lo) / grid_size``."""
|
| 183 |
+
a = _series('x', x)
|
| 184 |
+
lo_v = _num('lo', lo, -1e12, 1e12)
|
| 185 |
+
hi_v = _num('hi', hi, -1e12, 1e12)
|
| 186 |
+
if not hi_v > lo_v:
|
| 187 |
+
raise ValueError('hi must be greater than lo')
|
| 188 |
+
if np.any(a < lo_v) or np.any(a > hi_v):
|
| 189 |
+
raise ValueError('every observation must lie in [lo, hi]')
|
| 190 |
+
al = _alpha(alpha)
|
| 191 |
+
g = _int('grid_size', grid_size, 8, 100_000)
|
| 192 |
+
cc = _c(c)
|
| 193 |
+
th = _num('theta', theta, 0.0, 1.0, open_low=True, open_high=True)
|
| 194 |
+
if a.size * (g + 1) > _MAX_CS_WORK:
|
| 195 |
+
raise ValueError(f'len(x) * (grid_size + 1) must be at most {_MAX_CS_WORK}')
|
| 196 |
+
width = hi_v - lo_v
|
| 197 |
+
unit = np.clip((a - lo_v) / width, 0.0, 1.0)
|
| 198 |
+
lower_raw, upper_raw = _hedged_bounds(unit[None, :], al, g, cc, th)
|
| 199 |
+
lower = np.maximum.accumulate(lower_raw[0])
|
| 200 |
+
upper = np.minimum.accumulate(upper_raw[0])
|
| 201 |
+
scale = lambda v: lo_v + width * v # noqa: E731
|
| 202 |
+
return {'n': int(a.size), 'alpha': al, 'lo': lo_v, 'hi': hi_v, 'grid_size': g, 'c': cc, 'theta': th,
|
| 203 |
+
'lower': scale(lower), 'upper': scale(upper), 'lower_raw': scale(lower_raw[0]),
|
| 204 |
+
'upper_raw': scale(upper_raw[0]), 'final': (float(scale(lower[-1])), float(scale(upper[-1]))),
|
| 205 |
+
'empty': bool(lower[-1] > upper[-1]), 'method': 'hedged_capital_predictable_plugin'}
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def paired_e_process(differences: Any, bound: float, *, c: float = 0.5) -> dict[str, Any]:
|
| 209 |
+
"""Two-sided betting e-process for ``H0: E[D_t | past] = 0`` from paired differences ``|D_t| <= bound``.
|
| 210 |
+
|
| 211 |
+
``e_process[t]`` is ``(K+ + K-) / 2`` after ``t + 1`` observations; ``e_plus`` / ``e_minus`` are the one-sided
|
| 212 |
+
processes (evidence for a positive / negative mean). Values are capped at ``exp(690)`` to stay finite."""
|
| 213 |
+
d = _series('differences', differences)
|
| 214 |
+
b = _num('bound', bound, 0.0, 1e12, open_low=True)
|
| 215 |
+
if np.any(np.abs(d) > b):
|
| 216 |
+
raise ValueError('every |difference| must be at most bound')
|
| 217 |
+
cc = _c(c)
|
| 218 |
+
log_kp, log_km, log_e = _paired_log_capital(np.clip(d / b, -1.0, 1.0)[None, :], cc)
|
| 219 |
+
return {'n': int(d.size), 'bound': b, 'c': cc, 'e_process': _cap_exp(log_e[0]), 'log_e_process': log_e[0],
|
| 220 |
+
'e_plus': _cap_exp(log_kp[0]), 'e_minus': _cap_exp(log_km[0]),
|
| 221 |
+
'method': 'two_sided_mixture_of_one_sided_agrapa_bets'}
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def anytime_compare(candidate: Any, reference: Any, *, bound: float, alpha: float = 0.05,
|
| 225 |
+
higher_is_better: bool = True, c: float = 0.5, grid_size: int = 1000) -> dict[str, Any]:
|
| 226 |
+
"""Anytime-valid paired comparison of two aligned score streams (``|candidate - reference| <= bound``).
|
| 227 |
+
|
| 228 |
+
The e-process is monitored after every observation; ``rejected`` is true when it reaches ``1/alpha``
|
| 229 |
+
(``stopped_at`` is that 1-based time and ``e_value`` the stopped value), so peeking never inflates the
|
| 230 |
+
type-I error beyond ``alpha`` provided ``E[D_t | past] = 0`` under the null. The direction comes from the
|
| 231 |
+
one-sided process that is at least ``1/alpha`` at the stopping time. ``cs_lower``/``cs_upper`` bound the
|
| 232 |
+
mean difference ``candidate - reference`` at the last observation (betting CS, level ``1 - alpha``)."""
|
| 233 |
+
a = _series('candidate', candidate)
|
| 234 |
+
r = _series('reference', reference)
|
| 235 |
+
if a.shape != r.shape:
|
| 236 |
+
raise ValueError('candidate and reference must have the same length')
|
| 237 |
+
if type(higher_is_better) is not bool:
|
| 238 |
+
raise ValueError('higher_is_better must be a boolean')
|
| 239 |
+
b = _num('bound', bound, 0.0, 1e12, open_low=True)
|
| 240 |
+
al = _alpha(alpha)
|
| 241 |
+
d = a - r
|
| 242 |
+
if np.any(np.abs(d) > b):
|
| 243 |
+
raise ValueError('every |candidate - reference| must be at most bound')
|
| 244 |
+
ep = paired_e_process(d, b, c=c)
|
| 245 |
+
cs = betting_confidence_sequence(d, -b, b, al, grid_size=grid_size, c=c)
|
| 246 |
+
log_e = ep['log_e_process']
|
| 247 |
+
crossed = np.flatnonzero(log_e >= math.log(1.0 / al))
|
| 248 |
+
rejected = bool(crossed.size)
|
| 249 |
+
stop = int(crossed[0]) if rejected else d.size - 1
|
| 250 |
+
direction = None
|
| 251 |
+
if rejected:
|
| 252 |
+
direction = 'positive' if ep['e_plus'][stop] >= ep['e_minus'][stop] else 'negative'
|
| 253 |
+
if not rejected:
|
| 254 |
+
verdict = 'no_detectable_difference'
|
| 255 |
+
else:
|
| 256 |
+
verdict = 'improved' if (direction == 'positive') == higher_is_better else 'worse'
|
| 257 |
+
return {'n': int(d.size), 'alpha': al, 'bound': b, 'higher_is_better': higher_is_better,
|
| 258 |
+
'mean_difference': float(d.mean()), 'e_value': float(ep['e_process'][stop]),
|
| 259 |
+
'e_value_final': float(ep['e_process'][-1]), 'rejected': rejected,
|
| 260 |
+
'stopped_at': stop + 1 if rejected else None, 'direction': direction,
|
| 261 |
+
'cs_lower': float(cs['lower'][-1]), 'cs_upper': float(cs['upper'][-1]),
|
| 262 |
+
'cs_excludes_zero': bool(cs['lower'][-1] > 0.0 or cs['upper'][-1] < 0.0), 'cs_empty': cs['empty'],
|
| 263 |
+
'verdict': verdict, 'method': 'betting_e_process_and_hedged_confidence_sequence'}
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def naive_peeking_t_test(differences: Any, alpha: float = 0.05, *, min_n: int = 2) -> dict[str, Any]:
|
| 267 |
+
"""The invalid baseline: a two-sided one-sample t-test of mean 0 repeated after every observation.
|
| 268 |
+
|
| 269 |
+
Returns whether any look at ``n >= min_n`` gave ``p < alpha`` and whether the single final look did."""
|
| 270 |
+
d = _series('differences', differences)
|
| 271 |
+
al = _alpha(alpha)
|
| 272 |
+
mn = _int('min_n', min_n, 2, _MAX_N)
|
| 273 |
+
any_look, final_look = _naive_t_rejections(d[None, :], al, mn)
|
| 274 |
+
return {'n': int(d.size), 'alpha': al, 'min_n': mn, 'rejected_any_look': bool(any_look[0]),
|
| 275 |
+
'rejected_final_look': bool(final_look[0])}
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def _naive_t_rejections(d: np.ndarray, alpha: float, min_n: int) -> tuple[np.ndarray, np.ndarray]:
|
| 279 |
+
from scipy.special import stdtrit # Student-t quantile (lighter import than scipy.stats)
|
| 280 |
+
rows, n = d.shape
|
| 281 |
+
if n < 2:
|
| 282 |
+
return np.zeros(rows, dtype=bool), np.zeros(rows, dtype=bool)
|
| 283 |
+
t = np.arange(1, n + 1, dtype=np.float64)
|
| 284 |
+
s1 = np.cumsum(d, axis=1)
|
| 285 |
+
s2 = np.cumsum(d * d, axis=1)
|
| 286 |
+
mean = s1 / t
|
| 287 |
+
with np.errstate(divide='ignore', invalid='ignore'):
|
| 288 |
+
var = np.maximum(s2 - t * mean * mean, 0.0) / np.maximum(t - 1.0, 1.0)
|
| 289 |
+
se = np.sqrt(var / t)
|
| 290 |
+
stat = np.where(se > 0.0, np.abs(mean) / np.where(se > 0.0, se, 1.0), 0.0)
|
| 291 |
+
crit = np.full(n, np.inf)
|
| 292 |
+
df = np.arange(1, n) # look at t = 2..n has df = t - 1
|
| 293 |
+
crit[1:] = stdtrit(df.astype(np.float64), 1.0 - alpha / 2.0)
|
| 294 |
+
looks = np.arange(1, n + 1) >= max(2, min_n)
|
| 295 |
+
reject = (stat > crit[None, :]) & looks[None, :]
|
| 296 |
+
return reject.any(axis=1), reject[:, -1]
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
# ====================================================================== validation experiment
|
| 300 |
+
_DEFAULTS: dict[str, Any] = {'alpha': 0.05, 'replicates': 400, 'horizon': 500, 'grid_size': 400, 'c': 0.5,
|
| 301 |
+
'theta': 0.5, 'naive_min_n': 10, 'null_p': 0.6, 'effect_p': 0.75, 'effect_reference_p': 0.5,
|
| 302 |
+
'cover_beta': (2.0, 5.0), 'cover_bernoulli_p': 0.3, 'power_min': 0.8, 'mc_z': 3.0}
|
| 303 |
+
_QUICK: dict[str, Any] = {'replicates': 100, 'horizon': 200, 'grid_size': 200}
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def _seeds(seeds: Any) -> tuple[int, ...]:
|
| 307 |
+
if isinstance(seeds, (str, bytes, Mapping)):
|
| 308 |
+
raise ValueError('seeds must be an iterable of ints')
|
| 309 |
+
try:
|
| 310 |
+
out = tuple(_int('seed', s, 0, 2**31 - 1) for s in seeds)
|
| 311 |
+
except TypeError as exc:
|
| 312 |
+
raise ValueError('seeds must be an iterable of ints') from exc
|
| 313 |
+
if not out or len(set(out)) != len(out):
|
| 314 |
+
raise ValueError('seeds must be non-empty and unique')
|
| 315 |
+
return out
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def _config(quick: bool, overrides: Mapping[str, Any]) -> dict[str, Any]:
|
| 319 |
+
unknown = sorted(set(overrides) - set(_DEFAULTS))
|
| 320 |
+
if unknown:
|
| 321 |
+
raise ValueError(f'unknown run_experiment parameters: {unknown}')
|
| 322 |
+
cfg = {**_DEFAULTS, **(_QUICK if quick else {}), **overrides}
|
| 323 |
+
cfg['alpha'] = _alpha(cfg['alpha'])
|
| 324 |
+
cfg['replicates'] = _int('replicates', cfg['replicates'], 10, 100_000)
|
| 325 |
+
cfg['horizon'] = _int('horizon', cfg['horizon'], 20, 100_000)
|
| 326 |
+
cfg['grid_size'] = _int('grid_size', cfg['grid_size'], 8, 100_000)
|
| 327 |
+
cfg['c'] = _c(cfg['c'])
|
| 328 |
+
cfg['theta'] = _num('theta', cfg['theta'], 0.0, 1.0, open_low=True, open_high=True)
|
| 329 |
+
cfg['naive_min_n'] = _int('naive_min_n', cfg['naive_min_n'], 2, cfg['horizon'])
|
| 330 |
+
for key in ('null_p', 'effect_p', 'effect_reference_p', 'cover_bernoulli_p'):
|
| 331 |
+
cfg[key] = _num(key, cfg[key], 0.0, 1.0, open_low=True, open_high=True)
|
| 332 |
+
if not cfg['effect_p'] > cfg['effect_reference_p']:
|
| 333 |
+
raise ValueError('effect_p must exceed effect_reference_p (the effect scenario is a positive difference)')
|
| 334 |
+
beta = cfg['cover_beta']
|
| 335 |
+
if isinstance(beta, (str, bytes)) or len(tuple(beta)) != 2:
|
| 336 |
+
raise ValueError('cover_beta must be a pair of positive numbers')
|
| 337 |
+
cfg['cover_beta'] = tuple(_num('cover_beta', v, 0.0, 1000.0, open_low=True) for v in beta)
|
| 338 |
+
cfg['power_min'] = _num('power_min', cfg['power_min'], 0.0, 1.0)
|
| 339 |
+
cfg['mc_z'] = _num('mc_z', cfg['mc_z'], 0.0, 10.0)
|
| 340 |
+
if cfg['replicates'] * (cfg['grid_size'] + 1) > 20_000_000:
|
| 341 |
+
raise ValueError('replicates * (grid_size + 1) must be at most 20,000,000 (memory bound)')
|
| 342 |
+
if cfg['replicates'] * cfg['horizon'] > _MAX_SIM_CELLS:
|
| 343 |
+
raise ValueError(f'replicates * horizon must be at most {_MAX_SIM_CELLS:,} (memory bound)')
|
| 344 |
+
return cfg
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def _paired_bernoulli(rng: np.random.Generator, shape: tuple[int, int], p_cand: float, p_ref: float) -> np.ndarray:
|
| 348 |
+
cand = (rng.random(shape) < p_cand).astype(np.float64)
|
| 349 |
+
ref = (rng.random(shape) < p_ref).astype(np.float64)
|
| 350 |
+
return cand - ref
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def _seed_block(seed: int, cfg: Mapping[str, Any]) -> dict[str, Any]:
|
| 354 |
+
r, n, al, cc = cfg['replicates'], cfg['horizon'], cfg['alpha'], cfg['c']
|
| 355 |
+
thresh = math.log(1.0 / al)
|
| 356 |
+
out: dict[str, Any] = {'seed': int(seed)}
|
| 357 |
+
# ---- nulls: e-process under optional stopping vs repeated t-tests
|
| 358 |
+
nulls = {
|
| 359 |
+
'paired_bernoulli': _paired_bernoulli(np.random.default_rng(seed + _NULL_BERNOULLI_OFFSET), (r, n),
|
| 360 |
+
cfg['null_p'], cfg['null_p']),
|
| 361 |
+
'skewed_continuous': (np.random.default_rng(seed + _NULL_SKEWED_OFFSET).beta(_SKEW_A, _SKEW_B, (r, n))
|
| 362 |
+
- _SKEW_A / (_SKEW_A + _SKEW_B)),
|
| 363 |
+
}
|
| 364 |
+
for name, d in nulls.items():
|
| 365 |
+
_, _, log_e = _paired_log_capital(d, cc)
|
| 366 |
+
naive_any, naive_final = _naive_t_rejections(d, al, cfg['naive_min_n'])
|
| 367 |
+
final_e = _cap_exp(log_e[:, -1])
|
| 368 |
+
out[f'null_{name}'] = {
|
| 369 |
+
'e_process_rejections': int(np.sum(log_e.max(axis=1) >= thresh)),
|
| 370 |
+
'naive_peeking_rejections': int(naive_any.sum()), 'fixed_n_t_rejections': int(naive_final.sum()),
|
| 371 |
+
'final_e_sum': float(final_e.sum()), 'final_e_sq_sum': float(np.sum(final_e ** 2)),
|
| 372 |
+
'final_e_max': float(final_e.max()), 'replicates': r}
|
| 373 |
+
# ---- power on a clear positive effect
|
| 374 |
+
d = _paired_bernoulli(np.random.default_rng(seed + _EFFECT_OFFSET), (r, n), cfg['effect_p'],
|
| 375 |
+
cfg['effect_reference_p'])
|
| 376 |
+
log_kp, log_km, log_e = _paired_log_capital(d, cc)
|
| 377 |
+
hit = log_e >= thresh
|
| 378 |
+
rejected = hit.any(axis=1)
|
| 379 |
+
stop = np.where(rejected, np.argmax(hit, axis=1), n - 1)
|
| 380 |
+
rows = np.arange(r)
|
| 381 |
+
positive = log_kp[rows, stop] >= log_km[rows, stop]
|
| 382 |
+
naive_any, _ = _naive_t_rejections(d, al, cfg['naive_min_n'])
|
| 383 |
+
out['effect'] = {'replicates': r, 'rejections': int(rejected.sum()),
|
| 384 |
+
'wrong_direction_rejections': int(np.sum(rejected & ~positive)),
|
| 385 |
+
'stopping_times': (stop[rejected] + 1).tolist(),
|
| 386 |
+
'naive_peeking_rejections': int(naive_any.sum())}
|
| 387 |
+
# ---- uniform-in-time coverage of the betting CS
|
| 388 |
+
a_beta, b_beta = cfg['cover_beta']
|
| 389 |
+
cover = {
|
| 390 |
+
'beta': (np.random.default_rng(seed + _COVER_BETA_OFFSET).beta(a_beta, b_beta, (r, n)), a_beta / (a_beta + b_beta)),
|
| 391 |
+
'bernoulli': ((np.random.default_rng(seed + _COVER_BERNOULLI_OFFSET).random((r, n))
|
| 392 |
+
< cfg['cover_bernoulli_p']).astype(np.float64), cfg['cover_bernoulli_p']),
|
| 393 |
+
}
|
| 394 |
+
for name, (x, mu) in cover.items():
|
| 395 |
+
lower_raw, upper_raw = _hedged_bounds(x, al, cfg['grid_size'], cc, cfg['theta'])
|
| 396 |
+
lower = np.maximum.accumulate(lower_raw, axis=1)
|
| 397 |
+
upper = np.minimum.accumulate(upper_raw, axis=1)
|
| 398 |
+
covered_all = np.all((lower <= mu) & (mu <= upper), axis=1)
|
| 399 |
+
early = min(n - 1, 19)
|
| 400 |
+
out[f'cover_{name}'] = {'replicates': r, 'true_mean': float(mu), 'covered_all_times': int(covered_all.sum()),
|
| 401 |
+
'width_t20_sum': float(np.sum(upper[:, early] - lower[:, early])),
|
| 402 |
+
'width_final_sum': float(np.sum(upper[:, -1] - lower[:, -1])),
|
| 403 |
+
'empty_final': int(np.sum(lower[:, -1] > upper[:, -1]))}
|
| 404 |
+
return out
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def _rate(k: int, n: int) -> dict[str, float]:
|
| 408 |
+
p = k / n
|
| 409 |
+
return {'rate': p, 'mc_se': math.sqrt(max(p * (1.0 - p), 1e-12) / n), 'count': int(k), 'n': int(n)}
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def run_experiment(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]:
|
| 413 |
+
"""Seeded validation of the e-process and the betting CS under continuous monitoring.
|
| 414 |
+
|
| 415 |
+
For every seed: ``replicates`` sequences of length ``horizon`` per scenario, with a look after every
|
| 416 |
+
observation. Checks (pooled over seeds; ``mc_z`` Monte-Carlo standard errors of slack):
|
| 417 |
+
|
| 418 |
+
* type-I error of the e-process <= ``alpha`` under two nulls (paired Bernoulli, skewed continuous);
|
| 419 |
+
* the naive repeated two-sided t-test (looks from ``naive_min_n``) exceeds ``alpha`` clearly;
|
| 420 |
+
* the mean final e-value under each null is <= 1 + slack (it is a test martingale with expectation exactly 1;
|
| 421 |
+
the terminal value is heavy-tailed, so the sample mean usually falls below 1 and the check is one-sided);
|
| 422 |
+
* the running-intersection CS covers the true mean at every time with frequency >= ``1 - alpha``
|
| 423 |
+
(Beta and Bernoulli data);
|
| 424 |
+
* power on a clear effect (paired Bernoulli ``effect_p`` vs ``effect_reference_p``) >= ``power_min`` and
|
| 425 |
+
wrong-direction rejections <= ``alpha``."""
|
| 426 |
+
if type(quick) is not bool:
|
| 427 |
+
raise ValueError('quick must be a boolean')
|
| 428 |
+
seed_list = _seeds(seeds)
|
| 429 |
+
cfg = _config(quick, overrides)
|
| 430 |
+
t0 = time.perf_counter()
|
| 431 |
+
blocks = [_seed_block(s, cfg) for s in seed_list]
|
| 432 |
+
wall = time.perf_counter() - t0
|
| 433 |
+
al, z = cfg['alpha'], cfg['mc_z']
|
| 434 |
+
total = cfg['replicates'] * len(seed_list)
|
| 435 |
+
results: dict[str, Any] = {}
|
| 436 |
+
checks: dict[str, bool] = {}
|
| 437 |
+
for name in ('paired_bernoulli', 'skewed_continuous'):
|
| 438 |
+
key = f'null_{name}'
|
| 439 |
+
e_rej = sum(b[key]['e_process_rejections'] for b in blocks)
|
| 440 |
+
naive = sum(b[key]['naive_peeking_rejections'] for b in blocks)
|
| 441 |
+
fixed = sum(b[key]['fixed_n_t_rejections'] for b in blocks)
|
| 442 |
+
e_sum = sum(b[key]['final_e_sum'] for b in blocks)
|
| 443 |
+
e_sq = sum(b[key]['final_e_sq_sum'] for b in blocks)
|
| 444 |
+
e_mean = e_sum / total
|
| 445 |
+
e_sd = math.sqrt(max(e_sq / total - e_mean ** 2, 0.0) * total / max(total - 1, 1))
|
| 446 |
+
alpha_se = math.sqrt(al * (1.0 - al) / total)
|
| 447 |
+
results[key] = {'e_process_type1': _rate(e_rej, total), 'naive_peeking_t_type1': _rate(naive, total),
|
| 448 |
+
'fixed_n_t_type1': _rate(fixed, total),
|
| 449 |
+
'final_e_value': {'mean': e_mean, 'sd': e_sd, 'mc_se': e_sd / math.sqrt(total),
|
| 450 |
+
'max': max(b[key]['final_e_max'] for b in blocks)}}
|
| 451 |
+
checks[f'e_process_type1_le_alpha_{name}'] = bool(e_rej / total <= al + z * alpha_se)
|
| 452 |
+
naive_rate = naive / total
|
| 453 |
+
naive_se = math.sqrt(max(naive_rate * (1.0 - naive_rate), 1e-12) / total)
|
| 454 |
+
checks[f'naive_peeking_t_exceeds_alpha_{name}'] = bool(naive_rate - z * naive_se > al)
|
| 455 |
+
checks[f'mean_final_e_value_le_1_{name}'] = bool(e_mean <= 1.0 + z * e_sd / math.sqrt(total))
|
| 456 |
+
rej = sum(b['effect']['rejections'] for b in blocks)
|
| 457 |
+
wrong = sum(b['effect']['wrong_direction_rejections'] for b in blocks)
|
| 458 |
+
times = sorted(t for b in blocks for t in b['effect']['stopping_times'])
|
| 459 |
+
results['effect'] = {'power': _rate(rej, total), 'wrong_direction': _rate(wrong, total),
|
| 460 |
+
'naive_peeking_t_rejections': _rate(sum(b['effect']['naive_peeking_rejections'] for b in blocks), total),
|
| 461 |
+
'median_stopping_time': float(np.median(times)) if times else None,
|
| 462 |
+
'mean_difference': cfg['effect_p'] - cfg['effect_reference_p']}
|
| 463 |
+
checks['power_on_clear_effect'] = bool(rej / total >= cfg['power_min'])
|
| 464 |
+
checks['wrong_direction_rate_le_alpha'] = bool(wrong / total <= al)
|
| 465 |
+
for name in ('beta', 'bernoulli'):
|
| 466 |
+
key = f'cover_{name}'
|
| 467 |
+
cov = sum(b[key]['covered_all_times'] for b in blocks)
|
| 468 |
+
results[key] = {'uniform_coverage': _rate(cov, total), 'true_mean': blocks[0][key]['true_mean'],
|
| 469 |
+
'mean_width_t20': sum(b[key]['width_t20_sum'] for b in blocks) / total,
|
| 470 |
+
'mean_width_final': sum(b[key]['width_final_sum'] for b in blocks) / total,
|
| 471 |
+
'empty_final': int(sum(b[key]['empty_final'] for b in blocks))}
|
| 472 |
+
checks[f'cs_uniform_coverage_ge_1_minus_alpha_{name}'] = bool(
|
| 473 |
+
cov / total >= 1.0 - al - z * math.sqrt(al * (1.0 - al) / total))
|
| 474 |
+
checks[f'cs_shrinks_{name}'] = bool(results[key]['mean_width_final'] < results[key]['mean_width_t20'])
|
| 475 |
+
n, g = cfg['horizon'], cfg['grid_size']
|
| 476 |
+
receipt = harness.base_receipt(MODULE_ID, 'validation', {
|
| 477 |
+
**cfg, 'seeds': list(seed_list), 'quick': quick, 'looks': 'after every observation',
|
| 478 |
+
'nulls': {'paired_bernoulli': f'D = Bern({cfg["null_p"]}) - Bern({cfg["null_p"]}), independent',
|
| 479 |
+
'skewed_continuous': f'D = Beta({_SKEW_A}, {_SKEW_B}) - {_SKEW_A / (_SKEW_A + _SKEW_B):.6f}'},
|
| 480 |
+
'effect': f'D = Bern({cfg["effect_p"]}) - Bern({cfg["effect_reference_p"]}), independent, bound 1',
|
| 481 |
+
'coverage': {'beta': f'X ~ Beta{tuple(cfg["cover_beta"])} on [0, 1]',
|
| 482 |
+
'bernoulli': f'X ~ Bern({cfg["cover_bernoulli_p"]})'},
|
| 483 |
+
'e_process': 'mean of one-sided aGRAPA betting processes on X = (1 + D)/2 at m = 1/2; reject when E_t >= 1/alpha',
|
| 484 |
+
'confidence_sequence': 'hedged capital (theta, c) with predictable plug-in bets; grid search; running intersection',
|
| 485 |
+
'naive_baseline': 'two-sided one-sample t-test at every look n >= naive_min_n'})
|
| 486 |
+
receipt['module'] = MODULE_ID
|
| 487 |
+
receipt['source'] = SOURCE
|
| 488 |
+
receipt['per_seed'] = [{k: v for k, v in b.items() if k != 'effect'} | {'effect': {
|
| 489 |
+
kk: vv for kk, vv in b['effect'].items() if kk != 'stopping_times'}} for b in blocks]
|
| 490 |
+
receipt['results'] = results
|
| 491 |
+
receipt['checks'] = checks
|
| 492 |
+
receipt['verdict'] = 'pass' if all(checks.values()) else 'fail'
|
| 493 |
+
receipt['verdict_basis'] = 'all_checks_pass' if receipt['verdict'] == 'pass' else 'failed_checks: ' + ', '.join(
|
| 494 |
+
k for k, v in checks.items() if not v)
|
| 495 |
+
receipt['estimated_cost'] = {'e_process_updates': 3 * total * n, 't_test_looks': 3 * total * n,
|
| 496 |
+
'cs_capital_updates': 2 * 2 * total * n * (g + 1)}
|
| 497 |
+
receipt['measured_wallclock_s'] = wall
|
| 498 |
+
receipt['notes'] = ('Synthetic Monte-Carlo validation of two constructions from Waudby-Smith & Ramdas (2024): the '
|
| 499 |
+
'hedged-capital confidence sequence with predictable plug-in bets (grid search, conservative to '
|
| 500 |
+
'one grid step) and a two-sided e-process (mean of two one-sided aGRAPA betting processes). '
|
| 501 |
+
'Guarantees hold when E[D_t | past] = 0 (for the e-process) and observations are bounded with a '
|
| 502 |
+
'constant conditional mean (for the CS); serially dependent streams whose conditional mean '
|
| 503 |
+
'drifts are not covered. Rates are Monte-Carlo estimates with stated standard errors. The '
|
| 504 |
+
'terminal e-value under a null is heavy-tailed (rare large values carry its expectation of '
|
| 505 |
+
'1), so its sample mean usually falls below 1 and its naive standard error understates the '
|
| 506 |
+
'spread; the exact expectation is checked by path enumeration in the tests. Nothing here '
|
| 507 |
+
'reproduces the papers\' experiments.')
|
| 508 |
+
return harness.seal(receipt)
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
EXPERIMENTS = {MODULE_ID: run_experiment}
|
synapse/frontier/bridge.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Sonapse host-integration bridge for the Frontier Pack (`SynapseConfig`, `IntegratedAgent`, `NeuralResidualGraft`).
|
| 2 |
+
|
| 3 |
+
Centralises the config, checkpoint, observer-stepping and graft-optimizer hooks so host wiring stays minimal,
|
| 4 |
+
additive and strictly trajectory-neutral when read-only observers are active.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
from collections.abc import Mapping
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
from .muon import make_graft_optimizer
|
| 12 |
+
from .runtime import FrontierObserverHub
|
| 13 |
+
from .spec import OBSERVER_MODULE_IDS, FrontierSpecV1
|
| 14 |
+
|
| 15 |
+
__all__ = [
|
| 16 |
+
'CHECKPOINT_NAMESPACE',
|
| 17 |
+
'coerce_frontier_spec',
|
| 18 |
+
'frontier_audit_entries',
|
| 19 |
+
'normalize_saved_frontier',
|
| 20 |
+
'attach_frontier_to_agent',
|
| 21 |
+
'step_agent_frontier',
|
| 22 |
+
'export_agent_frontier',
|
| 23 |
+
'import_agent_frontier',
|
| 24 |
+
]
|
| 25 |
+
|
| 26 |
+
CHECKPOINT_NAMESPACE = 'frontier_v1'
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def coerce_frontier_spec(value: Any) -> FrontierSpecV1 | None:
|
| 30 |
+
"""Validate/convert a ``SynapseConfig.frontier`` value (``None``, ``FrontierSpecV1`` or mapping)."""
|
| 31 |
+
if value is None:
|
| 32 |
+
return None
|
| 33 |
+
if isinstance(value, FrontierSpecV1):
|
| 34 |
+
return value
|
| 35 |
+
if isinstance(value, Mapping):
|
| 36 |
+
return FrontierSpecV1.from_dict(value)
|
| 37 |
+
raise ValueError('frontier must be None, a FrontierSpecV1 or a mapping')
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def frontier_audit_entries(spec: FrontierSpecV1 | None) -> tuple[list[str], list[str]]:
|
| 41 |
+
"""Return ``(enabled, disabled)`` feature-audit entries for ``SynapseConfig.max_tandem_feature_audit``."""
|
| 42 |
+
if spec is None or not spec.enabled:
|
| 43 |
+
return [], ['frontier_v1']
|
| 44 |
+
enabled = ['frontier_v1']
|
| 45 |
+
disabled: list[str] = []
|
| 46 |
+
for mod_id in OBSERVER_MODULE_IDS:
|
| 47 |
+
key = f'frontier_v1.{mod_id}'
|
| 48 |
+
if mod_id in spec.modules:
|
| 49 |
+
enabled.append(key)
|
| 50 |
+
else:
|
| 51 |
+
disabled.append(key)
|
| 52 |
+
return enabled, disabled
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def normalize_saved_frontier(current_spec: FrontierSpecV1 | None,
|
| 56 |
+
normalized_saved: dict[str, Any]) -> bool:
|
| 57 |
+
"""Apply the additive legacy-checkpoint rule (same as DSAG and NEUROWEAVE) in ``SynapseConfig.matches_saved``.
|
| 58 |
+
|
| 59 |
+
Returns ``False`` only when ``normalized_saved['frontier']`` is malformed; otherwise updates
|
| 60 |
+
``normalized_saved`` in place and returns ``True``."""
|
| 61 |
+
normalized_saved.setdefault('frontier', None)
|
| 62 |
+
saved_frontier = normalized_saved.get('frontier')
|
| 63 |
+
saved_spec: FrontierSpecV1 | None = None
|
| 64 |
+
if isinstance(saved_frontier, FrontierSpecV1):
|
| 65 |
+
saved_spec = saved_frontier
|
| 66 |
+
elif isinstance(saved_frontier, Mapping):
|
| 67 |
+
try:
|
| 68 |
+
saved_spec = FrontierSpecV1.from_dict(saved_frontier)
|
| 69 |
+
except (TypeError, ValueError):
|
| 70 |
+
return False
|
| 71 |
+
normalized_saved['frontier'] = saved_spec
|
| 72 |
+
elif saved_frontier is not None:
|
| 73 |
+
return False
|
| 74 |
+
|
| 75 |
+
# Read-only frontier observers can be additively enabled on a legacy checkpoint that had frontier disabled/None,
|
| 76 |
+
# provided graft_optimizer stays at its default ('adam').
|
| 77 |
+
if (current_spec is not None and current_spec.enabled
|
| 78 |
+
and current_spec.graft_optimizer == 'adam'
|
| 79 |
+
and (saved_spec is None or not saved_spec.enabled)):
|
| 80 |
+
normalized_saved['frontier'] = current_spec
|
| 81 |
+
return True
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def attach_frontier_to_agent(agent: Any, spec: FrontierSpecV1 | None = None) -> FrontierObserverHub | None:
|
| 85 |
+
"""Attach a :class:`FrontierObserverHub` and optional Muon graft optimizer to an ``IntegratedAgent``."""
|
| 86 |
+
active_spec = coerce_frontier_spec(getattr(getattr(agent, 'config', None), 'frontier', None)
|
| 87 |
+
if spec is None else spec)
|
| 88 |
+
if active_spec is None or not active_spec.enabled:
|
| 89 |
+
agent.frontier_hub = None
|
| 90 |
+
return None
|
| 91 |
+
n_units = int(agent.brain.n)
|
| 92 |
+
hub = FrontierObserverHub(active_spec, n_units=n_units)
|
| 93 |
+
agent.frontier_hub = hub
|
| 94 |
+
if active_spec.graft_optimizer == 'muon' and getattr(agent, 'neural_graft', None) is not None:
|
| 95 |
+
graft = agent.neural_graft
|
| 96 |
+
if graft.settings.get('optimizer_kind', 'adam') != 'muon':
|
| 97 |
+
lr = float(graft.settings.get('learning_rate', 3e-4))
|
| 98 |
+
graft.settings['optimizer_kind'] = 'muon'
|
| 99 |
+
graft.optimizer = make_graft_optimizer(graft.network, kind='muon', lr=lr)
|
| 100 |
+
return hub
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def step_agent_frontier(agent: Any) -> dict[str, Any] | None:
|
| 104 |
+
"""Feed a read-only copy of ``agent.brain.r`` to ``agent.frontier_hub`` and update ``agent.last_telemetry``."""
|
| 105 |
+
hub: FrontierObserverHub | None = getattr(agent, 'frontier_hub', None)
|
| 106 |
+
if hub is None or not hub.enabled:
|
| 107 |
+
return None
|
| 108 |
+
hub.observe(agent.brain.r)
|
| 109 |
+
summary = hub.telemetry()
|
| 110 |
+
if hasattr(agent, 'last_telemetry') and isinstance(agent.last_telemetry, dict):
|
| 111 |
+
agent.last_telemetry['frontier'] = summary
|
| 112 |
+
return summary
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def export_agent_frontier(agent: Any, state: dict[str, Any]) -> None:
|
| 116 |
+
"""Store ``state['frontier_v1']`` when an active ``frontier_hub`` is attached."""
|
| 117 |
+
hub: FrontierObserverHub | None = getattr(agent, 'frontier_hub', None)
|
| 118 |
+
if hub is not None and hub.enabled:
|
| 119 |
+
state[CHECKPOINT_NAMESPACE] = hub.export_state()
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def import_agent_frontier(agent: Any, state: Mapping[str, Any]) -> None:
|
| 123 |
+
"""Validate and restore ``state['frontier_v1']`` (allowing additive enable on legacy checkpoints)."""
|
| 124 |
+
hub: FrontierObserverHub | None = getattr(agent, 'frontier_hub', None)
|
| 125 |
+
saved_config = state.get('config')
|
| 126 |
+
saved_frontier = saved_config.get('frontier') if isinstance(saved_config, Mapping) else None
|
| 127 |
+
saved_enabled = (isinstance(saved_frontier, Mapping) and saved_frontier.get('enabled') is True) or (
|
| 128 |
+
isinstance(saved_frontier, FrontierSpecV1) and saved_frontier.enabled
|
| 129 |
+
)
|
| 130 |
+
payload = state.get(CHECKPOINT_NAMESPACE)
|
| 131 |
+
if payload is not None:
|
| 132 |
+
if not saved_enabled:
|
| 133 |
+
raise ValueError('checkpoint contains frontier_v1 state but its saved config does not enable frontier')
|
| 134 |
+
if hub is None or not hub.enabled:
|
| 135 |
+
raise ValueError('checkpoint contains frontier_v1 state but this agent has no enabled frontier hub')
|
| 136 |
+
hub.import_state(payload)
|
| 137 |
+
elif saved_enabled and hub is not None and hub.enabled:
|
| 138 |
+
raise ValueError('frontier-enabled checkpoint is missing its frontier_v1 namespace')
|
| 139 |
+
elif hub is not None and hub.enabled:
|
| 140 |
+
# Legacy checkpoint without frontier_v1: reset observer hub to clean seeded initial state.
|
| 141 |
+
hub.reset()
|
synapse/frontier/btsp.py
ADDED
|
@@ -0,0 +1,964 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""One-shot content-addressable memory with binary synapses and BTSP-style plasticity.
|
| 2 |
+
|
| 3 |
+
Inspired by Wu & Maass, "A simple model for Behavioral Time Scale Synaptic Plasticity (BTSP) provides content
|
| 4 |
+
addressable memory with binary synapses and one-shot learning", Nature Communications 16, 342 (published online
|
| 5 |
+
2 January 2025), https://doi.org/10.1038/s41467-024-55563-6. It is a small synthetic abstraction of that model, not
|
| 6 |
+
a reproduction of the paper's networks, parameters or results, and it says nothing about hippocampal biology.
|
| 7 |
+
|
| 8 |
+
Model (``BTSPMemory``)
|
| 9 |
+
----------------------
|
| 10 |
+
``m = input_dim`` binary input units feed ``n = memory_dim`` binary memory units through a fixed random
|
| 11 |
+
connectivity mask ``C`` (``n x m``, connection probability ``density``) carrying binary weights ``W`` (initially 0).
|
| 12 |
+
Storing a binary pattern ``x`` is one-shot (paper Eq. 1):
|
| 13 |
+
|
| 14 |
+
* every memory unit receives a plateau potential with probability ``plateau_prob``, independently of its firing;
|
| 15 |
+
* for every existing synapse ``(j, i)`` with a plateau in ``j`` and ``x_i = 1``, a weight at 0 flips to 1 with
|
| 16 |
+
probability ``p_ltp`` and a weight at 1 flips to 0 with probability ``p_ltd`` (the paper uses 0.5 for both);
|
| 17 |
+
nothing else changes.
|
| 18 |
+
|
| 19 |
+
Memory units are McCulloch-Pitts units, ``z_j = 1[(W x)_j > threshold * density * |x|]``, so the threshold is a
|
| 20 |
+
fraction of the expected number of connected active inputs. (The paper grid-searches one absolute threshold for its
|
| 21 |
+
memory-trace experiments and, for input completion, sets both layers' thresholds by fitted linear functions of the
|
| 22 |
+
average fraction of 1's; a threshold proportional to the active count is this module's simplification.)
|
| 23 |
+
Reconstruction uses the paper's feedback pathway: a second random mask ``D`` (``m x n``, same density) carries binary
|
| 24 |
+
weights ``B`` that are set to 1, right after each store, on every existing synapse whose memory unit is in the new
|
| 25 |
+
trace ``z(x)`` and whose input unit is active in ``x`` (one-shot Hebbian rule saturating at 1). Recall of a cue
|
| 26 |
+
``c`` gives the trace ``z(c)`` and the reconstruction ``r_i = 1[(B z(c))_i > feedback_threshold * density * |z(c)|]``.
|
| 27 |
+
|
| 28 |
+
``WillshawMemory`` is an auto-associative form of the classic clipped-Hebbian binary memory (Willshaw, Buneman &
|
| 29 |
+
Longuet-Higgins, Nature 222, 960-962, 1969; the paper does not compare BTSP with it, this module does) and
|
| 30 |
+
``RandomRecallControl`` returns a seeded random pattern (chance).
|
| 31 |
+
``run_capacity_benchmark`` compares them at the same synapse count; ``BTSPExtension`` attaches the memory to a
|
| 32 |
+
NEUROWEAVE engine as a readout-only extension.
|
| 33 |
+
"""
|
| 34 |
+
from __future__ import annotations
|
| 35 |
+
|
| 36 |
+
import base64
|
| 37 |
+
import binascii
|
| 38 |
+
import copy
|
| 39 |
+
import itertools
|
| 40 |
+
import math
|
| 41 |
+
import time
|
| 42 |
+
from typing import Any, Callable, Mapping, Sequence
|
| 43 |
+
|
| 44 |
+
import numpy as np
|
| 45 |
+
|
| 46 |
+
from .continuum_memory import _check_float, _check_int, _check_seeds, _grid_edges
|
| 47 |
+
from .extension import EngineExtension
|
| 48 |
+
|
| 49 |
+
__all__ = ['MODULE_ID', 'CAPACITY_ID', 'SOURCE', 'EXPERIMENTS', 'CUE_KINDS', 'BTSPMemory', 'WillshawMemory',
|
| 50 |
+
'RandomRecallControl', 'BTSPExtension', 'overlap', 'hamming', 'reconstruction_error', 'make_cue',
|
| 51 |
+
'random_patterns', 'run_capacity_benchmark', 'run_experiment', 'CAPACITY_DEFAULTS', 'CAPACITY_QUICK']
|
| 52 |
+
|
| 53 |
+
MODULE_ID = 'btsp_memory'
|
| 54 |
+
CAPACITY_ID = 'btsp_memory_capacity'
|
| 55 |
+
SOURCE = ('Wu & Maass, "A simple model for Behavioral Time Scale Synaptic Plasticity (BTSP) provides content '
|
| 56 |
+
'addressable memory with binary synapses and one-shot learning", Nature Communications 16, 342 (2025), '
|
| 57 |
+
'doi:10.1038/s41467-024-55563-6; baseline: Willshaw, Buneman & Longuet-Higgins, "Non-holographic '
|
| 58 |
+
'associative memory", Nature 222, 960-962 (1969), doi:10.1038/222960a0')
|
| 59 |
+
CUE_KINDS = ('delete', 'flip')
|
| 60 |
+
_MAX_MATRIX = 4_000_000
|
| 61 |
+
_MASK_OFFSET = 61_403
|
| 62 |
+
_PLASTICITY_OFFSET = 61_417
|
| 63 |
+
_PROJECTION_OFFSET = 61_429
|
| 64 |
+
_PATTERN_OFFSET = 61_441
|
| 65 |
+
_TEST_OFFSET = 61_453
|
| 66 |
+
_CONTROL_OFFSET = 61_467
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# ====================================================================== binary helpers and metrics
|
| 70 |
+
def _binary(name: str, value: Any, size: int) -> np.ndarray:
|
| 71 |
+
"""Validate a binary vector (bool or numbers in {0, 1}) of length ``size``; returns a new bool array."""
|
| 72 |
+
try:
|
| 73 |
+
arr = np.asarray(value)
|
| 74 |
+
except (TypeError, ValueError) as exc:
|
| 75 |
+
raise ValueError(f'{name} must be a binary vector') from exc
|
| 76 |
+
if arr.shape != (size,):
|
| 77 |
+
raise ValueError(f'{name} must have shape ({size},), got {arr.shape}')
|
| 78 |
+
if arr.dtype == np.bool_:
|
| 79 |
+
return arr.copy()
|
| 80 |
+
if not np.issubdtype(arr.dtype, np.number) or np.issubdtype(arr.dtype, np.complexfloating):
|
| 81 |
+
raise ValueError(f'{name} must be a binary vector')
|
| 82 |
+
if not np.all((arr == 0) | (arr == 1)):
|
| 83 |
+
raise ValueError(f'{name} must contain only 0 and 1')
|
| 84 |
+
return arr.astype(bool)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _pair(a: Any, b: Any) -> tuple[np.ndarray, np.ndarray]:
|
| 88 |
+
size = np.shape(a)
|
| 89 |
+
if len(size) != 1:
|
| 90 |
+
raise ValueError('expected two binary vectors of the same length')
|
| 91 |
+
return _binary('a', a, size[0]), _binary('b', b, size[0])
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def overlap(a: Any, b: Any) -> float:
|
| 95 |
+
"""Normalised overlap ``|a & b| / sqrt(|a| |b|)`` of two binary vectors (cosine similarity; 0 if one is empty).
|
| 96 |
+
|
| 97 |
+
This is the module's recall metric. It is not the paper's "overlap ratio" of two memory traces, which divides
|
| 98 |
+
the common 1's by the average number of 1's in a trace."""
|
| 99 |
+
x, y = _pair(a, b)
|
| 100 |
+
nx, ny = int(np.count_nonzero(x)), int(np.count_nonzero(y))
|
| 101 |
+
if nx == 0 or ny == 0:
|
| 102 |
+
return 0.0
|
| 103 |
+
return float(np.count_nonzero(x & y) / math.sqrt(nx * ny))
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def hamming(a: Any, b: Any) -> int:
|
| 107 |
+
"""Hamming distance between two binary vectors of the same length."""
|
| 108 |
+
x, y = _pair(a, b)
|
| 109 |
+
return int(np.count_nonzero(x ^ y))
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def reconstruction_error(target: Any, cue: Any, reconstruction: Any) -> float | None:
|
| 113 |
+
"""Wu & Maass's reconstruction error ``HD(r(x'), x) / HD(x, x')``: 0 is perfect, 1 is no better than the cue.
|
| 114 |
+
``None`` when the cue equals the target (the ratio is undefined)."""
|
| 115 |
+
base = hamming(target, cue)
|
| 116 |
+
return None if base == 0 else hamming(reconstruction, target) / base
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _check_generator(rng: Any) -> np.random.Generator:
|
| 120 |
+
if not isinstance(rng, np.random.Generator):
|
| 121 |
+
raise ValueError('rng must be a numpy.random.Generator (e.g. numpy.random.default_rng(seed))')
|
| 122 |
+
return rng
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def make_cue(pattern: Any, fraction: float, kind: str, rng: np.random.Generator) -> np.ndarray:
|
| 126 |
+
"""Degraded copy of a binary pattern: ``round(fraction * |x|)`` active bits are switched off and, for
|
| 127 |
+
``kind='flip'``, the same number of inactive bits are switched on (the number of ones is kept)."""
|
| 128 |
+
_check_generator(rng)
|
| 129 |
+
if len(np.shape(pattern)) != 1:
|
| 130 |
+
raise ValueError('pattern must be a binary vector')
|
| 131 |
+
x = _binary('pattern', pattern, np.shape(pattern)[0])
|
| 132 |
+
frac = _check_float('fraction', fraction, 0.0, 1.0)
|
| 133 |
+
if kind not in CUE_KINDS:
|
| 134 |
+
raise ValueError(f'kind must be one of {CUE_KINDS}')
|
| 135 |
+
on, off = np.flatnonzero(x), np.flatnonzero(~x)
|
| 136 |
+
k = int(round(frac * on.size))
|
| 137 |
+
if kind == 'flip' and k > off.size:
|
| 138 |
+
raise ValueError('not enough inactive bits to flip')
|
| 139 |
+
cue = x.copy()
|
| 140 |
+
if k:
|
| 141 |
+
cue[rng.choice(on, k, replace=False)] = False
|
| 142 |
+
if kind == 'flip':
|
| 143 |
+
cue[rng.choice(off, k, replace=False)] = True
|
| 144 |
+
return cue
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def random_patterns(count: int, size: int, active: int, rng: np.random.Generator) -> np.ndarray:
|
| 148 |
+
"""``count`` random binary patterns of length ``size`` with exactly ``active`` ones each, ``(count, size)``."""
|
| 149 |
+
_check_int('count', count, 0, 1_000_000)
|
| 150 |
+
_check_int('size', size, 1, 1_000_000)
|
| 151 |
+
_check_int('active', active, 0, size)
|
| 152 |
+
_check_generator(rng)
|
| 153 |
+
if count * size > 200_000_000: # the capacity benchmark's largest workload (100,000 x 2,000)
|
| 154 |
+
raise ValueError('count * size must be <= 200,000,000')
|
| 155 |
+
out = np.zeros((count, size), dtype=bool)
|
| 156 |
+
for row in out:
|
| 157 |
+
row[rng.choice(size, active, replace=False)] = True
|
| 158 |
+
return out
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _pack(bits: np.ndarray) -> str:
|
| 162 |
+
return base64.b64encode(np.packbits(bits.astype(bool)).tobytes()).decode('ascii')
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def _unpack(name: str, text: Any, count: int) -> np.ndarray:
|
| 166 |
+
if not isinstance(text, str):
|
| 167 |
+
raise ValueError(f'{name} must be a base64 string')
|
| 168 |
+
try:
|
| 169 |
+
raw = base64.b64decode(text.encode('ascii'), validate=True)
|
| 170 |
+
except (binascii.Error, UnicodeEncodeError, ValueError) as exc:
|
| 171 |
+
raise ValueError(f'{name} is not valid base64') from exc
|
| 172 |
+
if len(raw) != (count + 7) // 8:
|
| 173 |
+
raise ValueError(f'{name} has the wrong length')
|
| 174 |
+
bits = np.unpackbits(np.frombuffer(raw, dtype=np.uint8))
|
| 175 |
+
if np.any(bits[count:]):
|
| 176 |
+
raise ValueError(f'{name} has non-zero padding bits')
|
| 177 |
+
return bits[:count].astype(bool)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _rng_state(rng: np.random.Generator) -> dict[str, Any]:
|
| 181 |
+
return copy.deepcopy(rng.bit_generator.state)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _restore_rng(state: Any) -> np.random.Generator:
|
| 185 |
+
if not isinstance(state, Mapping) or state.get('bit_generator') != 'PCG64':
|
| 186 |
+
raise ValueError('rng state must be a PCG64 state mapping')
|
| 187 |
+
inner = state.get('state')
|
| 188 |
+
if (not isinstance(inner, Mapping) or type(inner.get('state')) is not int or type(inner.get('inc')) is not int
|
| 189 |
+
or type(state.get('has_uint32')) is not int or type(state.get('uinteger')) is not int):
|
| 190 |
+
raise ValueError('malformed PCG64 state')
|
| 191 |
+
rng = np.random.Generator(np.random.PCG64())
|
| 192 |
+
try:
|
| 193 |
+
rng.bit_generator.state = {'bit_generator': 'PCG64', 'state': {'state': inner['state'], 'inc': inner['inc']},
|
| 194 |
+
'has_uint32': state['has_uint32'], 'uinteger': state['uinteger']}
|
| 195 |
+
except (TypeError, ValueError, OverflowError) as exc:
|
| 196 |
+
raise ValueError('invalid PCG64 state') from exc
|
| 197 |
+
return rng
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def _flip_probs(value: Any) -> tuple[float, float]:
|
| 201 |
+
if isinstance(value, (list, tuple, np.ndarray)):
|
| 202 |
+
if np.ndim(value) != 1 or len(value) != 2:
|
| 203 |
+
raise ValueError('flip_prob must be a number or a (p_ltp, p_ltd) pair')
|
| 204 |
+
return (_check_float('flip_prob[0] (p_ltp)', value[0], 0.0, 1.0),
|
| 205 |
+
_check_float('flip_prob[1] (p_ltd)', value[1], 0.0, 1.0))
|
| 206 |
+
p = _check_float('flip_prob', value, 0.0, 1.0)
|
| 207 |
+
return p, p
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
# ====================================================================== BTSP memory
|
| 211 |
+
class BTSPMemory:
|
| 212 |
+
"""Binary feed-forward + feedback memory trained one-shot by plateau-gated stochastic flips (module docstring).
|
| 213 |
+
|
| 214 |
+
All randomness comes from ``seed``: the masks from ``default_rng(seed + 61403)`` and the plateau / flip draws
|
| 215 |
+
from ``default_rng(seed + 61417)``, so the same seed and the same store sequence give identical weights."""
|
| 216 |
+
|
| 217 |
+
def __init__(self, input_dim: int, memory_dim: int, *, density: float = 0.6, plateau_prob: float = 0.02,
|
| 218 |
+
flip_prob: float | Sequence[float] = 0.5, threshold: float = 0.35, feedback_threshold: float = 0.5,
|
| 219 |
+
seed: int = 0) -> None:
|
| 220 |
+
self.input_dim = _check_int('input_dim', input_dim, 1, 1_000_000)
|
| 221 |
+
self.memory_dim = _check_int('memory_dim', memory_dim, 1, 1_000_000)
|
| 222 |
+
if self.input_dim * self.memory_dim > _MAX_MATRIX:
|
| 223 |
+
raise ValueError(f'input_dim * memory_dim must be <= {_MAX_MATRIX:,}')
|
| 224 |
+
self.density = _check_float('density', density, 0.0, 1.0, low_open=True)
|
| 225 |
+
self.plateau_prob = _check_float('plateau_prob', plateau_prob, 0.0, 1.0)
|
| 226 |
+
self.p_ltp, self.p_ltd = _flip_probs(flip_prob)
|
| 227 |
+
self.threshold = _check_float('threshold', threshold, 0.0, 10.0)
|
| 228 |
+
self.feedback_threshold = _check_float('feedback_threshold', feedback_threshold, 0.0, 10.0)
|
| 229 |
+
self.seed = _check_int('seed', seed, 0, 2**31 - 1)
|
| 230 |
+
mask_rng = np.random.default_rng(self.seed + _MASK_OFFSET)
|
| 231 |
+
self._C = mask_rng.random((self.memory_dim, self.input_dim)) < self.density
|
| 232 |
+
self._D = mask_rng.random((self.input_dim, self.memory_dim)) < self.density
|
| 233 |
+
self.reset()
|
| 234 |
+
|
| 235 |
+
# ------------------------------------------------------------------ state
|
| 236 |
+
def reset(self) -> None:
|
| 237 |
+
"""Erase every memory (all weights 0) and restart the plasticity random stream."""
|
| 238 |
+
self.W = np.zeros((self.memory_dim, self.input_dim), dtype=bool)
|
| 239 |
+
self.B = np.zeros((self.input_dim, self.memory_dim), dtype=bool)
|
| 240 |
+
self._rng = np.random.default_rng(self.seed + _PLASTICITY_OFFSET)
|
| 241 |
+
self.stores = 0
|
| 242 |
+
self.plateaus = 0
|
| 243 |
+
self.ltp_flips = 0
|
| 244 |
+
self.ltd_flips = 0
|
| 245 |
+
|
| 246 |
+
@property
|
| 247 |
+
def forward_mask(self) -> np.ndarray:
|
| 248 |
+
return self._C.copy()
|
| 249 |
+
|
| 250 |
+
@property
|
| 251 |
+
def feedback_mask(self) -> np.ndarray:
|
| 252 |
+
return self._D.copy()
|
| 253 |
+
|
| 254 |
+
@property
|
| 255 |
+
def synapse_count(self) -> int:
|
| 256 |
+
"""Existing plastic binary synapses (forward plus feedback)."""
|
| 257 |
+
return int(np.count_nonzero(self._C) + np.count_nonzero(self._D))
|
| 258 |
+
|
| 259 |
+
@property
|
| 260 |
+
def state_numbers(self) -> int:
|
| 261 |
+
"""Stored numbers: binary weights and masks of both pathways plus four counters."""
|
| 262 |
+
return int(self.W.size + self.B.size + self._C.size + self._D.size + 4)
|
| 263 |
+
|
| 264 |
+
def weight_fractions(self) -> dict[str, float]:
|
| 265 |
+
"""Fraction of existing synapses at weight 1 in each pathway."""
|
| 266 |
+
c, d = max(1, int(np.count_nonzero(self._C))), max(1, int(np.count_nonzero(self._D)))
|
| 267 |
+
return {'forward': float(np.count_nonzero(self.W) / c), 'feedback': float(np.count_nonzero(self.B) / d)}
|
| 268 |
+
|
| 269 |
+
def config(self) -> dict[str, Any]:
|
| 270 |
+
return {'input_dim': self.input_dim, 'memory_dim': self.memory_dim, 'density': self.density,
|
| 271 |
+
'plateau_prob': self.plateau_prob, 'flip_prob': [self.p_ltp, self.p_ltd], 'threshold': self.threshold,
|
| 272 |
+
'feedback_threshold': self.feedback_threshold, 'seed': self.seed}
|
| 273 |
+
|
| 274 |
+
# ------------------------------------------------------------------ store / recall
|
| 275 |
+
def _code_idx(self, idx: np.ndarray) -> np.ndarray:
|
| 276 |
+
if idx.size == 0:
|
| 277 |
+
return np.zeros(self.memory_dim, dtype=bool)
|
| 278 |
+
drive = np.count_nonzero(self.W[:, idx], axis=1)
|
| 279 |
+
return drive > self.threshold * self.density * idx.size
|
| 280 |
+
|
| 281 |
+
def _reconstruct_idx(self, zi: np.ndarray) -> np.ndarray:
|
| 282 |
+
if zi.size == 0:
|
| 283 |
+
return np.zeros(self.input_dim, dtype=bool)
|
| 284 |
+
drive = np.count_nonzero(self.B[:, zi], axis=1)
|
| 285 |
+
return drive > self.feedback_threshold * self.density * zi.size
|
| 286 |
+
|
| 287 |
+
def store(self, pattern: Any, *, plateau_prob: float | None = None) -> dict[str, int]:
|
| 288 |
+
"""One-shot store of a binary pattern (``plateau_prob`` overrides the configured probability for this store).
|
| 289 |
+
|
| 290 |
+
Returns the number of plateau units, LTP (0 -> 1) and LTD (1 -> 0) flips, the new trace size and the number
|
| 291 |
+
of feedback synapses newly set to 1."""
|
| 292 |
+
x = _binary('pattern', pattern, self.input_dim)
|
| 293 |
+
p = self.plateau_prob if plateau_prob is None else _check_float('plateau_prob', plateau_prob, 0.0, 1.0)
|
| 294 |
+
idx = np.flatnonzero(x)
|
| 295 |
+
rows = np.flatnonzero(self._rng.random(self.memory_dim) < p)
|
| 296 |
+
ltp = ltd = 0
|
| 297 |
+
if rows.size and idx.size:
|
| 298 |
+
ix = np.ix_(rows, idx)
|
| 299 |
+
old = self.W[ix]
|
| 300 |
+
draw = self._rng.random(old.shape)
|
| 301 |
+
flip = self._C[ix] & (draw < np.where(old, self.p_ltd, self.p_ltp))
|
| 302 |
+
ltp = int(np.count_nonzero(flip & ~old))
|
| 303 |
+
ltd = int(np.count_nonzero(flip & old))
|
| 304 |
+
self.W[ix] = old ^ flip
|
| 305 |
+
zi = np.flatnonzero(self._code_idx(idx))
|
| 306 |
+
new_feedback = 0
|
| 307 |
+
if zi.size and idx.size:
|
| 308 |
+
ix = np.ix_(idx, zi)
|
| 309 |
+
before = self.B[ix]
|
| 310 |
+
after = before | self._D[ix]
|
| 311 |
+
new_feedback = int(np.count_nonzero(after & ~before))
|
| 312 |
+
self.B[ix] = after
|
| 313 |
+
self.stores += 1
|
| 314 |
+
self.plateaus += int(rows.size)
|
| 315 |
+
self.ltp_flips += ltp
|
| 316 |
+
self.ltd_flips += ltd
|
| 317 |
+
return {'plateau_units': int(rows.size), 'ltp_flips': ltp, 'ltd_flips': ltd, 'trace_size': int(zi.size),
|
| 318 |
+
'new_feedback_synapses': new_feedback}
|
| 319 |
+
|
| 320 |
+
def drive(self, cue: Any) -> np.ndarray:
|
| 321 |
+
"""Integer input of every memory unit, ``W c``."""
|
| 322 |
+
idx = np.flatnonzero(_binary('cue', cue, self.input_dim))
|
| 323 |
+
return np.count_nonzero(self.W[:, idx], axis=1).astype(np.int64)
|
| 324 |
+
|
| 325 |
+
def code(self, cue: Any) -> np.ndarray:
|
| 326 |
+
"""Memory trace ``z(c)`` (bool, length ``memory_dim``)."""
|
| 327 |
+
return self._code_idx(np.flatnonzero(_binary('cue', cue, self.input_dim)))
|
| 328 |
+
|
| 329 |
+
def reconstruct(self, code: Any) -> np.ndarray:
|
| 330 |
+
"""Feedback reconstruction ``r(z)`` of the input from a memory trace (bool, length ``input_dim``)."""
|
| 331 |
+
return self._reconstruct_idx(np.flatnonzero(_binary('code', code, self.memory_dim)))
|
| 332 |
+
|
| 333 |
+
def recall(self, cue: Any) -> dict[str, np.ndarray]:
|
| 334 |
+
"""``{'code': z(c), 'reconstruction': r(z(c))}`` (no state change)."""
|
| 335 |
+
z = self.code(cue)
|
| 336 |
+
return {'code': z, 'reconstruction': self._reconstruct_idx(np.flatnonzero(z))}
|
| 337 |
+
|
| 338 |
+
# ------------------------------------------------------------------ persistence
|
| 339 |
+
def export_state(self) -> dict[str, Any]:
|
| 340 |
+
"""JSON-safe state: weights on existing synapses (packed bits), counters and the plasticity RNG state."""
|
| 341 |
+
return {'config': self.config(), 'W_bits': _pack(self.W[self._C]), 'B_bits': _pack(self.B[self._D]),
|
| 342 |
+
'stores': int(self.stores), 'plateaus': int(self.plateaus), 'ltp_flips': int(self.ltp_flips),
|
| 343 |
+
'ltd_flips': int(self.ltd_flips), 'rng': _rng_state(self._rng)}
|
| 344 |
+
|
| 345 |
+
def import_state(self, state: Mapping[str, Any]) -> None:
|
| 346 |
+
"""Validate everything, then replace weights, counters and RNG (the configuration must match)."""
|
| 347 |
+
if not isinstance(state, Mapping):
|
| 348 |
+
raise ValueError('BTSP memory state must be a mapping')
|
| 349 |
+
if state.get('config') != self.config():
|
| 350 |
+
raise ValueError('BTSP memory state was made with a different configuration')
|
| 351 |
+
w_bits = _unpack('W_bits', state.get('W_bits'), int(np.count_nonzero(self._C)))
|
| 352 |
+
b_bits = _unpack('B_bits', state.get('B_bits'), int(np.count_nonzero(self._D)))
|
| 353 |
+
counters = {k: _check_int(k, state.get(k), 0, 2**62) for k in ('stores', 'plateaus', 'ltp_flips', 'ltd_flips')}
|
| 354 |
+
if counters['plateaus'] > counters['stores'] * self.memory_dim:
|
| 355 |
+
raise ValueError('plateau counter exceeds stores * memory_dim')
|
| 356 |
+
rng = _restore_rng(state.get('rng'))
|
| 357 |
+
W = np.zeros_like(self.W)
|
| 358 |
+
W[self._C] = w_bits
|
| 359 |
+
B = np.zeros_like(self.B)
|
| 360 |
+
B[self._D] = b_bits
|
| 361 |
+
self.W, self.B, self._rng = W, B, rng
|
| 362 |
+
self.stores, self.plateaus = counters['stores'], counters['plateaus']
|
| 363 |
+
self.ltp_flips, self.ltd_flips = counters['ltp_flips'], counters['ltd_flips']
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
# ====================================================================== comparison memories
|
| 367 |
+
class WillshawMemory:
|
| 368 |
+
"""Clipped-Hebbian auto-associative binary memory (Willshaw et al., 1969) with ``input_dim**2`` synapses.
|
| 369 |
+
|
| 370 |
+
``store`` sets ``A_ij = 1`` for every co-active pair (including ``i = j``); ``recall`` returns
|
| 371 |
+
``r_i = 1[(A c)_i >= threshold * |c|]`` (``threshold = 1`` is the classic all-cue-units rule)."""
|
| 372 |
+
|
| 373 |
+
def __init__(self, input_dim: int, *, threshold: float = 1.0) -> None:
|
| 374 |
+
self.input_dim = _check_int('input_dim', input_dim, 1, 1_000_000)
|
| 375 |
+
if self.input_dim ** 2 > _MAX_MATRIX:
|
| 376 |
+
raise ValueError(f'input_dim**2 must be <= {_MAX_MATRIX:,}')
|
| 377 |
+
self.threshold = _check_float('threshold', threshold, 0.0, 1.0, low_open=True)
|
| 378 |
+
self.reset()
|
| 379 |
+
|
| 380 |
+
def reset(self) -> None:
|
| 381 |
+
self.A = np.zeros((self.input_dim, self.input_dim), dtype=bool)
|
| 382 |
+
self.stores = 0
|
| 383 |
+
|
| 384 |
+
@property
|
| 385 |
+
def synapse_count(self) -> int:
|
| 386 |
+
return int(self.A.size)
|
| 387 |
+
|
| 388 |
+
def store(self, pattern: Any) -> dict[str, int]:
|
| 389 |
+
idx = np.flatnonzero(_binary('pattern', pattern, self.input_dim))
|
| 390 |
+
new = 0
|
| 391 |
+
if idx.size:
|
| 392 |
+
ix = np.ix_(idx, idx)
|
| 393 |
+
new = int(idx.size * idx.size - np.count_nonzero(self.A[ix]))
|
| 394 |
+
self.A[ix] = True
|
| 395 |
+
self.stores += 1
|
| 396 |
+
return {'new_synapses': new}
|
| 397 |
+
|
| 398 |
+
def recall(self, cue: Any) -> np.ndarray:
|
| 399 |
+
idx = np.flatnonzero(_binary('cue', cue, self.input_dim))
|
| 400 |
+
if idx.size == 0:
|
| 401 |
+
return np.zeros(self.input_dim, dtype=bool)
|
| 402 |
+
return np.count_nonzero(self.A[:, idx], axis=1) >= self.threshold * idx.size
|
| 403 |
+
|
| 404 |
+
def export_state(self) -> dict[str, Any]:
|
| 405 |
+
return {'config': {'input_dim': self.input_dim, 'threshold': self.threshold}, 'A_bits': _pack(self.A.ravel()),
|
| 406 |
+
'stores': int(self.stores)}
|
| 407 |
+
|
| 408 |
+
def import_state(self, state: Mapping[str, Any]) -> None:
|
| 409 |
+
if not isinstance(state, Mapping) or state.get('config') != {'input_dim': self.input_dim,
|
| 410 |
+
'threshold': self.threshold}:
|
| 411 |
+
raise ValueError('Willshaw state does not match this memory')
|
| 412 |
+
bits = _unpack('A_bits', state.get('A_bits'), self.input_dim ** 2).reshape(self.input_dim, self.input_dim)
|
| 413 |
+
if not np.array_equal(bits, bits.T):
|
| 414 |
+
raise ValueError('Willshaw matrix must be symmetric')
|
| 415 |
+
stores = _check_int('stores', state.get('stores'), 0, 2**62)
|
| 416 |
+
self.A, self.stores = bits, stores
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
class RandomRecallControl:
|
| 420 |
+
"""Chance control: 'recalls' a seeded random pattern with ``active`` ones and ignores the cue.
|
| 421 |
+
Its expected normalised overlap with any pattern of ``active`` ones is ``active / input_dim``."""
|
| 422 |
+
|
| 423 |
+
def __init__(self, input_dim: int, active: int, seed: int = 0) -> None:
|
| 424 |
+
self.input_dim = _check_int('input_dim', input_dim, 1, 1_000_000)
|
| 425 |
+
self.active = _check_int('active', active, 0, self.input_dim)
|
| 426 |
+
self.seed = _check_int('seed', seed, 0, 2**31 - 1)
|
| 427 |
+
self._rng = np.random.default_rng(self.seed + _CONTROL_OFFSET)
|
| 428 |
+
|
| 429 |
+
def store(self, pattern: Any) -> dict[str, int]:
|
| 430 |
+
_binary('pattern', pattern, self.input_dim)
|
| 431 |
+
return {}
|
| 432 |
+
|
| 433 |
+
def recall(self, cue: Any) -> np.ndarray:
|
| 434 |
+
_binary('cue', cue, self.input_dim)
|
| 435 |
+
out = np.zeros(self.input_dim, dtype=bool)
|
| 436 |
+
out[self._rng.choice(self.input_dim, self.active, replace=False)] = True
|
| 437 |
+
return out
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
# ====================================================================== engine extension
|
| 441 |
+
class BTSPExtension(EngineExtension):
|
| 442 |
+
"""Readout-only NEUROWEAVE extension around a :class:`BTSPMemory` over binarised brain output.
|
| 443 |
+
|
| 444 |
+
After each engine step the brain output (fixed at the first ``n`` units seen at :meth:`bind`; units born later
|
| 445 |
+
are ignored) is binarised by top-``k`` (``k = max(1, round(active_fraction * n))``, ties to the lower index).
|
| 446 |
+
The current pattern is used as a recall cue *before* any store, giving the features
|
| 447 |
+
|
| 448 |
+
* ``recall_overlap`` = ``overlap(x_t, r(z(x_t)))`` (familiarity of the current state),
|
| 449 |
+
* ``recall_confidence`` = ``min(1, |z(x_t)| / max(1, plateau_prob * memory_dim))`` (trace size relative to the
|
| 450 |
+
expected size of a stored trace),
|
| 451 |
+
* ``projection_dim`` fixed ``+-1`` projections of the trace, ``P z / sqrt(max(1, |z|))``.
|
| 452 |
+
|
| 453 |
+
Then, only when ``ctx['learn']`` is true, the pattern is stored one-shot if its salience
|
| 454 |
+
``max(|ctx['reward']|, 1 - recall_overlap)`` exceeds ``gate``, with plateau probability
|
| 455 |
+
``plateau_prob * min(1, salience)``. The drive is never changed."""
|
| 456 |
+
|
| 457 |
+
id = MODULE_ID
|
| 458 |
+
|
| 459 |
+
def __init__(self, memory_dim: int = 64, *, active_fraction: float = 0.25, density: float = 0.6,
|
| 460 |
+
plateau_prob: float = 0.1, flip_prob: float | Sequence[float] = 0.5, threshold: float = 0.35,
|
| 461 |
+
feedback_threshold: float = 0.5, gate: float = 0.5, projection_dim: int = 6, seed: int = 0) -> None:
|
| 462 |
+
self.memory_dim = _check_int('memory_dim', memory_dim, 1, 4096)
|
| 463 |
+
self.active_fraction = _check_float('active_fraction', active_fraction, 0.0, 1.0, low_open=True)
|
| 464 |
+
self.density = _check_float('density', density, 0.0, 1.0, low_open=True)
|
| 465 |
+
self.plateau_prob = _check_float('plateau_prob', plateau_prob, 0.0, 1.0)
|
| 466 |
+
self.flip_prob = list(_flip_probs(flip_prob))
|
| 467 |
+
self.threshold = _check_float('threshold', threshold, 0.0, 10.0)
|
| 468 |
+
self.feedback_threshold = _check_float('feedback_threshold', feedback_threshold, 0.0, 10.0)
|
| 469 |
+
self.gate = _check_float('gate', gate, 0.0, 1.0)
|
| 470 |
+
self.projection_dim = _check_int('projection_dim', projection_dim, 0, 64)
|
| 471 |
+
self.seed = _check_int('seed', seed, 0, 2**31 - 1)
|
| 472 |
+
self.feature_dim = 2 + self.projection_dim
|
| 473 |
+
prng = np.random.default_rng(self.seed + _PROJECTION_OFFSET)
|
| 474 |
+
self._P = np.where(prng.random((self.projection_dim, self.memory_dim)) < 0.5, -1.0, 1.0)
|
| 475 |
+
self._expected_trace = max(1.0, self.plateau_prob * self.memory_dim)
|
| 476 |
+
self._n = 0
|
| 477 |
+
self._k = 0
|
| 478 |
+
self.memory: BTSPMemory | None = None
|
| 479 |
+
self._clear_counters()
|
| 480 |
+
|
| 481 |
+
def _clear_counters(self) -> None:
|
| 482 |
+
self._features = np.zeros(self.feature_dim)
|
| 483 |
+
self._steps = 0
|
| 484 |
+
self._frozen_steps = 0
|
| 485 |
+
self._stores = 0
|
| 486 |
+
self._last = {'overlap': 0.0, 'confidence': 0.0, 'salience': 0.0, 'stored': False}
|
| 487 |
+
|
| 488 |
+
def _new_memory(self, n: int) -> BTSPMemory:
|
| 489 |
+
return BTSPMemory(n, self.memory_dim, density=self.density, plateau_prob=self.plateau_prob,
|
| 490 |
+
flip_prob=tuple(self.flip_prob), threshold=self.threshold,
|
| 491 |
+
feedback_threshold=self.feedback_threshold, seed=self.seed)
|
| 492 |
+
|
| 493 |
+
def _build(self, n: int) -> None:
|
| 494 |
+
self._n = n
|
| 495 |
+
self._k = max(1, int(round(self.active_fraction * n)))
|
| 496 |
+
self.memory = self._new_memory(n)
|
| 497 |
+
|
| 498 |
+
# ------------------------------------------------------------------ lifecycle
|
| 499 |
+
def bind(self, engine: Any) -> None:
|
| 500 |
+
"""Size the memory from ``engine.n`` (copied); the memory starts empty."""
|
| 501 |
+
n = getattr(engine, 'n', None)
|
| 502 |
+
if isinstance(n, (bool, np.bool_)) or not isinstance(n, (int, np.integer)):
|
| 503 |
+
raise ValueError('engine.n must be an int')
|
| 504 |
+
n = int(n)
|
| 505 |
+
if not 1 <= n <= 4096 or n * self.memory_dim > _MAX_MATRIX:
|
| 506 |
+
raise ValueError('engine size is out of range for the BTSP extension')
|
| 507 |
+
self._build(n)
|
| 508 |
+
self._clear_counters()
|
| 509 |
+
|
| 510 |
+
def reset(self) -> None:
|
| 511 |
+
"""Episode boundary: clear the current features (stored memories are kept)."""
|
| 512 |
+
self._features = np.zeros(self.feature_dim)
|
| 513 |
+
|
| 514 |
+
# ------------------------------------------------------------------ hooks
|
| 515 |
+
def binarise(self, output: Any) -> np.ndarray:
|
| 516 |
+
"""Top-``k`` binary pattern of the first ``n`` output values (zero-padded if the output is shorter)."""
|
| 517 |
+
if self.memory is None:
|
| 518 |
+
raise ValueError('BTSP extension is not bound to an engine')
|
| 519 |
+
try:
|
| 520 |
+
o = np.asarray(output, dtype=np.float64).ravel()
|
| 521 |
+
except (TypeError, ValueError) as exc:
|
| 522 |
+
raise ValueError('brain output must be numeric') from exc
|
| 523 |
+
if not np.all(np.isfinite(o)):
|
| 524 |
+
raise ValueError('brain output must be finite')
|
| 525 |
+
v = np.zeros(self._n)
|
| 526 |
+
m = min(self._n, o.size)
|
| 527 |
+
v[:m] = o[:m]
|
| 528 |
+
x = np.zeros(self._n, dtype=bool)
|
| 529 |
+
x[np.argsort(-v, kind='stable')[:self._k]] = True
|
| 530 |
+
return x
|
| 531 |
+
|
| 532 |
+
def after_step(self, output: np.ndarray, ctx: Mapping[str, Any]) -> None:
|
| 533 |
+
if not isinstance(ctx, Mapping):
|
| 534 |
+
raise ValueError('BTSP extension needs the engine step context')
|
| 535 |
+
learn = ctx.get('learn')
|
| 536 |
+
if type(learn) is not bool:
|
| 537 |
+
raise ValueError("ctx['learn'] must be a boolean")
|
| 538 |
+
reward = ctx.get('reward', 0.0)
|
| 539 |
+
if isinstance(reward, (bool, np.bool_)) or not isinstance(reward, (int, float, np.integer, np.floating)) \
|
| 540 |
+
or not math.isfinite(float(reward)):
|
| 541 |
+
raise ValueError("ctx['reward'] must be a finite number")
|
| 542 |
+
x = self.binarise(output)
|
| 543 |
+
mem = self.memory
|
| 544 |
+
z = mem._code_idx(np.flatnonzero(x))
|
| 545 |
+
zi = np.flatnonzero(z)
|
| 546 |
+
rec = mem._reconstruct_idx(zi)
|
| 547 |
+
ov = overlap(x, rec)
|
| 548 |
+
conf = min(1.0, zi.size / self._expected_trace)
|
| 549 |
+
proj = self._P @ z.astype(np.float64) / math.sqrt(max(1, zi.size)) if self.projection_dim else np.zeros(0)
|
| 550 |
+
self._features = np.clip(np.concatenate([[ov, conf], proj]), -10.0, 10.0)
|
| 551 |
+
salience = max(min(abs(float(reward)), 1.0), 1.0 - ov)
|
| 552 |
+
stored = False
|
| 553 |
+
if learn:
|
| 554 |
+
if salience > self.gate:
|
| 555 |
+
mem.store(x, plateau_prob=self.plateau_prob * min(1.0, salience))
|
| 556 |
+
self._stores += 1
|
| 557 |
+
stored = True
|
| 558 |
+
else:
|
| 559 |
+
self._frozen_steps += 1
|
| 560 |
+
self._last = {'overlap': float(ov), 'confidence': float(conf), 'salience': float(salience), 'stored': stored}
|
| 561 |
+
self._steps += 1
|
| 562 |
+
|
| 563 |
+
def features(self) -> np.ndarray:
|
| 564 |
+
return self._features.copy()
|
| 565 |
+
|
| 566 |
+
# ------------------------------------------------------------------ accounting / persistence
|
| 567 |
+
def parameter_count(self) -> int:
|
| 568 |
+
"""Plastic binary synapses of the memory (0 before :meth:`bind`)."""
|
| 569 |
+
return 0 if self.memory is None else self.memory.synapse_count
|
| 570 |
+
|
| 571 |
+
def state_numbers(self) -> int:
|
| 572 |
+
mem = 0 if self.memory is None else self.memory.state_numbers
|
| 573 |
+
return int(mem + self._P.size + self.feature_dim + 4)
|
| 574 |
+
|
| 575 |
+
def telemetry(self) -> dict[str, Any]:
|
| 576 |
+
out: dict[str, Any] = {'id': self.id, 'n': self._n, 'k': self._k, 'memory_dim': self.memory_dim,
|
| 577 |
+
'steps': self._steps, 'frozen_steps': self._frozen_steps, 'stores': self._stores,
|
| 578 |
+
'last_overlap': self._last['overlap'], 'last_confidence': self._last['confidence'],
|
| 579 |
+
'last_salience': self._last['salience'], 'last_stored': self._last['stored']}
|
| 580 |
+
if self.memory is not None:
|
| 581 |
+
out['weight_fractions'] = self.memory.weight_fractions()
|
| 582 |
+
out['synapses'] = self.memory.synapse_count
|
| 583 |
+
return out
|
| 584 |
+
|
| 585 |
+
def config(self) -> dict[str, Any]:
|
| 586 |
+
return {'memory_dim': self.memory_dim, 'active_fraction': self.active_fraction, 'density': self.density,
|
| 587 |
+
'plateau_prob': self.plateau_prob, 'flip_prob': list(self.flip_prob), 'threshold': self.threshold,
|
| 588 |
+
'feedback_threshold': self.feedback_threshold, 'gate': self.gate,
|
| 589 |
+
'projection_dim': self.projection_dim, 'seed': self.seed}
|
| 590 |
+
|
| 591 |
+
def export_state(self) -> dict[str, Any]:
|
| 592 |
+
return {'id': self.id, 'config': self.config(), 'n': self._n,
|
| 593 |
+
'memory': None if self.memory is None else self.memory.export_state(),
|
| 594 |
+
'features': self._features.tolist(), 'steps': self._steps, 'frozen_steps': self._frozen_steps,
|
| 595 |
+
'stores': self._stores, 'last': dict(self._last)}
|
| 596 |
+
|
| 597 |
+
def import_state(self, state: Mapping[str, Any]) -> None:
|
| 598 |
+
"""Validate fully, then restore. An unbound extension is sized from the state's ``n``."""
|
| 599 |
+
super().import_state(state)
|
| 600 |
+
if state.get('config') != self.config():
|
| 601 |
+
raise ValueError('BTSP extension state was made with a different configuration')
|
| 602 |
+
n = _check_int('n', state.get('n'), 0, 4096)
|
| 603 |
+
if self._n and n != self._n:
|
| 604 |
+
raise ValueError('BTSP extension state was made for a different engine size')
|
| 605 |
+
if n == 0:
|
| 606 |
+
if state.get('memory') is not None:
|
| 607 |
+
raise ValueError('unbound BTSP extension state cannot hold a memory')
|
| 608 |
+
memory = None
|
| 609 |
+
else:
|
| 610 |
+
if n * self.memory_dim > _MAX_MATRIX:
|
| 611 |
+
raise ValueError('engine size is out of range for the BTSP extension')
|
| 612 |
+
memory = self._new_memory(n)
|
| 613 |
+
memory.import_state(state.get('memory')) # validates fully before anything is replaced
|
| 614 |
+
try:
|
| 615 |
+
feats = np.asarray(state.get('features'), dtype=np.float64)
|
| 616 |
+
except (TypeError, ValueError) as exc:
|
| 617 |
+
raise ValueError('features must be numeric') from exc
|
| 618 |
+
if feats.shape != (self.feature_dim,) or not np.all(np.isfinite(feats)) \
|
| 619 |
+
or np.max(np.abs(feats), initial=0.0) > 10.0:
|
| 620 |
+
raise ValueError('features must be finite, in [-10, 10] and of length feature_dim')
|
| 621 |
+
steps = _check_int('steps', state.get('steps'), 0, 2**62)
|
| 622 |
+
frozen = _check_int('frozen_steps', state.get('frozen_steps'), 0, steps)
|
| 623 |
+
stores = _check_int('stores', state.get('stores'), 0, steps - frozen)
|
| 624 |
+
last = state.get('last')
|
| 625 |
+
if not isinstance(last, Mapping) or set(last) != {'overlap', 'confidence', 'salience', 'stored'} \
|
| 626 |
+
or type(last['stored']) is not bool:
|
| 627 |
+
raise ValueError('last must hold overlap, confidence, salience and stored')
|
| 628 |
+
last = {'overlap': _check_float('last.overlap', last['overlap'], 0.0, 1.0),
|
| 629 |
+
'confidence': _check_float('last.confidence', last['confidence'], 0.0, 1.0),
|
| 630 |
+
'salience': _check_float('last.salience', last['salience'], 0.0, 1.0), 'stored': last['stored']}
|
| 631 |
+
if n == 0 and (steps or feats.any() or last['stored']):
|
| 632 |
+
raise ValueError('an unbound BTSP extension cannot have stepped')
|
| 633 |
+
if n:
|
| 634 |
+
self._n, self._k = n, max(1, int(round(self.active_fraction * n)))
|
| 635 |
+
self.memory = memory
|
| 636 |
+
self._features = feats.copy()
|
| 637 |
+
self._steps, self._frozen_steps, self._stores, self._last = steps, frozen, stores, last
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
# ====================================================================== capacity benchmark
|
| 641 |
+
# Both arms' tuned optimum lies inside its grid at these sizes (measured 2026-11-19); receipts flag a chosen value
|
| 642 |
+
# that sits on a grid edge, because an under-tuned arm would make the comparison unfair.
|
| 643 |
+
CAPACITY_DEFAULTS: dict[str, Any] = {
|
| 644 |
+
'input_dim': 1000, 'active': 50, 'patterns': 400, 'checkpoints': 4, 'test_per_checkpoint': 64,
|
| 645 |
+
'cue_fractions': (0.3, 0.5), 'cue_kinds': ('delete', 'flip'), 'density': 0.6, 'flip_prob': 0.5,
|
| 646 |
+
'plateau_grid': (0.005, 0.01, 0.02, 0.04), 'threshold_grid': (0.25, 0.3, 0.35, 0.4),
|
| 647 |
+
'feedback_grid': (0.35, 0.5, 0.65, 0.8), 'willshaw_grid': (0.5, 0.6, 0.7, 0.8, 0.9, 1.0),
|
| 648 |
+
'tune_seeds': (1000, 1001)}
|
| 649 |
+
CAPACITY_QUICK: dict[str, Any] = {
|
| 650 |
+
'input_dim': 400, 'active': 20, 'patterns': 120, 'test_per_checkpoint': 24, 'plateau_grid': (0.02, 0.04, 0.08),
|
| 651 |
+
'threshold_grid': (0.3, 0.35, 0.4, 0.45), 'feedback_grid': (0.5, 0.65, 0.8), 'willshaw_grid': (0.5, 0.6, 0.8, 1.0),
|
| 652 |
+
'tune_seeds': (1000,)}
|
| 653 |
+
_BTSP_NATURAL_BOUNDS = {'plateau_prob': (1.0,), 'threshold': (0.0,), 'feedback_threshold': (0.0,)}
|
| 654 |
+
_WILLSHAW_NATURAL_BOUNDS = {'threshold': (1.0,)} # 1 = the classic all-cue-units rule (and the largest allowed)
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
def _grid(name: str, value: Any, low: float, high: float, *, low_open: bool = False) -> tuple[float, ...]:
|
| 658 |
+
try:
|
| 659 |
+
out = tuple(value)
|
| 660 |
+
except TypeError as exc:
|
| 661 |
+
raise ValueError(f'{name} must be a sequence of numbers') from exc
|
| 662 |
+
if not 1 <= len(out) <= 16:
|
| 663 |
+
raise ValueError(f'{name} must hold 1..16 values')
|
| 664 |
+
return tuple(_check_float(f'{name} entry', v, low, high, low_open=low_open) for v in out)
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
def _test_sets(seed: int, patterns: np.ndarray, loads: Sequence[int], per: int,
|
| 668 |
+
conditions: Sequence[tuple[float, str]]) -> list[dict[str, Any]]:
|
| 669 |
+
"""For each checkpoint: tested pattern indices and one cue per (condition, pattern), shared by every arm."""
|
| 670 |
+
sets = []
|
| 671 |
+
for j, load in enumerate(loads):
|
| 672 |
+
rng = np.random.default_rng(seed + _TEST_OFFSET + 7919 * j)
|
| 673 |
+
idx = np.sort(rng.choice(load, min(per, load), replace=False))
|
| 674 |
+
cues = {cond: np.stack([make_cue(patterns[i], cond[0], cond[1], rng) for i in idx]) for cond in conditions}
|
| 675 |
+
sets.append({'load': int(load), 'idx': idx, 'cues': cues})
|
| 676 |
+
return sets
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
def _cond_name(cond: tuple[float, str]) -> str:
|
| 680 |
+
return f'{cond[1]}_{cond[0]:g}'
|
| 681 |
+
|
| 682 |
+
|
| 683 |
+
def _score_recall(patterns: np.ndarray, test: Mapping[str, Any], recalls: Mapping[Any, Sequence[np.ndarray]]
|
| 684 |
+
) -> dict[str, dict[str, float | None]]:
|
| 685 |
+
out: dict[str, dict[str, float | None]] = {}
|
| 686 |
+
for cond, recs in recalls.items():
|
| 687 |
+
ovs, errs = [], []
|
| 688 |
+
for i, cue, rec in zip(test['idx'], test['cues'][cond], recs):
|
| 689 |
+
ovs.append(overlap(patterns[i], rec))
|
| 690 |
+
err = reconstruction_error(patterns[i], cue, rec)
|
| 691 |
+
if err is not None:
|
| 692 |
+
errs.append(err)
|
| 693 |
+
out[_cond_name(cond)] = {'overlap': float(np.mean(ovs)),
|
| 694 |
+
'reconstruction_error': float(np.mean(errs)) if errs else None}
|
| 695 |
+
return out
|
| 696 |
+
|
| 697 |
+
|
| 698 |
+
def _curve(per_ckpt: Sequence[Mapping[str, Mapping[str, Any]]]) -> float:
|
| 699 |
+
return float(np.mean([v['overlap'] for ck in per_ckpt for v in ck.values()]))
|
| 700 |
+
|
| 701 |
+
|
| 702 |
+
def _run_btsp(patterns: np.ndarray, tests: Sequence[Mapping[str, Any]], *, memory_dim: int, density: float,
|
| 703 |
+
flip_prob: float, plateau: float, threshold: float, feedback_grid: Sequence[float], seed: int,
|
| 704 |
+
diagnostics: bool = False) -> dict[str, Any]:
|
| 705 |
+
"""Store sequentially; at each checkpoint score every feedback threshold (it acts at recall only)."""
|
| 706 |
+
mem = BTSPMemory(patterns.shape[1], memory_dim, density=density, plateau_prob=plateau, flip_prob=flip_prob,
|
| 707 |
+
threshold=threshold, feedback_threshold=feedback_grid[0], seed=seed)
|
| 708 |
+
per_fb: dict[float, list[dict[str, Any]]] = {fb: [] for fb in feedback_grid}
|
| 709 |
+
diag = []
|
| 710 |
+
stored = 0
|
| 711 |
+
for test in tests:
|
| 712 |
+
while stored < test['load']:
|
| 713 |
+
mem.store(patterns[stored])
|
| 714 |
+
stored += 1
|
| 715 |
+
codes = {cond: [mem.code(c) for c in cues] for cond, cues in test['cues'].items()}
|
| 716 |
+
for fb in feedback_grid:
|
| 717 |
+
mem.feedback_threshold = fb
|
| 718 |
+
recs = {cond: [mem._reconstruct_idx(np.flatnonzero(z)) for z in zs] for cond, zs in codes.items()}
|
| 719 |
+
per_fb[fb].append(_score_recall(patterns, test, recs))
|
| 720 |
+
if diagnostics:
|
| 721 |
+
full = [mem.code(patterns[i]) for i in test['idx']]
|
| 722 |
+
diag.append({'load': test['load'], 'weight_fractions': mem.weight_fractions(),
|
| 723 |
+
'mean_trace_size': float(np.mean([np.count_nonzero(z) for z in full])),
|
| 724 |
+
'trace_overlap': {_cond_name(cond): float(np.mean([overlap(a, b) for a, b in zip(full, zs)]))
|
| 725 |
+
for cond, zs in codes.items()}})
|
| 726 |
+
return {'per_feedback': per_fb, 'diagnostics': diag, 'synapses': mem.synapse_count}
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
def _run_willshaw(patterns: np.ndarray, tests: Sequence[Mapping[str, Any]], grid: Sequence[float]
|
| 730 |
+
) -> dict[float, list[dict[str, Any]]]:
|
| 731 |
+
mem = WillshawMemory(patterns.shape[1], threshold=grid[0])
|
| 732 |
+
out: dict[float, list[dict[str, Any]]] = {th: [] for th in grid}
|
| 733 |
+
stored = 0
|
| 734 |
+
for test in tests:
|
| 735 |
+
while stored < test['load']:
|
| 736 |
+
mem.store(patterns[stored])
|
| 737 |
+
stored += 1
|
| 738 |
+
for th in grid:
|
| 739 |
+
mem.threshold = th
|
| 740 |
+
recs = {cond: [mem.recall(c) for c in cues] for cond, cues in test['cues'].items()}
|
| 741 |
+
out[th].append(_score_recall(patterns, test, recs))
|
| 742 |
+
return out
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
def _run_reference(patterns: np.ndarray, tests: Sequence[Mapping[str, Any]], *, active: int, seed: int
|
| 746 |
+
) -> dict[str, list[dict[str, Any]]]:
|
| 747 |
+
control = RandomRecallControl(patterns.shape[1], active, seed=seed)
|
| 748 |
+
rand, cue_only = [], []
|
| 749 |
+
for test in tests:
|
| 750 |
+
rand.append(_score_recall(patterns, test, {cond: [control.recall(c) for c in cues]
|
| 751 |
+
for cond, cues in test['cues'].items()}))
|
| 752 |
+
cue_only.append(_score_recall(patterns, test, {cond: list(cues) for cond, cues in test['cues'].items()}))
|
| 753 |
+
return {'random_recall': rand, 'cue_only': cue_only}
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
def run_capacity_benchmark(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any
|
| 757 |
+
) -> dict[str, Any]:
|
| 758 |
+
"""BTSP vs a Willshaw memory with the same synapse count vs a random-recall control.
|
| 759 |
+
|
| 760 |
+
``patterns`` random binary patterns with exactly ``active`` ones are stored one-shot, in order. At
|
| 761 |
+
``checkpoints`` evenly spaced loads, ``test_per_checkpoint`` stored patterns are recalled from degraded cues
|
| 762 |
+
(every ``cue_fractions`` x ``cue_kinds`` condition; the same cues for every arm). Metric: normalised overlap
|
| 763 |
+
between the stored pattern and its reconstruction, averaged over checkpoints and conditions (the mean of the
|
| 764 |
+
capacity curve). BTSP uses ``memory_dim = round(input_dim / (2 * density))`` memory units, so its forward plus
|
| 765 |
+
feedback synapses match the Willshaw matrix's ``input_dim**2`` in expectation (exact counts are reported).
|
| 766 |
+
Free parameters are tuned per arm on ``tune_seeds`` (disjoint from ``seeds``) by the same metric: plateau
|
| 767 |
+
probability, threshold and feedback threshold for BTSP, the threshold for Willshaw. Verdict: paired 95 % t
|
| 768 |
+
interval over seeds, BTSP vs Willshaw (higher is better)."""
|
| 769 |
+
from . import harness
|
| 770 |
+
if type(quick) is not bool:
|
| 771 |
+
raise ValueError('quick must be a boolean')
|
| 772 |
+
seeds = _check_seeds('seeds', seeds)
|
| 773 |
+
cfg = dict(CAPACITY_DEFAULTS)
|
| 774 |
+
if quick:
|
| 775 |
+
cfg.update(CAPACITY_QUICK)
|
| 776 |
+
unknown = sorted(set(overrides) - set(cfg))
|
| 777 |
+
if unknown:
|
| 778 |
+
raise ValueError(f'unknown run_capacity_benchmark overrides: {unknown}')
|
| 779 |
+
cfg.update(overrides)
|
| 780 |
+
m = _check_int('input_dim', cfg['input_dim'], 8, 2000)
|
| 781 |
+
a = _check_int('active', cfg['active'], 1, m // 2)
|
| 782 |
+
n_pat = _check_int('patterns', cfg['patterns'], 1, 100_000)
|
| 783 |
+
n_ck = _check_int('checkpoints', cfg['checkpoints'], 1, min(16, n_pat))
|
| 784 |
+
per = _check_int('test_per_checkpoint', cfg['test_per_checkpoint'], 1, 4096)
|
| 785 |
+
density = _check_float('density', cfg['density'], 0.0, 1.0, low_open=True)
|
| 786 |
+
flip = _check_float('flip_prob', cfg['flip_prob'], 0.0, 1.0)
|
| 787 |
+
fracs = _grid('cue_fractions', cfg['cue_fractions'], 0.0, 1.0)
|
| 788 |
+
try:
|
| 789 |
+
kinds = tuple(cfg['cue_kinds'])
|
| 790 |
+
except TypeError as exc:
|
| 791 |
+
raise ValueError(f'cue_kinds must be distinct values from {CUE_KINDS}') from exc
|
| 792 |
+
if not kinds or any(k not in CUE_KINDS for k in kinds) or len(set(kinds)) != len(kinds):
|
| 793 |
+
raise ValueError(f'cue_kinds must be distinct values from {CUE_KINDS}')
|
| 794 |
+
plateau_grid = _grid('plateau_grid', cfg['plateau_grid'], 0.0, 1.0, low_open=True)
|
| 795 |
+
threshold_grid = _grid('threshold_grid', cfg['threshold_grid'], 0.0, 10.0)
|
| 796 |
+
feedback_grid = _grid('feedback_grid', cfg['feedback_grid'], 0.0, 10.0)
|
| 797 |
+
willshaw_grid = _grid('willshaw_grid', cfg['willshaw_grid'], 0.0, 1.0, low_open=True)
|
| 798 |
+
tune_seeds = _check_seeds('tune_seeds', cfg['tune_seeds'])
|
| 799 |
+
if set(tune_seeds) & set(seeds):
|
| 800 |
+
raise ValueError('tune_seeds must be disjoint from seeds')
|
| 801 |
+
memory_dim = max(1, int(round(m / (2.0 * density))))
|
| 802 |
+
if m * memory_dim > _MAX_MATRIX:
|
| 803 |
+
raise ValueError('input_dim / density gives a BTSP memory that is too large')
|
| 804 |
+
conditions = [(f, k) for k in kinds for f in fracs]
|
| 805 |
+
loads = sorted({max(1, int(round(n_pat * (j + 1) / n_ck))) for j in range(n_ck)})
|
| 806 |
+
cfg.update({'input_dim': m, 'active': a, 'patterns': n_pat, 'checkpoints': n_ck, 'test_per_checkpoint': per,
|
| 807 |
+
'density': density, 'flip_prob': flip, 'cue_fractions': fracs, 'cue_kinds': kinds,
|
| 808 |
+
'plateau_grid': plateau_grid, 'threshold_grid': threshold_grid, 'feedback_grid': feedback_grid,
|
| 809 |
+
'willshaw_grid': willshaw_grid, 'tune_seeds': tune_seeds})
|
| 810 |
+
|
| 811 |
+
def workload(seed: int) -> tuple[np.ndarray, list[dict[str, Any]]]:
|
| 812 |
+
pats = random_patterns(n_pat, m, a, np.random.default_rng(seed + _PATTERN_OFFSET))
|
| 813 |
+
return pats, _test_sets(seed, pats, loads, per, conditions)
|
| 814 |
+
|
| 815 |
+
t0 = time.perf_counter()
|
| 816 |
+
tune_work = {s: workload(s) for s in tune_seeds}
|
| 817 |
+
btsp_table: list[dict[str, Any]] = []
|
| 818 |
+
for plateau, threshold in itertools.product(plateau_grid, threshold_grid):
|
| 819 |
+
runs = [_run_btsp(*tune_work[s], memory_dim=memory_dim, density=density, flip_prob=flip, plateau=plateau,
|
| 820 |
+
threshold=threshold, feedback_grid=feedback_grid, seed=s)['per_feedback']
|
| 821 |
+
for s in tune_seeds]
|
| 822 |
+
for fb in feedback_grid:
|
| 823 |
+
btsp_table.append({'plateau_prob': plateau, 'threshold': threshold, 'feedback_threshold': fb,
|
| 824 |
+
'tune_score': float(np.mean([_curve(r[fb]) for r in runs]))})
|
| 825 |
+
will_runs = [_run_willshaw(*tune_work[s], willshaw_grid) for s in tune_seeds]
|
| 826 |
+
will_table = [{'threshold': th, 'tune_score': float(np.mean([_curve(r[th]) for r in will_runs]))}
|
| 827 |
+
for th in willshaw_grid]
|
| 828 |
+
b_best = btsp_table[max(range(len(btsp_table)), key=lambda i: (btsp_table[i]['tune_score'], -i))]
|
| 829 |
+
w_best = will_table[max(range(len(will_table)), key=lambda i: (will_table[i]['tune_score'], -i))]
|
| 830 |
+
b_chosen = {k: b_best[k] for k in ('plateau_prob', 'threshold', 'feedback_threshold')}
|
| 831 |
+
b_edges = _grid_edges(b_chosen, {'plateau_prob': plateau_grid, 'threshold': threshold_grid,
|
| 832 |
+
'feedback_threshold': feedback_grid}, _BTSP_NATURAL_BOUNDS)
|
| 833 |
+
w_edges = _grid_edges({'threshold': w_best['threshold']}, {'threshold': willshaw_grid}, _WILLSHAW_NATURAL_BOUNDS)
|
| 834 |
+
tune_wall = time.perf_counter() - t0
|
| 835 |
+
|
| 836 |
+
t1 = time.perf_counter()
|
| 837 |
+
per_seed = []
|
| 838 |
+
for s in seeds:
|
| 839 |
+
pats, tests = workload(s)
|
| 840 |
+
b = _run_btsp(pats, tests, memory_dim=memory_dim, density=density, flip_prob=flip,
|
| 841 |
+
plateau=b_best['plateau_prob'], threshold=b_best['threshold'],
|
| 842 |
+
feedback_grid=(b_best['feedback_threshold'],), seed=s, diagnostics=True)
|
| 843 |
+
w = _run_willshaw(pats, tests, (w_best['threshold'],))[w_best['threshold']]
|
| 844 |
+
ref = _run_reference(pats, tests, active=a, seed=s)
|
| 845 |
+
arms = {'btsp': b['per_feedback'][b_best['feedback_threshold']], 'willshaw': w,
|
| 846 |
+
'random_recall': ref['random_recall'], 'cue_only': ref['cue_only']}
|
| 847 |
+
per_seed.append({'seed': int(s), 'btsp_synapses': b['synapses'], 'btsp_diagnostics': b['diagnostics'],
|
| 848 |
+
'curve_mean_overlap': {arm: _curve(v) for arm, v in arms.items()},
|
| 849 |
+
'per_checkpoint': {arm: [{'load': t['load'], **ck} for t, ck in zip(tests, v)]
|
| 850 |
+
for arm, v in arms.items()}})
|
| 851 |
+
eval_wall = time.perf_counter() - t1
|
| 852 |
+
|
| 853 |
+
def vals(arm: str) -> list[float]:
|
| 854 |
+
return [r['curve_mean_overlap'][arm] for r in per_seed]
|
| 855 |
+
|
| 856 |
+
comparisons = {'btsp_vs_willshaw': harness.compare(vals('btsp'), vals('willshaw')),
|
| 857 |
+
'btsp_vs_random_recall': harness.compare(vals('btsp'), vals('random_recall')),
|
| 858 |
+
'willshaw_vs_random_recall': harness.compare(vals('willshaw'), vals('random_recall')),
|
| 859 |
+
'btsp_vs_cue_only': harness.compare(vals('btsp'), vals('cue_only')),
|
| 860 |
+
'willshaw_vs_cue_only': harness.compare(vals('willshaw'), vals('cue_only'))}
|
| 861 |
+
arm_names = ('btsp', 'willshaw', 'random_recall', 'cue_only')
|
| 862 |
+
summary = {arm: {'curve_mean_overlap': float(np.mean(vals(arm))),
|
| 863 |
+
'overlap_by_load': [float(np.mean([r['per_checkpoint'][arm][j][_cond_name(c)]['overlap']
|
| 864 |
+
for r in per_seed for c in conditions]))
|
| 865 |
+
for j in range(len(loads))]}
|
| 866 |
+
for arm in arm_names}
|
| 867 |
+
btsp_syn = [r['btsp_synapses'] for r in per_seed]
|
| 868 |
+
receipt = harness.base_receipt(CAPACITY_ID, 'memory_benchmark', {
|
| 869 |
+
**{k: (list(v) if isinstance(v, tuple) else v) for k, v in cfg.items()}, 'seeds': list(seeds), 'quick': quick,
|
| 870 |
+
'loads': loads, 'conditions': [_cond_name(c) for c in conditions], 'memory_dim': memory_dim,
|
| 871 |
+
'metric': 'normalised reconstruction overlap |x & r| / sqrt(|x| |r|), mean over checkpoints and conditions',
|
| 872 |
+
'tuning_objective': 'the same metric on tune_seeds'})
|
| 873 |
+
receipt.update({
|
| 874 |
+
'module': MODULE_ID, 'source': SOURCE,
|
| 875 |
+
'arms': {'btsp': f'BTSP memory: {memory_dim} memory units, forward + feedback masks at density {density:g}, '
|
| 876 |
+
'plateau-gated stochastic flips, Hebbian feedback readout',
|
| 877 |
+
'willshaw': f'Willshaw clipped-Hebbian auto-associative matrix, {m}x{m} binary synapses',
|
| 878 |
+
'random_recall': f'seeded random pattern with {a} ones (chance; expected overlap {a / m:.4f})',
|
| 879 |
+
'cue_only': 'reference without memory: the degraded cue itself is the reconstruction'},
|
| 880 |
+
'tuning': {'btsp': {'chosen': b_chosen, 'chosen_on_grid_edge': b_edges, 'table': btsp_table},
|
| 881 |
+
'willshaw': {'chosen': {'threshold': w_best['threshold']}, 'chosen_on_grid_edge': w_edges,
|
| 882 |
+
'table': will_table}},
|
| 883 |
+
'per_seed': per_seed, 'summary': summary, 'comparisons': comparisons,
|
| 884 |
+
'verdict': comparisons['btsp_vs_willshaw']['verdict'],
|
| 885 |
+
'verdict_basis': ('btsp_vs_willshaw: paired 95% t interval over seeds on the capacity-curve mean '
|
| 886 |
+
'reconstruction overlap (higher is better), both arms tuned on disjoint tune_seeds'),
|
| 887 |
+
'budget': {'willshaw_synapses': m * m, 'btsp_synapses_per_seed': btsp_syn,
|
| 888 |
+
'btsp_synapses_expected': float(2.0 * density * m * memory_dim),
|
| 889 |
+
'btsp_to_willshaw_synapse_ratio': float(np.mean(btsp_syn) / (m * m)),
|
| 890 |
+
'btsp_state_numbers': int(4 * m * memory_dim + 4), 'willshaw_state_numbers': int(m * m + 1)},
|
| 891 |
+
'estimated_cost': {'stores_per_arm_run': n_pat, 'tuning_btsp_runs': len(plateau_grid) * len(threshold_grid)
|
| 892 |
+
* len(tune_seeds), 'recall_queries_per_run': len(loads) * len(conditions) * per,
|
| 893 |
+
'estimated_synapse_reads': int((len(plateau_grid) * len(threshold_grid) * len(tune_seeds)
|
| 894 |
+
+ len(seeds)) * (n_pat + len(loads) * len(conditions) * per)
|
| 895 |
+
* 2 * a * memory_dim)},
|
| 896 |
+
'measured_wallclock_s': {'tuning': tune_wall, 'evaluation': eval_wall},
|
| 897 |
+
'notes': ('Synthetic random sparse patterns stored once each, in order; recall is one feed-forward + feedback '
|
| 898 |
+
'pass for BTSP and one pass for Willshaw (no iteration). Thresholds are proportional to the cue / '
|
| 899 |
+
'trace size (the paper grid-searches an absolute memory threshold and, for input completion, uses '
|
| 900 |
+
'fitted linear functions of the average fraction of 1\'s). BTSP gets a larger tuning grid than '
|
| 901 |
+
'Willshaw (it has three free parameters, Willshaw one); tuning.<arm>.chosen_on_grid_edge names any '
|
| 902 |
+
'parameter whose chosen value is a grid edge. The paper itself does not compare BTSP with a '
|
| 903 |
+
'Willshaw memory. The comparison is at equal synapse count, not equal bits of '
|
| 904 |
+
'state: Willshaw has no masks. BTSP feed-forward weights are a palimpsest (stochastic flips), but the '
|
| 905 |
+
'Hebbian feedback weights only saturate, as in the paper. The cue_only reference shows whether a '
|
| 906 |
+
'reconstruction beats the degraded cue. A small toy at one scale: it does not test the paper\'s '
|
| 907 |
+
'network sizes or claims.'),
|
| 908 |
+
})
|
| 909 |
+
return harness.seal(receipt)
|
| 910 |
+
|
| 911 |
+
|
| 912 |
+
# ====================================================================== NEUROWEAVE extension experiment
|
| 913 |
+
_EXT_DEFAULTS: dict[str, Any] = {'memory_dim': 64, 'active_fraction': 0.25, 'density': 0.6, 'plateau_prob': 0.1,
|
| 914 |
+
'flip_prob': 0.5, 'threshold': 0.35, 'feedback_threshold': 0.5, 'gate': 0.5,
|
| 915 |
+
'projection_dim': 6}
|
| 916 |
+
_RUN_DEFAULTS: dict[str, Any] = {'task': 'delayed_recall', 'heldout_seeds': (100, 101), 'steps': 300,
|
| 917 |
+
'heldout_steps': None, 'neurons': 48, 'topology': 'clustered', 'mechanisms': ()}
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
def run_experiment(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]:
|
| 921 |
+
"""Baseline vs ``BTSPExtension`` readout features vs the random-trace capacity control on a NEUROWEAVE
|
| 922 |
+
temporal task (default ``delayed_recall``), through ``harness.run_extension_experiment``.
|
| 923 |
+
|
| 924 |
+
Extension overrides: the keys of ``_EXT_DEFAULTS``. Harness overrides: ``task``, ``heldout_seeds``, ``steps``,
|
| 925 |
+
``heldout_steps``, ``neurons``, ``topology``, ``mechanisms``. Quick mode uses the harness ``QUICK_ARGS`` sizes
|
| 926 |
+
(the seeds stay the caller's)."""
|
| 927 |
+
from . import harness
|
| 928 |
+
if type(quick) is not bool:
|
| 929 |
+
raise ValueError('quick must be a boolean')
|
| 930 |
+
seeds = _check_seeds('seeds', seeds)
|
| 931 |
+
ext_cfg, run_cfg = dict(_EXT_DEFAULTS), dict(_RUN_DEFAULTS)
|
| 932 |
+
if quick:
|
| 933 |
+
run_cfg.update({k: v for k, v in harness.QUICK_ARGS.items() if k != 'seeds'})
|
| 934 |
+
unknown = sorted(set(overrides) - set(ext_cfg) - set(run_cfg))
|
| 935 |
+
if unknown:
|
| 936 |
+
raise ValueError(f'unknown run_experiment overrides: {unknown}')
|
| 937 |
+
for key, value in overrides.items():
|
| 938 |
+
(ext_cfg if key in ext_cfg else run_cfg)[key] = value
|
| 939 |
+
probe = BTSPExtension(seed=0, **ext_cfg) # validate before running anything
|
| 940 |
+
ext_cfg = {k: v for k, v in probe.config().items() if k != 'seed'}
|
| 941 |
+
|
| 942 |
+
def factory(seed: int) -> BTSPExtension:
|
| 943 |
+
return BTSPExtension(seed=seed, **ext_cfg)
|
| 944 |
+
|
| 945 |
+
t0 = time.perf_counter()
|
| 946 |
+
receipt = dict(harness.run_extension_experiment(
|
| 947 |
+
MODULE_ID, factory, seeds=seeds, control='random_trace', metric='accuracy', notes=(
|
| 948 |
+
f'Readout-only extension: the brain output is binarised by top-k (fraction {probe.active_fraction:g}) and '
|
| 949 |
+
f'recalled from a {probe.memory_dim}-unit BTSP memory before any store; features are the recall overlap, '
|
| 950 |
+
f'the recall confidence and {probe.projection_dim} fixed projections of the memory trace. While learning, '
|
| 951 |
+
f'a pattern is stored one-shot when max(|reward|, novelty) exceeds {probe.gate:g}, with the plateau '
|
| 952 |
+
'probability scaled by that salience. It never changes the brain drive. The control gets the same number '
|
| 953 |
+
'of random leaky-trace features of the brain output. Small synthetic task; the verdict is a paired 95 % '
|
| 954 |
+
't interval over seeds.'),
|
| 955 |
+
**run_cfg))
|
| 956 |
+
receipt.pop('digest', None)
|
| 957 |
+
receipt['config'] = {**receipt['config'], 'quick': quick, 'extension': ext_cfg}
|
| 958 |
+
receipt['module'] = MODULE_ID
|
| 959 |
+
receipt['source'] = SOURCE
|
| 960 |
+
receipt['measured_wallclock_s'] = {'total': time.perf_counter() - t0}
|
| 961 |
+
return harness.seal(receipt)
|
| 962 |
+
|
| 963 |
+
|
| 964 |
+
EXPERIMENTS: dict[str, Callable[..., dict[str, Any]]] = {MODULE_ID: run_experiment, CAPACITY_ID: run_capacity_benchmark}
|
synapse/frontier/causal_emergence.py
ADDED
|
@@ -0,0 +1,1365 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Effective information and causal emergence (frontier module ``causal_emergence``).
|
| 2 |
+
|
| 3 |
+
Inspired by effective information (EI) and causal emergence as defined by Hoel, Albantakis & Tononi (2013) and
|
| 4 |
+
Hoel (2017), and by the macro-vs-micro EI experiments of SONAPSE-ORIGIN (kai9987kai,
|
| 5 |
+
``sonapse_origin/theories/causal_emergence.py``). GhostInTheMachine (kai9987kai) measures emergence with the
|
| 6 |
+
Rosas et al. (2020) Psi criterion instead; its lesson that an emergence statistic must be read against a matched
|
| 7 |
+
null is applied here. This is a synthetic computational abstraction over discretised unit activity, not a measure
|
| 8 |
+
of consciousness, agency or biological causation.
|
| 9 |
+
|
| 10 |
+
What is computed
|
| 11 |
+
----------------
|
| 12 |
+
* **Effective information.** For a row-stochastic transition probability matrix (TPM) ``T`` over ``n`` states and
|
| 13 |
+
maximum-entropy (uniform) interventions on the current state,
|
| 14 |
+
``EI(T) = (1/n) sum_i D_KL(T_i || E_D)`` in bits, ``E_D = (1/n) sum_i T_i`` (the effect distribution).
|
| 15 |
+
Equivalently ``EI = H(E_D) - (1/n) sum_i H(T_i)``, the mutual information between uniform interventions and
|
| 16 |
+
their effects.
|
| 17 |
+
* **Decomposition (Hoel 2017).** ``determinism = (1/n) sum_i D_KL(T_i || U) / log2 n``,
|
| 18 |
+
``degeneracy = D_KL(E_D || U) / log2 n``, ``effectiveness = determinism - degeneracy`` and
|
| 19 |
+
``EI = log2(n) * effectiveness`` (``U`` uniform).
|
| 20 |
+
* **Estimation.** Transition counts of a discretised state sequence, additive (Laplace, ``alpha = 1``) smoothing:
|
| 21 |
+
``T_ij = (C_ij + alpha) / (sum_k C_ik + alpha n)``.
|
| 22 |
+
* **Coarse-graining.** A partition of micro states into macro states; the macro TPM is obtained by intervening
|
| 23 |
+
uniformly on the micro states inside each macro state and summing their effects over each macro state
|
| 24 |
+
(Hoel et al. 2013). Candidates are all proper set partitions of a small state space (``3 <= n <= 10``), or
|
| 25 |
+
partitions of binary units into groups whose macro variable is the group's count of active units.
|
| 26 |
+
* **Causal emergence.** ``CE = max_macro EI(macro) - EI(micro)`` over proper coarse-grainings (the micro
|
| 27 |
+
description itself is excluded, so ``CE`` can be negative).
|
| 28 |
+
* **Nulls.** Two references, both re-running the search for the best coarse-graining in every draw (so the null
|
| 29 |
+
includes the selection of the maximum), each reported as ``z = (CE - mean_null) / sd_null`` and the one-sided
|
| 30 |
+
rank p-value ``(1 + #{CE_null >= CE}) / (1 + draws)``:
|
| 31 |
+
|
| 32 |
+
- *successor block permutation* (temporal-dependence null): the successor sequence is block-permuted against
|
| 33 |
+
the current-state sequence, which breaks lag-1 dependence but keeps how often each state was visited;
|
| 34 |
+
- *independent units* (multi-unit data only): every unit's bit sequence is circularly shifted by its own random
|
| 35 |
+
offset, which keeps each unit's own occupancy and autocorrelation but makes the units independent.
|
| 36 |
+
|
| 37 |
+
Neither null tests "true macro EI > true micro EI". Smoothed EI estimates shrink the many-state micro TPM more
|
| 38 |
+
than a macro TPM, so with sparse counts the CE estimate rises above the successor null for *any* temporally
|
| 39 |
+
dependent data, including independent slow units whose exact CE is negative (a measured case is in the
|
| 40 |
+
receipt). Against the independent-units null, a large CE means the coarse-graining gains from coordination
|
| 41 |
+
between units beyond the units' own dynamics; the known-answer checks show where each null is calibrated.
|
| 42 |
+
|
| 43 |
+
References (verified 2026-11-20; notes in ``docs/frontier/modules/causal_emergence.md``)
|
| 44 |
+
--------------------------------------------------------------------------------------
|
| 45 |
+
* E. P. Hoel, L. Albantakis, G. Tononi, "Quantifying causal emergence shows that macro can beat micro",
|
| 46 |
+
PNAS 110(49):19790-19795, December 2013 (online 18 November 2013), https://doi.org/10.1073/pnas.1314922110
|
| 47 |
+
* E. P. Hoel, "When the map is better than the territory", Entropy 19(5):188, published 26 April 2017,
|
| 48 |
+
https://doi.org/10.3390/e19050188 (preprint arXiv:1612.09592, whose v1 text was used to check printed values)
|
| 49 |
+
* F. E. Rosas, P. A. M. Mediano, H. J. Jensen, A. K. Seth, A. B. Barrett, R. L. Carhart-Harris, D. Bor,
|
| 50 |
+
"Reconciling emergences: an information-theoretic approach to identify causal emergence in multivariate data",
|
| 51 |
+
PLOS Comput. Biol. 16(12):e1008289, December 2020, https://doi.org/10.1371/journal.pcbi.1008289 (the Psi
|
| 52 |
+
criterion used by GhostInTheMachine; not implemented here)
|
| 53 |
+
"""
|
| 54 |
+
from __future__ import annotations
|
| 55 |
+
|
| 56 |
+
import math
|
| 57 |
+
import time
|
| 58 |
+
from fractions import Fraction
|
| 59 |
+
from typing import Any, Callable, Mapping, Sequence
|
| 60 |
+
|
| 61 |
+
import numpy as np
|
| 62 |
+
|
| 63 |
+
from .connectomics import block_permutation
|
| 64 |
+
from .spec import EVIDENCE_TIER, FrontierSpecV1
|
| 65 |
+
|
| 66 |
+
__all__ = ['MODULE_ID', 'CausalEmergenceObserver', 'entropy_bits', 'as_tpm', 'effective_information',
|
| 67 |
+
'ei_decomposition', 'transition_counts', 'estimate_tpm', 'median_binarize', 'encode_bits',
|
| 68 |
+
'decode_states', 'coarse_grain_tpm', 'set_partitions', 'unit_sum_labels', 'unit_sum_candidates',
|
| 69 |
+
'state_partition_candidates', 'macro_ei_batch', 'best_state_partition', 'best_unit_coarse_graining',
|
| 70 |
+
'causal_emergence', 'successor_block_null', 'independent_units_null', 'hoel2017_examples',
|
| 71 |
+
'and_gate_network', 'pair_count_copy_tpm', 'noisy_permutation_tpm', 'independent_flip_tpm',
|
| 72 |
+
'PRINTED_VALUES', 'run_experiment', 'EXPERIMENTS']
|
| 73 |
+
|
| 74 |
+
MODULE_ID = 'causal_emergence'
|
| 75 |
+
OBSERVER_STATE_SCHEMA = 'CausalEmergenceObserverStateV1'
|
| 76 |
+
_PERM_OFFSET = 64_001
|
| 77 |
+
_EST_OFFSET = 64_011
|
| 78 |
+
_IID_OFFSET = 64_021
|
| 79 |
+
_CHAIN_OFFSET = 64_031
|
| 80 |
+
_NULL_OFFSET = 64_041
|
| 81 |
+
_OBS_UNITS_OFFSET = 64_051
|
| 82 |
+
_OBS_NULL_OFFSET = 64_061
|
| 83 |
+
_INDEP_OFFSET = 64_071
|
| 84 |
+
_OBS_INDEP_OFFSET = 64_081
|
| 85 |
+
_PAIR_OFFSET = 64_091
|
| 86 |
+
_SLOW_OFFSET = 64_101
|
| 87 |
+
_UNIT_NULL_OFFSET = 64_111
|
| 88 |
+
_PERM8_OFFSET = 64_121
|
| 89 |
+
_EPS = 1e-12
|
| 90 |
+
_MAX_STATES = 2048
|
| 91 |
+
_MAX_SEARCH_STATES = 10
|
| 92 |
+
_MAX_OBSERVER_UNITS = 6
|
| 93 |
+
_CHUNK_CELLS = 1 << 20 # candidate chunks hold at most ~1M (candidate, i, j) cells
|
| 94 |
+
_SPEC_OBSERVER_PARAMS = frozenset({'sync_pairs', 'sae_features', 'sae_k', 'fc_window', 'max_observed_units',
|
| 95 |
+
'observe_every'})
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# ====================================================================== validation helpers
|
| 99 |
+
def _check_int(name: str, value: Any, low: int, high: int) -> int:
|
| 100 |
+
if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, np.integer)) or not low <= int(value) <= high:
|
| 101 |
+
raise ValueError(f'{name} must be an int in [{low}, {high}]')
|
| 102 |
+
return int(value)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _check_float(name: str, value: Any, low: float, high: float) -> float:
|
| 106 |
+
if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
|
| 107 |
+
raise ValueError(f'{name} must be a number in [{low}, {high}]')
|
| 108 |
+
v = float(value)
|
| 109 |
+
if not (math.isfinite(v) and low <= v <= high):
|
| 110 |
+
raise ValueError(f'{name} must be a finite number in [{low}, {high}]')
|
| 111 |
+
return v
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _check_seeds(seeds: Any) -> tuple[int, ...]:
|
| 115 |
+
try:
|
| 116 |
+
out = tuple(_check_int('seed', s, 0, 2**31 - 1) for s in seeds)
|
| 117 |
+
except TypeError as exc:
|
| 118 |
+
raise ValueError('seeds must be an iterable of ints') from exc
|
| 119 |
+
if not out or len(set(out)) != len(out):
|
| 120 |
+
raise ValueError('seeds must be non-empty and unique')
|
| 121 |
+
return out
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _int_vector(name: str, value: Any, *, min_len: int = 1) -> np.ndarray:
|
| 125 |
+
arr = np.asarray(value)
|
| 126 |
+
if arr.ndim != 1 or arr.size < min_len or (arr.size and arr.dtype.kind not in 'iu'):
|
| 127 |
+
raise ValueError(f'{name} must be a 1-D integer array with at least {min_len} entries')
|
| 128 |
+
return arr.astype(np.int64)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# ====================================================================== information measures
|
| 132 |
+
def _entropy(P: np.ndarray) -> np.ndarray:
|
| 133 |
+
"""Shannon entropy in bits along the last axis (``0 log 0 = 0``)."""
|
| 134 |
+
L = np.zeros_like(P)
|
| 135 |
+
np.log2(P, out=L, where=P > 0.0)
|
| 136 |
+
return -(P * L).sum(axis=-1)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def entropy_bits(p: Any) -> float:
|
| 140 |
+
"""Shannon entropy (bits) of a probability vector (finite, non-negative, summing to 1 within 1e-8)."""
|
| 141 |
+
try:
|
| 142 |
+
v = np.array(p, dtype=np.float64)
|
| 143 |
+
except (TypeError, ValueError) as exc:
|
| 144 |
+
raise ValueError('p must be numeric') from exc
|
| 145 |
+
if v.ndim != 1 or v.size < 1 or not np.all(np.isfinite(v)) or np.any(v < 0.0) or abs(float(v.sum()) - 1.0) > 1e-8:
|
| 146 |
+
raise ValueError('p must be a finite, non-negative 1-D probability vector')
|
| 147 |
+
return float(max(0.0, float(_entropy(v / v.sum()))))
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def as_tpm(tpm: Any, *, atol: float = 1e-8) -> np.ndarray:
|
| 151 |
+
"""A validated float64 copy of a row-stochastic ``(n, n)`` matrix, ``1 <= n <= 2048``. Rows must sum to 1
|
| 152 |
+
within ``atol`` and are then renormalised exactly."""
|
| 153 |
+
try:
|
| 154 |
+
T = np.array(tpm, dtype=np.float64)
|
| 155 |
+
except (TypeError, ValueError) as exc:
|
| 156 |
+
raise ValueError('tpm must be numeric') from exc
|
| 157 |
+
if T.ndim != 2 or T.shape[0] != T.shape[1] or not 1 <= T.shape[0] <= _MAX_STATES:
|
| 158 |
+
raise ValueError(f'tpm must be a square matrix with 1 to {_MAX_STATES} states')
|
| 159 |
+
if not np.all(np.isfinite(T)) or np.any(T < 0.0):
|
| 160 |
+
raise ValueError('tpm must be finite and non-negative')
|
| 161 |
+
s = T.sum(axis=1)
|
| 162 |
+
if np.any(np.abs(s - 1.0) > _check_float('atol', atol, 0.0, 1e-3)):
|
| 163 |
+
raise ValueError('every tpm row must sum to 1')
|
| 164 |
+
return T / s[:, None]
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def _ei(T: np.ndarray) -> float:
|
| 168 |
+
"""EI of a validated TPM: mean KL divergence (bits) of the rows from their mean."""
|
| 169 |
+
m = T.mean(axis=0)
|
| 170 |
+
ratio = np.ones_like(T)
|
| 171 |
+
np.divide(T, m[None, :], out=ratio, where=T > 0.0) # T_ij > 0 implies m_j >= T_ij / n > 0
|
| 172 |
+
return max(0.0, float((T * np.log2(ratio)).sum() / T.shape[0]))
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def effective_information(tpm: Any) -> float:
|
| 176 |
+
"""``EI = (1/n) sum_i D_KL(T_i || E_D)`` in bits under uniform interventions (Hoel et al., 2013)."""
|
| 177 |
+
return _ei(as_tpm(tpm))
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _decomposition(T: np.ndarray) -> dict[str, Any]:
|
| 181 |
+
n = T.shape[0]
|
| 182 |
+
ei = _ei(T)
|
| 183 |
+
mean_h = float(_entropy(T).mean())
|
| 184 |
+
h_eff = float(_entropy(T.mean(axis=0)))
|
| 185 |
+
size = math.log2(n)
|
| 186 |
+
out: dict[str, Any] = {'states': int(n), 'ei': ei, 'size_bits': size, 'mean_row_entropy': mean_h,
|
| 187 |
+
'effect_entropy': h_eff, 'determinism': None, 'degeneracy': None, 'effectiveness': None}
|
| 188 |
+
if n > 1:
|
| 189 |
+
det = min(1.0, max(0.0, (size - mean_h) / size))
|
| 190 |
+
deg = min(1.0, max(0.0, (size - h_eff) / size))
|
| 191 |
+
out.update(determinism=det, degeneracy=deg, effectiveness=det - deg)
|
| 192 |
+
return out
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def ei_decomposition(tpm: Any) -> dict[str, Any]:
|
| 196 |
+
"""EI with Hoel's (2017) decomposition: ``determinism = (log2 n - mean_i H(T_i)) / log2 n``,
|
| 197 |
+
``degeneracy = (log2 n - H(E_D)) / log2 n``, ``effectiveness = determinism - degeneracy``, so
|
| 198 |
+
``EI = log2(n) * effectiveness``. The normalised terms are ``None`` for a single state."""
|
| 199 |
+
return _decomposition(as_tpm(tpm))
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ====================================================================== estimation from data
|
| 203 |
+
def _state_sequence(states: Any, n_states: int, *, min_len: int = 2) -> np.ndarray:
|
| 204 |
+
s = _int_vector('states', states, min_len=min_len)
|
| 205 |
+
if s.min() < 0 or s.max() >= n_states:
|
| 206 |
+
raise ValueError(f'states must lie in [0, {n_states})')
|
| 207 |
+
return s
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def _counts(cur: np.ndarray, nxt: np.ndarray, n: int) -> np.ndarray:
|
| 211 |
+
return np.bincount(cur * n + nxt, minlength=n * n).reshape(n, n)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def transition_counts(states: Any, n_states: int, *, next_states: Any = None) -> np.ndarray:
|
| 215 |
+
"""Counts ``C[i, j]`` of transitions ``i -> j`` (values in ``[0, n_states)``).
|
| 216 |
+
|
| 217 |
+
Without ``next_states`` the transitions are the consecutive pairs of one state sequence. With ``next_states``
|
| 218 |
+
(same length as ``states``) they are the pairs ``(states[t], next_states[t])``, e.g. interventional samples
|
| 219 |
+
in which the current state was set and its successor observed."""
|
| 220 |
+
n = _check_int('n_states', n_states, 1, _MAX_STATES)
|
| 221 |
+
if next_states is None:
|
| 222 |
+
s = _state_sequence(states, n)
|
| 223 |
+
return _counts(s[:-1], s[1:], n)
|
| 224 |
+
cur = _state_sequence(states, n, min_len=1)
|
| 225 |
+
nxt = _state_sequence(next_states, n, min_len=1)
|
| 226 |
+
if nxt.size != cur.size:
|
| 227 |
+
raise ValueError('next_states must have the same length as states')
|
| 228 |
+
return _counts(cur, nxt, n)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def _smoothed(C: np.ndarray, alpha: float) -> np.ndarray:
|
| 232 |
+
n = C.shape[0]
|
| 233 |
+
A = C + alpha
|
| 234 |
+
tot = A.sum(axis=1, keepdims=True)
|
| 235 |
+
out = np.full(A.shape, 1.0 / n)
|
| 236 |
+
np.divide(A, tot, out=out, where=tot > 0.0) # unseen rows with alpha = 0 stay uniform
|
| 237 |
+
return out
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def estimate_tpm(counts: Any, *, alpha: float = 1.0) -> np.ndarray:
|
| 241 |
+
"""Additively smoothed TPM ``(C + alpha) / (row total + alpha n)``; ``alpha = 1`` is Laplace smoothing.
|
| 242 |
+
Rows without counts (possible only with ``alpha = 0``) are uniform: no evidence, maximum entropy."""
|
| 243 |
+
try:
|
| 244 |
+
C = np.array(counts, dtype=np.float64)
|
| 245 |
+
except (TypeError, ValueError) as exc:
|
| 246 |
+
raise ValueError('counts must be numeric') from exc
|
| 247 |
+
if C.ndim != 2 or C.shape[0] != C.shape[1] or not 1 <= C.shape[0] <= _MAX_STATES:
|
| 248 |
+
raise ValueError('counts must be a square matrix')
|
| 249 |
+
if not np.all(np.isfinite(C)) or np.any(C < 0.0):
|
| 250 |
+
raise ValueError('counts must be finite and non-negative')
|
| 251 |
+
return _smoothed(C, _check_float('alpha', alpha, 0.0, 1e6))
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def _above_median(values: np.ndarray, reference: np.ndarray) -> np.ndarray:
|
| 255 |
+
"""``values > median(reference)`` per column. A value tied with the median counts as on when more of the
|
| 256 |
+
reference lies strictly below the median than strictly above it, so a discrete unit whose upper value is the
|
| 257 |
+
majority (e.g. a 0/1 unit that is on 70 % of the time) is binarised as itself rather than as constant 0;
|
| 258 |
+
for continuous data ties have probability zero and the rule is plain ``x > median``."""
|
| 259 |
+
med = np.median(reference, axis=0)
|
| 260 |
+
on = values > med
|
| 261 |
+
tie = values == med
|
| 262 |
+
if np.any(tie):
|
| 263 |
+
on |= tie & ((reference < med).sum(axis=0) > (reference > med).sum(axis=0))
|
| 264 |
+
return on
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def median_binarize(X: Any) -> np.ndarray:
|
| 268 |
+
"""Offline per-column binarisation ``x > median(column)`` of a finite ``(T, k)`` array (boolean result); values
|
| 269 |
+
tied with the median go to the side of the median that holds less of the column (see the observer)."""
|
| 270 |
+
try:
|
| 271 |
+
A = np.array(X, dtype=np.float64)
|
| 272 |
+
except (TypeError, ValueError) as exc:
|
| 273 |
+
raise ValueError('X must be numeric') from exc
|
| 274 |
+
if A.ndim != 2 or A.shape[0] < 1 or A.shape[1] < 1 or not np.all(np.isfinite(A)):
|
| 275 |
+
raise ValueError('X must be a finite 2-D array')
|
| 276 |
+
return _above_median(A, A)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def encode_bits(bits: Any) -> np.ndarray:
|
| 280 |
+
"""Integer states ``sum_j bit_j 2^j`` of a ``(T, k)`` 0/1 array, ``1 <= k <= 30``."""
|
| 281 |
+
b = np.asarray(bits)
|
| 282 |
+
if b.ndim != 2 or not 1 <= b.shape[1] <= 30 or b.dtype.kind not in 'biu' or np.any((b != 0) & (b != 1)):
|
| 283 |
+
raise ValueError('bits must be a 2-D 0/1 array with 1 to 30 columns')
|
| 284 |
+
return (b.astype(np.int64) << np.arange(b.shape[1], dtype=np.int64)).sum(axis=1)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def decode_states(states: Any, n_bits: int) -> np.ndarray:
|
| 288 |
+
"""Inverse of :func:`encode_bits`: a ``(T, n_bits)`` int8 array of bits."""
|
| 289 |
+
k = _check_int('n_bits', n_bits, 1, 30)
|
| 290 |
+
s = _state_sequence(states, 2 ** k, min_len=1)
|
| 291 |
+
return ((s[:, None] >> np.arange(k, dtype=np.int64)) & 1).astype(np.int8)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
# ====================================================================== coarse-graining
|
| 295 |
+
def _labels(labels: Any, n: int) -> tuple[np.ndarray, int]:
|
| 296 |
+
lab = _int_vector('labels', labels)
|
| 297 |
+
if lab.size != n or lab.min() < 0:
|
| 298 |
+
raise ValueError(f'labels must hold one non-negative macro label per micro state ({n})')
|
| 299 |
+
m = int(lab.max()) + 1
|
| 300 |
+
if np.unique(lab).size != m:
|
| 301 |
+
raise ValueError('labels must use every macro state 0..m-1')
|
| 302 |
+
return lab, m
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def coarse_grain_tpm(tpm: Any, labels: Any) -> np.ndarray:
|
| 306 |
+
"""Macro TPM of a partition (Hoel et al., 2013): macro state ``A`` is entered by intervening uniformly on its
|
| 307 |
+
micro states, ``T_M[A, B] = (1/|A|) sum_{i in A} sum_{j in B} T[i, j]``."""
|
| 308 |
+
T = as_tpm(tpm)
|
| 309 |
+
lab, m = _labels(labels, T.shape[0])
|
| 310 |
+
Q = np.bincount((lab[:, None] * m + lab[None, :]).ravel(), weights=T.ravel(), minlength=m * m).reshape(m, m)
|
| 311 |
+
return Q / np.bincount(lab, minlength=m)[:, None]
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def set_partitions(n: int) -> np.ndarray:
|
| 315 |
+
"""Every set partition of ``n`` items (``1 <= n <= 10``) as restricted-growth label rows, shape ``(B_n, n)``
|
| 316 |
+
(Bell number ``B_n``; 115975 rows for ``n = 10``)."""
|
| 317 |
+
n = _check_int('n', n, 1, _MAX_SEARCH_STATES)
|
| 318 |
+
rgs = np.zeros((1, 1), dtype=np.int64)
|
| 319 |
+
mx = np.zeros(1, dtype=np.int64)
|
| 320 |
+
for _ in range(1, n):
|
| 321 |
+
reps = mx + 2 # the next label is 0 .. max + 1
|
| 322 |
+
start = np.repeat(np.cumsum(reps) - reps, reps)
|
| 323 |
+
vals = np.arange(int(reps.sum()), dtype=np.int64) - start
|
| 324 |
+
rgs = np.column_stack([np.repeat(rgs, reps, axis=0), vals])
|
| 325 |
+
mx = np.maximum(np.repeat(mx, reps), vals)
|
| 326 |
+
return rgs
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def unit_sum_labels(groups: Any) -> tuple[np.ndarray, int]:
|
| 330 |
+
"""Macro labels of the ``2^u`` binary micro states when units are grouped by ``groups`` (one group label per
|
| 331 |
+
unit, every group ``0..G-1`` used) and each group's macro variable is its number of active units. Returns
|
| 332 |
+
``(labels, m)`` with ``m = prod_g (|g| + 1)`` (mixed-radix encoding of the group counts)."""
|
| 333 |
+
g = _int_vector('groups', groups)
|
| 334 |
+
if not 1 <= g.size <= 12 or g.min() < 0 or np.unique(g).size != int(g.max()) + 1:
|
| 335 |
+
raise ValueError('groups must give 1 to 12 units a group label, using every group 0..G-1')
|
| 336 |
+
u, G = g.size, int(g.max()) + 1
|
| 337 |
+
sizes = np.bincount(g, minlength=G)
|
| 338 |
+
bits = (np.arange(2 ** u, dtype=np.int64)[:, None] >> np.arange(u, dtype=np.int64)) & 1
|
| 339 |
+
member = np.zeros((u, G), dtype=np.int64)
|
| 340 |
+
member[np.arange(u), g] = 1
|
| 341 |
+
radix = np.cumprod(np.r_[1, sizes[:-1] + 1]).astype(np.int64)
|
| 342 |
+
return (bits @ member) @ radix, int(np.prod(sizes + 1))
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def unit_sum_candidates(n_units: int) -> dict[str, Any]:
|
| 346 |
+
"""All partitions of ``n_units`` binary units (2..6) except all-singletons (the micro description), each
|
| 347 |
+
with its count-per-group macro labels. Keys ``groups (K, u)``, ``labels (K, 2^u)``, ``m (K,)``."""
|
| 348 |
+
u = _check_int('n_units', n_units, 2, _MAX_OBSERVER_UNITS)
|
| 349 |
+
parts = set_partitions(u)
|
| 350 |
+
parts = parts[parts.max(axis=1) < u - 1]
|
| 351 |
+
labs, ms = zip(*(unit_sum_labels(p) for p in parts))
|
| 352 |
+
return {'groups': parts, 'labels': np.stack(labs), 'm': np.asarray(ms, dtype=np.int64)}
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def state_partition_candidates(n: int) -> dict[str, Any]:
|
| 356 |
+
"""All proper partitions (``2 <= m < n`` macro states) of ``3 <= n <= 10`` micro states."""
|
| 357 |
+
n = _check_int('n', n, 3, _MAX_SEARCH_STATES)
|
| 358 |
+
parts = set_partitions(n)
|
| 359 |
+
m = parts.max(axis=1) + 1
|
| 360 |
+
keep = (m >= 2) & (m < n)
|
| 361 |
+
return {'labels': parts[keep], 'm': m[keep]}
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
class _Candidates:
|
| 365 |
+
"""A chunk of ``K`` coarse-grainings of ``n`` micro states. The macro cells of candidate ``k`` form a compact
|
| 366 |
+
``m_k x m_k`` block; a sparse 0/1 matrix maps the ``n^2`` micro TPM entries onto all blocks at once."""
|
| 367 |
+
|
| 368 |
+
def __init__(self, labels: np.ndarray, m: np.ndarray) -> None:
|
| 369 |
+
from scipy.sparse import csr_matrix
|
| 370 |
+
K, n = labels.shape
|
| 371 |
+
m = m.astype(np.int64)
|
| 372 |
+
self.labels, self.K, self.n, self.m = labels, K, n, m.astype(np.float64)
|
| 373 |
+
sq = m * m
|
| 374 |
+
off_cells = np.r_[0, np.cumsum(sq)[:-1]].astype(np.int64)
|
| 375 |
+
off_cols = np.r_[0, np.cumsum(m)[:-1]].astype(np.int64)
|
| 376 |
+
n_cells, n_cols = int(sq.sum()), int(m.sum())
|
| 377 |
+
cell = off_cells[:, None, None] + labels[:, :, None] * m[:, None, None] + labels[:, None, :]
|
| 378 |
+
# micro entry (i, j) of candidate k adds T[i, j] / |A| to macro cell (A, B), A = label of i, B = label of j
|
| 379 |
+
sizes = np.bincount((off_cols[:, None] + labels).ravel(), minlength=n_cols).astype(np.float64)
|
| 380 |
+
inv_size = 1.0 / sizes[off_cols[:, None] + labels] # every macro state is non-empty
|
| 381 |
+
self.S = csr_matrix((np.repeat(inv_size.ravel(), n),
|
| 382 |
+
(cell.ravel(), np.tile(np.arange(n * n, dtype=np.int64), K))), shape=(n_cells, n * n))
|
| 383 |
+
k_cell = np.repeat(np.arange(K, dtype=np.int64), sq)
|
| 384 |
+
m_cell = m[k_cell]
|
| 385 |
+
cell_col = off_cols[k_cell] + (np.arange(n_cells, dtype=np.int64) - off_cells[k_cell]) % m_cell
|
| 386 |
+
# column means of every macro TPM (its effect distribution under uniform macro interventions)
|
| 387 |
+
self.C = csr_matrix((1.0 / m_cell.astype(np.float64), (cell_col, np.arange(n_cells, dtype=np.int64))),
|
| 388 |
+
shape=(n_cols, n_cells))
|
| 389 |
+
self.cell_starts, self.col_starts = off_cells, off_cols
|
| 390 |
+
|
| 391 |
+
def macro_ei(self, T: np.ndarray) -> np.ndarray:
|
| 392 |
+
"""``EI_k = H(mean row) - mean_A H(row A)`` (bits) of every candidate's macro TPM."""
|
| 393 |
+
r = self.S @ T.ravel() # macro TPM entries, block by block
|
| 394 |
+
rlogr = np.add.reduceat(r * np.log2(np.where(r > 0.0, r, 1.0)), self.cell_starts)
|
| 395 |
+
col = self.C @ r # mean rows
|
| 396 |
+
h_mean = -np.add.reduceat(col * np.log2(np.where(col > 0.0, col, 1.0)), self.col_starts)
|
| 397 |
+
return np.maximum(h_mean + rlogr / self.m, 0.0)
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def _candidate_chunks(labels_batch: Any, n: int, m: Any = None) -> list[_Candidates]:
|
| 401 |
+
L = np.asarray(labels_batch)
|
| 402 |
+
if L.ndim != 2 or L.shape[0] < 1 or L.shape[1] != n or L.dtype.kind not in 'iu':
|
| 403 |
+
raise ValueError(f'labels_batch must be a non-empty 2-D integer array with {n} columns')
|
| 404 |
+
L = L.astype(np.int64)
|
| 405 |
+
if L.min() < 0:
|
| 406 |
+
raise ValueError('labels must be non-negative')
|
| 407 |
+
mk = L.max(axis=1) + 1
|
| 408 |
+
if m is None:
|
| 409 |
+
used = np.zeros((L.shape[0], int(mk.max())), dtype=bool)
|
| 410 |
+
used[np.repeat(np.arange(L.shape[0]), n), L.ravel()] = True
|
| 411 |
+
if not np.array_equal(used.sum(axis=1), mk):
|
| 412 |
+
raise ValueError('every labels row must use each macro state 0..m-1')
|
| 413 |
+
step = max(1, _CHUNK_CELLS // (n * n))
|
| 414 |
+
return [_Candidates(L[i:i + step], mk[i:i + step]) for i in range(0, L.shape[0], step)]
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def _batch_ei(T: np.ndarray, chunks: Sequence[_Candidates]) -> np.ndarray:
|
| 418 |
+
return np.concatenate([c.macro_ei(T) for c in chunks])
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def macro_ei_batch(tpm: Any, labels_batch: Any) -> np.ndarray:
|
| 422 |
+
"""EI of the macro TPM of every coarse-graining in ``labels_batch`` (``(K, n)``, one partition per row)."""
|
| 423 |
+
T = as_tpm(tpm)
|
| 424 |
+
return _batch_ei(T, _candidate_chunks(labels_batch, T.shape[0]))
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def best_state_partition(tpm: Any) -> dict[str, Any]:
|
| 428 |
+
"""Exhaustive search over every proper partition of a ``3 <= n <= 10`` state TPM for the macro TPM with the
|
| 429 |
+
largest EI (ties: the first partition in restricted-growth order)."""
|
| 430 |
+
T = as_tpm(tpm)
|
| 431 |
+
cand = state_partition_candidates(T.shape[0])
|
| 432 |
+
eis = _batch_ei(T, _candidate_chunks(cand['labels'], T.shape[0], cand['m']))
|
| 433 |
+
k = int(np.argmax(eis))
|
| 434 |
+
micro = _ei(T)
|
| 435 |
+
return {'ei_micro': micro, 'ei_macro': float(eis[k]), 'ce': float(eis[k]) - micro,
|
| 436 |
+
'labels': cand['labels'][k].copy(), 'macro_states': int(cand['m'][k]),
|
| 437 |
+
'partitions_evaluated': int(eis.size), 'macro_tpm': coarse_grain_tpm(T, cand['labels'][k])}
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def best_unit_coarse_graining(tpm: Any, n_units: int) -> dict[str, Any]:
|
| 441 |
+
"""Best count-per-group coarse-graining of a TPM over ``2^n_units`` binary micro states (``2 <= n_units <= 6``)."""
|
| 442 |
+
T = as_tpm(tpm)
|
| 443 |
+
cand = unit_sum_candidates(n_units)
|
| 444 |
+
if T.shape[0] != 2 ** int(n_units):
|
| 445 |
+
raise ValueError('tpm must have 2^n_units states')
|
| 446 |
+
eis = _batch_ei(T, _candidate_chunks(cand['labels'], T.shape[0], cand['m']))
|
| 447 |
+
k = int(np.argmax(eis))
|
| 448 |
+
micro = _ei(T)
|
| 449 |
+
return {'ei_micro': micro, 'ei_macro': float(eis[k]), 'ce': float(eis[k]) - micro,
|
| 450 |
+
'groups': _groups(cand['groups'][k], np.arange(int(n_units))), 'labels': cand['labels'][k].copy(),
|
| 451 |
+
'macro_states': int(cand['m'][k]), 'partitions_evaluated': int(eis.size)}
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
def _groups(rgs: np.ndarray, units: np.ndarray) -> list[list[int]]:
|
| 455 |
+
return [[int(units[j]) for j in np.flatnonzero(rgs == g)] for g in range(int(rgs.max()) + 1)]
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
def causal_emergence(tpm: Any, labels: Any) -> dict[str, Any]:
|
| 459 |
+
"""Micro and macro EI (with decompositions) of one coarse-graining and ``CE = EI_macro - EI_micro``."""
|
| 460 |
+
T = as_tpm(tpm)
|
| 461 |
+
M = coarse_grain_tpm(T, labels)
|
| 462 |
+
micro, macro = _decomposition(T), _decomposition(M)
|
| 463 |
+
return {'micro': micro, 'macro': macro, 'ce': macro['ei'] - micro['ei'], 'macro_tpm': M}
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
# ====================================================================== null distribution
|
| 467 |
+
def _default_block(transitions: int) -> int:
|
| 468 |
+
return max(1, int(round(transitions ** (1.0 / 3.0)))) if transitions >= 8 else 1
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
def _ce_of_pairs(cur: np.ndarray, nxt: np.ndarray, n: int, alpha: float,
|
| 472 |
+
chunks: Sequence[_Candidates]) -> tuple[float, np.ndarray, int]:
|
| 473 |
+
T = _smoothed(_counts(cur, nxt, n), alpha)
|
| 474 |
+
eis = _batch_ei(T, chunks)
|
| 475 |
+
return _ei(T), eis, int(np.argmax(eis))
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def _null_stats(ce: float, null: np.ndarray) -> dict[str, Any]:
|
| 479 |
+
mu = float(null.mean())
|
| 480 |
+
sd = float(null.std(ddof=1)) if null.size > 1 else 0.0
|
| 481 |
+
return {'null_mean': mu, 'null_sd': sd, 'excess': ce - mu, 'z': (ce - mu) / sd if sd > _EPS else None,
|
| 482 |
+
'p': float((1 + int((null >= ce - 1e-12).sum())) / (1 + null.size))}
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def successor_block_null(states: Any, n_states: int, labels_batch: Any, *, alpha: float = 1.0, draws: int = 99,
|
| 486 |
+
block: int | None = None, seed: int = 0) -> dict[str, Any]:
|
| 487 |
+
"""CE of a state sequence (best of the coarse-grainings in ``labels_batch``) against a successor
|
| 488 |
+
block-permutation null.
|
| 489 |
+
|
| 490 |
+
The TPM is estimated from the pairs ``(s_t, s_{t+1})`` with smoothing ``alpha``. In each of ``draws`` null
|
| 491 |
+
draws the successor sequence ``s_{1..T}`` is block-permuted (blocks of ``block`` steps keep their order,
|
| 492 |
+
default ``round(transitions^(1/3))``) against the unchanged ``s_{0..T-1}``: every state keeps its visit count
|
| 493 |
+
and the successor marginal is kept, but lag-1 dependence is broken. The best coarse-graining is searched again
|
| 494 |
+
per draw. Returns observed EI/CE, the best partition, the null CE values and ``z`` / one-sided ``p``."""
|
| 495 |
+
n = _check_int('n_states', n_states, 2, _MAX_STATES)
|
| 496 |
+
s = _state_sequence(states, n, min_len=3)
|
| 497 |
+
chunks = _candidate_chunks(labels_batch, n)
|
| 498 |
+
alpha = _check_float('alpha', alpha, 0.0, 1e6)
|
| 499 |
+
draws = _check_int('draws', draws, 2, 100_000)
|
| 500 |
+
block = None if block is None else _check_int('block', block, 1, s.size - 1)
|
| 501 |
+
return _successor_block_null(s, n, chunks, alpha, draws, block, _check_int('seed', seed, 0, 2**31 - 1))
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
def _successor_null_values(cur: np.ndarray, nxt: np.ndarray, n: int, chunks: Sequence[_Candidates], alpha: float,
|
| 505 |
+
draws: int, block: int, rng: np.random.Generator) -> np.ndarray:
|
| 506 |
+
"""Null CE values with the successor sequence block-permuted against the current-state sequence."""
|
| 507 |
+
out = np.empty(draws)
|
| 508 |
+
for b in range(draws):
|
| 509 |
+
m_b, e_b, k_b = _ce_of_pairs(cur, nxt[block_permutation(cur.size, block, rng)], n, alpha, chunks)
|
| 510 |
+
out[b] = float(e_b[k_b]) - m_b
|
| 511 |
+
return out
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def _successor_block_null(s: np.ndarray, n: int, chunks: Sequence[_Candidates], alpha: float, draws: int,
|
| 515 |
+
block: int | None, seed: int) -> dict[str, Any]:
|
| 516 |
+
""":func:`successor_block_null` on validated inputs and pre-built candidate chunks."""
|
| 517 |
+
cur, nxt = s[:-1], s[1:]
|
| 518 |
+
block = _default_block(cur.size) if block is None else int(block)
|
| 519 |
+
rng = np.random.default_rng(seed + _NULL_OFFSET)
|
| 520 |
+
micro, eis, k = _ce_of_pairs(cur, nxt, n, alpha, chunks)
|
| 521 |
+
ce = float(eis[k]) - micro
|
| 522 |
+
null = _successor_null_values(cur, nxt, n, chunks, alpha, draws, block, rng)
|
| 523 |
+
labels = np.concatenate([c.labels for c in chunks])
|
| 524 |
+
return {'ei_micro': micro, 'ei_macro': float(eis[k]), 'ce': ce, 'best_index': k, 'labels': labels[k].copy(),
|
| 525 |
+
'null_ce': null, 'draws': draws, 'block': block, 'alpha': alpha, 'transitions': int(cur.size),
|
| 526 |
+
**_null_stats(ce, null)}
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
def _indep_null_values(states: np.ndarray, n_units: int, chunks: Sequence[_Candidates], alpha: float, draws: int,
|
| 530 |
+
rng: np.random.Generator) -> np.ndarray:
|
| 531 |
+
"""Null CE values with every unit's bit sequence circularly shifted by its own offset in ``[1, L - 1]``."""
|
| 532 |
+
L = int(states.size)
|
| 533 |
+
bits = (states[:, None] >> np.arange(n_units, dtype=np.int64)) & 1
|
| 534 |
+
weights = np.left_shift(1, np.arange(n_units, dtype=np.int64))
|
| 535 |
+
rows, cols = np.arange(L, dtype=np.int64)[:, None], np.arange(n_units, dtype=np.int64)[None, :]
|
| 536 |
+
out = np.empty(draws)
|
| 537 |
+
for b in range(draws):
|
| 538 |
+
shifted = bits[(rows - rng.integers(1, L, n_units)[None, :]) % L, cols] @ weights # np.roll per unit
|
| 539 |
+
micro, eis, k = _ce_of_pairs(shifted[:-1], shifted[1:], 2 ** n_units, alpha, chunks)
|
| 540 |
+
out[b] = float(eis[k]) - micro
|
| 541 |
+
return out
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
def independent_units_null(states: Any, n_units: int, labels_batch: Any, *, alpha: float = 1.0, draws: int = 99,
|
| 545 |
+
seed: int = 0) -> dict[str, Any]:
|
| 546 |
+
"""CE of a binary-unit state sequence against an independent-units null.
|
| 547 |
+
|
| 548 |
+
``states`` encode ``n_units`` binary units (bit ``j`` of a state is unit ``j``, see :func:`encode_bits`). In
|
| 549 |
+
each of ``draws`` null draws every unit's bit sequence is circularly shifted by its own random offset in
|
| 550 |
+
``[1, L - 1]``: each unit keeps its occupancy and autocorrelation (up to one wrap-around transition) while the
|
| 551 |
+
units become independent of each other. The best coarse-graining in ``labels_batch`` (``(K, 2^n_units)``) is
|
| 552 |
+
searched again per draw. A large ``z`` says the coarse-grained description gains from coordination between
|
| 553 |
+
units beyond what the units' own dynamics, and the estimator's finite-sample behaviour on them, give."""
|
| 554 |
+
u = _check_int('n_units', n_units, 2, 11)
|
| 555 |
+
n = 2 ** u
|
| 556 |
+
s = _state_sequence(states, n, min_len=3)
|
| 557 |
+
chunks = _candidate_chunks(labels_batch, n)
|
| 558 |
+
alpha = _check_float('alpha', alpha, 0.0, 1e6)
|
| 559 |
+
draws = _check_int('draws', draws, 2, 100_000)
|
| 560 |
+
rng = np.random.default_rng(_check_int('seed', seed, 0, 2**31 - 1) + _INDEP_OFFSET)
|
| 561 |
+
micro, eis, k = _ce_of_pairs(s[:-1], s[1:], n, alpha, chunks)
|
| 562 |
+
ce = float(eis[k]) - micro
|
| 563 |
+
null = _indep_null_values(s, u, chunks, alpha, draws, rng)
|
| 564 |
+
labels = np.concatenate([c.labels for c in chunks])
|
| 565 |
+
return {'ei_micro': micro, 'ei_macro': float(eis[k]), 'ce': ce, 'best_index': k, 'labels': labels[k].copy(),
|
| 566 |
+
'null_ce': null, 'draws': draws, 'alpha': alpha, 'transitions': int(s.size - 1), **_null_stats(ce, null)}
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
def _ce_and_nulls(seq: np.ndarray, n_units: int, chunks: Sequence[_Candidates], alpha: float, draws: int,
|
| 570 |
+
block: int | None, rng_successor: np.random.Generator,
|
| 571 |
+
rng_independent: np.random.Generator) -> dict[str, Any]:
|
| 572 |
+
"""Observed CE of a binary-unit state sequence plus both null summaries (shared by the observer and the lab)."""
|
| 573 |
+
n = 2 ** n_units
|
| 574 |
+
cur, nxt = seq[:-1], seq[1:]
|
| 575 |
+
micro, eis, k = _ce_of_pairs(cur, nxt, n, alpha, chunks)
|
| 576 |
+
ce = float(eis[k]) - micro
|
| 577 |
+
blk = min(_default_block(cur.size) if block is None else int(block), int(cur.size))
|
| 578 |
+
succ = _successor_null_values(cur, nxt, n, chunks, alpha, draws, blk, rng_successor)
|
| 579 |
+
indep = _indep_null_values(seq, n_units, chunks, alpha, draws, rng_independent)
|
| 580 |
+
return {'ei_micro': micro, 'ei_macro': float(eis[k]), 'best_index': k, 'ce': ce, 'block': blk,
|
| 581 |
+
'successor': _null_stats(ce, succ), 'independent': _null_stats(ce, indep)}
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
# ====================================================================== published toy systems
|
| 585 |
+
def hoel2017_examples() -> dict[str, np.ndarray]:
|
| 586 |
+
"""The Markov chains printed in Hoel (2017): ``M1``, ``M2``, ``M3`` (EI 2, 1, 0 bits), the 8-state chain ``Sm``
|
| 587 |
+
(seven states mix uniformly among themselves, the eighth is absorbing), its variant with unequal rows, and the
|
| 588 |
+
4-state channel ``X -> Y`` of the channel-capacity section (three states mix uniformly, the fourth is
|
| 589 |
+
absorbing; printed EI 0.81 bits at the micro scale and 1 bit for the macro code {x1, x2, x3} -> 0, x4 -> 1)."""
|
| 590 |
+
third, F = 1.0 / 3.0, Fraction
|
| 591 |
+
chain = np.zeros((8, 8))
|
| 592 |
+
chain[:7, :7] = 1.0 / 7.0
|
| 593 |
+
chain[7, 7] = 1.0
|
| 594 |
+
varied = [[F(1, 5)] * 5 + [0, 0, 0],
|
| 595 |
+
[F(1, 7), F(3, 7), F(1, 7), 0, F(1, 7), 0, F(1, 7), 0],
|
| 596 |
+
[0] + [F(1, 6)] * 6 + [0],
|
| 597 |
+
[F(1, 7), 0, F(1, 7), F(1, 7), F(1, 7), F(1, 7), F(2, 7), 0],
|
| 598 |
+
[F(1, 9), F(2, 9), F(2, 9), F(1, 9), 0, F(2, 9), F(1, 9), 0],
|
| 599 |
+
[F(1, 7)] * 7 + [0],
|
| 600 |
+
[F(1, 6), F(1, 6), 0, F(1, 6), F(1, 6), F(1, 6), F(1, 6), 0],
|
| 601 |
+
[0] * 7 + [1]]
|
| 602 |
+
return {'M1': np.array([[0, 0, 1, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0]], dtype=np.float64),
|
| 603 |
+
'M2': np.array([[third, third, third, 0], [third, third, third, 0], [0, 0, 0, 1], [0, 0, 0, 1]]),
|
| 604 |
+
'M3': np.full((4, 4), 0.25), 'chain8': chain,
|
| 605 |
+
'chain8_varied': np.array([[float(x) for x in row] for row in varied]),
|
| 606 |
+
'channel4': np.array([[third, third, third, 0], [third, third, third, 0], [third, third, third, 0],
|
| 607 |
+
[0, 0, 0, 1]])}
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
def and_gate_network(pairs: int = 3) -> tuple[np.ndarray, np.ndarray]:
|
| 611 |
+
"""Deterministic ring of ``2 * pairs`` AND gates in the spirit of Hoel et al. (2013, Fig. 4): both elements of
|
| 612 |
+
pair ``k`` compute AND of the two elements of pair ``k + 1`` (mod ``pairs``). Bit ``2k`` and ``2k + 1`` of a
|
| 613 |
+
state belong to pair ``k``. Returns the micro TPM and the macro labels that map each pair to one element that
|
| 614 |
+
is on only when both of its micro elements are on (the macro elements then copy each other around the ring)."""
|
| 615 |
+
p = _check_int('pairs', pairs, 1, 5)
|
| 616 |
+
u = 2 * p
|
| 617 |
+
states = np.arange(2 ** u, dtype=np.int64)
|
| 618 |
+
bits = (states[:, None] >> np.arange(u, dtype=np.int64)) & 1
|
| 619 |
+
pair_and = bits[:, 0::2] & bits[:, 1::2]
|
| 620 |
+
nxt_bits = np.repeat(np.roll(pair_and, -1, axis=1), 2, axis=1)
|
| 621 |
+
nxt = (nxt_bits << np.arange(u, dtype=np.int64)).sum(axis=1)
|
| 622 |
+
T = np.zeros((2 ** u, 2 ** u))
|
| 623 |
+
T[states, nxt] = 1.0
|
| 624 |
+
return T, (pair_and << np.arange(p, dtype=np.int64)).sum(axis=1)
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
def pair_count_copy_tpm(pairs: int = 3, noise: float = 0.1) -> np.ndarray:
|
| 628 |
+
"""Exact micro TPM of a ring of binary-unit pairs whose active-unit *counts* copy each other.
|
| 629 |
+
|
| 630 |
+
Pair ``k`` (units ``2k`` and ``2k + 1``) takes the count of pair ``k + 1`` (mod ``pairs``) with probability
|
| 631 |
+
``1 - noise`` and a uniformly random count in {0, 1, 2} otherwise; count 1 is realised as either unit alone
|
| 632 |
+
with probability 1/2. The pair counts follow near-deterministic macro dynamics over a degenerate, noisy micro
|
| 633 |
+
realisation, so the count-per-pair coarse-graining has higher EI than the micro TPM. This is a constructed
|
| 634 |
+
known-answer system in the spirit of Hoel et al. (2013), not an example printed there."""
|
| 635 |
+
p = _check_int('pairs', pairs, 1, 5)
|
| 636 |
+
eps = _check_float('noise', noise, 0.0, 1.0)
|
| 637 |
+
u, n = 2 * p, 4 ** p
|
| 638 |
+
bits = decode_states(np.arange(n), u).astype(np.int64)
|
| 639 |
+
counts = bits[:, 0::2] + bits[:, 1::2] # (n, pairs) counts of the current state
|
| 640 |
+
p_count = (1.0 - eps) * (np.roll(counts, -1, axis=1)[:, :, None] == np.arange(3)) + eps / 3.0
|
| 641 |
+
# P(pair micro state | count) for pair micro index b0 + 2 b1 = 00, 10, 01, 11
|
| 642 |
+
realise = np.array([[1.0, 0.0, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.0, 1.0]])
|
| 643 |
+
T = np.ones((n, n))
|
| 644 |
+
for k in range(p):
|
| 645 |
+
T *= p_count[:, k, :] @ realise[bits[:, 2 * k] + 2 * bits[:, 2 * k + 1]].T
|
| 646 |
+
return T
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
def noisy_permutation_tpm(n: int, noise: float, *, seed: int = 0) -> np.ndarray:
|
| 650 |
+
"""``(1 - noise) P + noise / n`` for a seeded random ``n x n`` permutation matrix ``P``.
|
| 651 |
+
|
| 652 |
+
Every row is a permutation of every other row and all column sums are 1, so the TPM is a weakly symmetric
|
| 653 |
+
channel. Uniform inputs achieve its capacity, and since a coarse-graining only changes the input distribution
|
| 654 |
+
(uniform over macro states) and post-processes inputs and outputs, no coarse-graining has a larger EI: the
|
| 655 |
+
exact CE of every partition is <= 0 (Hoel 2017: no causal emergence without asymmetry)."""
|
| 656 |
+
n = _check_int('n', n, 2, _MAX_STATES)
|
| 657 |
+
eps = _check_float('noise', noise, 0.0, 1.0)
|
| 658 |
+
P = np.eye(n)[np.random.default_rng(_check_int('seed', seed, 0, 2**31 - 1) + _PERM8_OFFSET).permutation(n)]
|
| 659 |
+
return (1.0 - eps) * P + eps / n
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
def independent_flip_tpm(n_units: int, keep: float) -> np.ndarray:
|
| 663 |
+
"""Exact micro TPM of ``n_units`` independent binary units that each keep their state with probability
|
| 664 |
+
``keep`` and flip otherwise (bit ``j`` of a state is unit ``j``)."""
|
| 665 |
+
u = _check_int('n_units', n_units, 1, 11)
|
| 666 |
+
q = _check_float('keep', keep, 0.0, 1.0)
|
| 667 |
+
bits = decode_states(np.arange(2 ** u), u)
|
| 668 |
+
same = (bits[:, None, :] == bits[None, :, :]).sum(axis=2)
|
| 669 |
+
return q ** same * (1.0 - q) ** (u - same)
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
def _sample_pair_count_copy(pairs: int, noise: float, steps: int, rng: np.random.Generator) -> np.ndarray:
|
| 673 |
+
c = rng.integers(0, 3, pairs)
|
| 674 |
+
out = np.zeros((steps, 2 * pairs), dtype=np.int64)
|
| 675 |
+
for t in range(steps):
|
| 676 |
+
c = np.where(rng.random(pairs) < noise, rng.integers(0, 3, pairs), np.roll(c, -1))
|
| 677 |
+
second = rng.integers(0, 2, pairs) == 1 # which unit realises a count of 1
|
| 678 |
+
out[t, 0::2] = (c == 2) | ((c == 1) & ~second)
|
| 679 |
+
out[t, 1::2] = (c == 2) | ((c == 1) & second)
|
| 680 |
+
return out
|
| 681 |
+
|
| 682 |
+
|
| 683 |
+
def _sample_independent_flips(n_units: int, keep: float, steps: int, rng: np.random.Generator) -> np.ndarray:
|
| 684 |
+
start = rng.integers(0, 2, n_units)
|
| 685 |
+
return (start[None, :] + np.cumsum(rng.random((steps, n_units)) >= keep, axis=0)) % 2
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
PRINTED_VALUES: dict[str, float] = {
|
| 689 |
+
# Hoel (2017), Entropy 19:188, as printed in its preprint arXiv:1612.09592v1 (usually 2 decimals)
|
| 690 |
+
'hoel2017_M1_ei': 2.0, 'hoel2017_M2_ei': 1.0, 'hoel2017_M3_ei': 0.0,
|
| 691 |
+
'hoel2017_chain8_ei_micro': 0.55, 'hoel2017_chain8_effectiveness': 0.18, 'hoel2017_chain8_ei_macro': 1.0,
|
| 692 |
+
'hoel2017_chain8_ce': 0.45, 'hoel2017_chain8_varied_ei_micro': 0.81, 'hoel2017_chain8_varied_ei_macro': 1.0,
|
| 693 |
+
'hoel2017_and_ei_micro': 2.43, 'hoel2017_and_effectiveness': 0.41, 'hoel2017_and_degeneracy': 0.59,
|
| 694 |
+
'hoel2017_and_ei_macro': 3.0, 'hoel2017_channel4_ei_micro': 0.81, 'hoel2017_channel4_conditional_entropy': 1.19,
|
| 695 |
+
'hoel2017_channel4_ei_macro': 1.0,
|
| 696 |
+
# Hoel, Albantakis & Tononi (2013), PNAS 110:19790, Fig. 4 (six AND gates -> three COPY gates)
|
| 697 |
+
'hoel2013_and_ei_micro': 2.43, 'hoel2013_and_effectiveness': 0.4, 'hoel2013_and_determinism': 1.0,
|
| 698 |
+
'hoel2013_and_degeneracy': 0.6, 'hoel2013_and_ei_macro': 3.0, 'hoel2013_and_ce': 0.57,
|
| 699 |
+
}
|
| 700 |
+
|
| 701 |
+
|
| 702 |
+
# ====================================================================== live observer
|
| 703 |
+
class CausalEmergenceObserver:
|
| 704 |
+
"""Read-only live observer: EI and causal emergence of a few discretised units.
|
| 705 |
+
|
| 706 |
+
* ``u = min(units, n_units)`` units (``2 <= u <= 6``; a seeded, sorted subset when ``n_units > units``) are
|
| 707 |
+
binarised online: each new value is compared with the median of that unit's last ``history`` raw values
|
| 708 |
+
(including the new one), so a unit is on when it is above its running median (a value tied with the median
|
| 709 |
+
is on when more of the window lies below the median than above it, which keeps discrete 0/1 units intact).
|
| 710 |
+
The ``2^u`` micro states of the last ``history`` observations are kept in a ring buffer (bounded transition
|
| 711 |
+
counts). With ``alpha = 1`` every row of the ``2^u``-state TPM receives ``2^u`` pseudo-counts, so until there
|
| 712 |
+
are many transitions per micro state (``transitions_per_micro_state``) EI estimates are shrunk far below the
|
| 713 |
+
exact values; the nulls below, not the raw ``ce``, carry the evidence.
|
| 714 |
+
* ``summary()`` estimates the micro TPM (smoothing ``alpha``; 1 = Laplace) from the buffered transitions and
|
| 715 |
+
reports micro EI with determinism/degeneracy, the best count-per-group coarse-graining over every partition
|
| 716 |
+
of the units (the micro description excluded) and ``ce = ei_macro - ei_micro``. Once ``min_transitions``
|
| 717 |
+
transitions exist (default ``min(32, history - 1)``) it adds two nulls of ``null_draws`` draws each, seeded
|
| 718 |
+
by ``(seed, observed steps)``: the successor block permutation (``null_ce_mean``, ``null_ce_sd``,
|
| 719 |
+
``ce_excess``, ``ce_z``, ``ce_p``: is CE above what temporally independent data give?) and the
|
| 720 |
+
independent-units circular shift (``indep_ce_mean``, ``indep_ce_sd``, ``ce_excess_indep``, ``ce_z_indep``,
|
| 721 |
+
``ce_p_indep``: is CE above what the same units give when they are made independent?). The smallest
|
| 722 |
+
attainable p is ``1 / (null_draws + 1)`` (0.05 at the default 19 draws). With few transitions per micro
|
| 723 |
+
state the successor null flags any temporal dependence (see the module docstring); read emergence claims
|
| 724 |
+
against the independent-units null and the lab's known-answer checks.
|
| 725 |
+
* Results are a pure function of the buffered state and are cached per observed step, so they do not depend
|
| 726 |
+
on how often ``summary()`` is called. Unit indices refer to positions in the observed vector. FrontierSpecV1
|
| 727 |
+
parameters meant for other observers are accepted and ignored."""
|
| 728 |
+
|
| 729 |
+
module_id = MODULE_ID
|
| 730 |
+
schema = OBSERVER_STATE_SCHEMA
|
| 731 |
+
|
| 732 |
+
def __init__(self, n_units: int, *, seed: int = 7, history: int = 256, units: int = 6, alpha: float = 1.0,
|
| 733 |
+
null_draws: int = 19, block: int | None = None, min_transitions: int | None = None,
|
| 734 |
+
**params: Any) -> None:
|
| 735 |
+
unknown = sorted(set(params) - _SPEC_OBSERVER_PARAMS)
|
| 736 |
+
if unknown:
|
| 737 |
+
raise ValueError(f'unknown CausalEmergenceObserver parameters: {unknown}')
|
| 738 |
+
self.n_units = _check_int('n_units', n_units, 2, 1_000_000)
|
| 739 |
+
self.seed = _check_int('seed', seed, 0, 2**31 - 1)
|
| 740 |
+
self.history = _check_int('history', history, 16, 8192)
|
| 741 |
+
self.units = _check_int('units', units, 2, _MAX_OBSERVER_UNITS)
|
| 742 |
+
self.alpha = _check_float('alpha', alpha, 0.0, 100.0)
|
| 743 |
+
self.null_draws = _check_int('null_draws', null_draws, 2, 999)
|
| 744 |
+
self.block = None if block is None else _check_int('block', block, 1, self.history)
|
| 745 |
+
self.min_transitions = (min(32, self.history - 1) if min_transitions is None
|
| 746 |
+
else _check_int('min_transitions', min_transitions, 8, self.history - 1))
|
| 747 |
+
m = self.m = min(self.units, self.n_units)
|
| 748 |
+
if m == self.n_units:
|
| 749 |
+
sample = np.arange(m, dtype=np.int64)
|
| 750 |
+
else:
|
| 751 |
+
sample = np.sort(np.random.default_rng(self.seed + _OBS_UNITS_OFFSET).choice(self.n_units, m, replace=False))
|
| 752 |
+
self._units = sample.astype(np.int64)
|
| 753 |
+
self.n_states = 2 ** m
|
| 754 |
+
cand = unit_sum_candidates(m)
|
| 755 |
+
self._groups = cand['groups']
|
| 756 |
+
self._chunks = _candidate_chunks(cand['labels'], self.n_states, cand['m'])
|
| 757 |
+
self._bit_weights = np.left_shift(1, np.arange(m, dtype=np.int64))
|
| 758 |
+
self.reset()
|
| 759 |
+
|
| 760 |
+
@classmethod
|
| 761 |
+
def from_spec(cls, n_units: int, spec: Any, **params: Any) -> 'CausalEmergenceObserver':
|
| 762 |
+
"""Observer sized from a :class:`~synapse.frontier.spec.FrontierSpecV1` (``seed``, ``history``); ``params``
|
| 763 |
+
are the observer's own keyword parameters (``units``, ``alpha``, ...)."""
|
| 764 |
+
if not isinstance(spec, FrontierSpecV1):
|
| 765 |
+
raise ValueError('spec must be a FrontierSpecV1')
|
| 766 |
+
return cls(n_units, seed=int(spec.seed), history=int(spec.history), **params)
|
| 767 |
+
|
| 768 |
+
def config(self) -> dict[str, Any]:
|
| 769 |
+
return {'n_units': self.n_units, 'seed': self.seed, 'history': self.history, 'units': self.units,
|
| 770 |
+
'alpha': self.alpha, 'null_draws': self.null_draws, 'block': self.block,
|
| 771 |
+
'min_transitions': self.min_transitions}
|
| 772 |
+
|
| 773 |
+
def reset(self) -> None:
|
| 774 |
+
self._raw = np.zeros((self.history, self.m))
|
| 775 |
+
self._states = np.zeros(self.history, dtype=np.int64)
|
| 776 |
+
self._pos = 0
|
| 777 |
+
self._filled = 0
|
| 778 |
+
self._steps = 0
|
| 779 |
+
self._cache: tuple[int, dict[str, Any]] | None = None
|
| 780 |
+
|
| 781 |
+
@property
|
| 782 |
+
def observed_steps(self) -> int:
|
| 783 |
+
return int(self._steps)
|
| 784 |
+
|
| 785 |
+
@property
|
| 786 |
+
def units_observed(self) -> np.ndarray:
|
| 787 |
+
return self._units.copy()
|
| 788 |
+
|
| 789 |
+
def _encode(self, raw: np.ndarray, buffer: np.ndarray) -> int:
|
| 790 |
+
return int((_above_median(raw, buffer).astype(np.int64) * self._bit_weights).sum())
|
| 791 |
+
|
| 792 |
+
def observe(self, x: np.ndarray) -> None:
|
| 793 |
+
try:
|
| 794 |
+
v = np.asarray(x, dtype=np.float64)
|
| 795 |
+
except (TypeError, ValueError) as exc:
|
| 796 |
+
raise ValueError(f'observation must be a finite 1-D array of length {self.n_units}') from exc
|
| 797 |
+
if v.shape != (self.n_units,) or not np.all(np.isfinite(v)):
|
| 798 |
+
raise ValueError(f'observation must be a finite 1-D array of length {self.n_units}')
|
| 799 |
+
raw = v[self._units] # fancy indexing copies; the input is never written
|
| 800 |
+
p = self._pos
|
| 801 |
+
self._raw[p] = raw
|
| 802 |
+
self._filled = min(self.history, self._filled + 1)
|
| 803 |
+
self._states[p] = self._encode(raw, self._raw[:self._filled])
|
| 804 |
+
self._pos = (p + 1) % self.history
|
| 805 |
+
self._steps += 1
|
| 806 |
+
self._cache = None
|
| 807 |
+
|
| 808 |
+
def _sequence(self) -> np.ndarray:
|
| 809 |
+
if self._filled < self.history:
|
| 810 |
+
return self._states[:self._filled].copy()
|
| 811 |
+
return np.concatenate([self._states[self._pos:], self._states[:self._pos]])
|
| 812 |
+
|
| 813 |
+
def _compute(self) -> dict[str, Any]:
|
| 814 |
+
seq = self._sequence()
|
| 815 |
+
cur, nxt = seq[:-1], seq[1:]
|
| 816 |
+
n = self.n_states
|
| 817 |
+
micro_T = _smoothed(_counts(cur, nxt, n), self.alpha)
|
| 818 |
+
micro = _decomposition(micro_T)
|
| 819 |
+
eis = _batch_ei(micro_T, self._chunks)
|
| 820 |
+
k = int(np.argmax(eis))
|
| 821 |
+
labels = np.concatenate([c.labels for c in self._chunks])[k]
|
| 822 |
+
macro = _decomposition(coarse_grain_tpm(micro_T, labels))
|
| 823 |
+
ce = float(eis[k]) - micro['ei']
|
| 824 |
+
out: dict[str, Any] = {
|
| 825 |
+
'visited_states': int(np.unique(cur).size), 'ei_micro': micro['ei'],
|
| 826 |
+
'determinism_micro': micro['determinism'], 'degeneracy_micro': micro['degeneracy'],
|
| 827 |
+
'effectiveness_micro': micro['effectiveness'], 'ei_macro': float(eis[k]),
|
| 828 |
+
'determinism_macro': macro['determinism'], 'degeneracy_macro': macro['degeneracy'],
|
| 829 |
+
'macro_partition': _groups(self._groups[k], self._units), 'macro_states': int(macro['states']),
|
| 830 |
+
'ce': ce, 'null_ready': False, 'null_block': None, 'null_ce_mean': None, 'null_ce_sd': None,
|
| 831 |
+
'ce_excess': None, 'ce_z': None, 'ce_p': None, 'indep_ce_mean': None, 'indep_ce_sd': None,
|
| 832 |
+
'ce_excess_indep': None, 'ce_z_indep': None, 'ce_p_indep': None}
|
| 833 |
+
if cur.size >= self.min_transitions:
|
| 834 |
+
res = _ce_and_nulls(seq, self.m, self._chunks, self.alpha, self.null_draws, self.block,
|
| 835 |
+
np.random.default_rng([self.seed + _OBS_NULL_OFFSET, self._steps]),
|
| 836 |
+
np.random.default_rng([self.seed + _OBS_INDEP_OFFSET, self._steps]))
|
| 837 |
+
st, si = res['successor'], res['independent']
|
| 838 |
+
out.update(null_ready=True, null_block=int(res['block']), null_ce_mean=st['null_mean'],
|
| 839 |
+
null_ce_sd=st['null_sd'], ce_excess=st['excess'], ce_z=st['z'], ce_p=st['p'],
|
| 840 |
+
indep_ce_mean=si['null_mean'], indep_ce_sd=si['null_sd'], ce_excess_indep=si['excess'],
|
| 841 |
+
ce_z_indep=si['z'], ce_p_indep=si['p'])
|
| 842 |
+
return out
|
| 843 |
+
|
| 844 |
+
_METRIC_KEYS = ('visited_states', 'ei_micro', 'determinism_micro', 'degeneracy_micro', 'effectiveness_micro',
|
| 845 |
+
'ei_macro', 'determinism_macro', 'degeneracy_macro', 'macro_partition', 'macro_states', 'ce',
|
| 846 |
+
'null_ready', 'null_block', 'null_ce_mean', 'null_ce_sd', 'ce_excess', 'ce_z', 'ce_p',
|
| 847 |
+
'indep_ce_mean', 'indep_ce_sd', 'ce_excess_indep', 'ce_z_indep', 'ce_p_indep')
|
| 848 |
+
|
| 849 |
+
def summary(self) -> dict[str, Any]:
|
| 850 |
+
"""JSON-safe metrics (``None`` until the first transition; null fields once ``min_transitions`` exist)."""
|
| 851 |
+
transitions = max(0, self._filled - 1)
|
| 852 |
+
out: dict[str, Any] = {'module': MODULE_ID, 'evidence_tier': EVIDENCE_TIER, 'n_units': self.n_units,
|
| 853 |
+
'analysed_units': int(self.m), 'unit_sample': self._units.tolist(),
|
| 854 |
+
'history': self.history, 'micro_states': int(self.n_states), 'alpha': self.alpha,
|
| 855 |
+
'null_draws': self.null_draws, 'min_transitions': self.min_transitions,
|
| 856 |
+
'observed_steps': int(self._steps), 'buffered': int(self._filled),
|
| 857 |
+
'transitions': int(transitions),
|
| 858 |
+
'transitions_per_micro_state': float(transitions / self.n_states)}
|
| 859 |
+
if transitions == 0:
|
| 860 |
+
out.update({k: None for k in self._METRIC_KEYS})
|
| 861 |
+
out['null_ready'] = False
|
| 862 |
+
return out
|
| 863 |
+
if self._cache is None or self._cache[0] != self._steps:
|
| 864 |
+
self._cache = (self._steps, self._compute())
|
| 865 |
+
metrics = self._cache[1]
|
| 866 |
+
out.update({k: ([list(g) for g in v] if k == 'macro_partition' else v) for k, v in metrics.items()})
|
| 867 |
+
return out
|
| 868 |
+
|
| 869 |
+
def export_state(self) -> dict[str, Any]:
|
| 870 |
+
return {'module': MODULE_ID, 'schema': self.schema, 'config': self.config(), 'units': self._units.tolist(),
|
| 871 |
+
'raw': self._raw.tolist(), 'states': self._states.tolist(), 'pos': int(self._pos),
|
| 872 |
+
'filled': int(self._filled), 'steps': int(self._steps)}
|
| 873 |
+
|
| 874 |
+
def import_state(self, state: Mapping[str, Any]) -> None:
|
| 875 |
+
"""Validate the whole state first (configuration, shapes, counters and, where the raw values are still
|
| 876 |
+
buffered, that every stored state is the median-binarisation of its raw values); then replace."""
|
| 877 |
+
if not isinstance(state, Mapping) or state.get('module') != MODULE_ID or state.get('schema') != self.schema:
|
| 878 |
+
raise ValueError('state does not belong to a CausalEmergenceObserver')
|
| 879 |
+
try:
|
| 880 |
+
cfg = dict(state['config'])
|
| 881 |
+
units = state['units']
|
| 882 |
+
raw = np.array(state['raw'], dtype=np.float64)
|
| 883 |
+
st = np.array(state['states'])
|
| 884 |
+
pos, filled, steps = state['pos'], state['filled'], state['steps']
|
| 885 |
+
except (KeyError, TypeError, ValueError) as exc:
|
| 886 |
+
raise ValueError('CausalEmergenceObserver state is incomplete or malformed') from exc
|
| 887 |
+
if cfg != self.config() or units != self._units.tolist():
|
| 888 |
+
raise ValueError('CausalEmergenceObserver state was made with a different configuration')
|
| 889 |
+
H = self.history
|
| 890 |
+
if raw.shape != (H, self.m) or not np.all(np.isfinite(raw)):
|
| 891 |
+
raise ValueError('raw buffer has the wrong shape or non-finite values')
|
| 892 |
+
if st.shape != (H,) or (st.size and st.dtype.kind not in 'iu') or np.any(st < 0) or np.any(st >= self.n_states):
|
| 893 |
+
raise ValueError('state buffer must hold one micro state in [0, 2^units) per history row')
|
| 894 |
+
if not all(type(v) is int for v in (pos, filled, steps)) or not (0 <= pos < H and 0 <= filled <= H
|
| 895 |
+
and filled == min(steps, H)):
|
| 896 |
+
raise ValueError('CausalEmergenceObserver counters are inconsistent')
|
| 897 |
+
if pos != steps % H:
|
| 898 |
+
raise ValueError('CausalEmergenceObserver ring-buffer position is inconsistent')
|
| 899 |
+
st = st.astype(np.int64)
|
| 900 |
+
if filled < H and (np.any(raw[filled:] != 0.0) or np.any(st[filled:] != 0)):
|
| 901 |
+
raise ValueError('buffers hold values beyond the observed steps')
|
| 902 |
+
if steps <= H: # every raw value is still buffered: check them all
|
| 903 |
+
ok = all(st[t] == self._encode(raw[t], raw[:t + 1]) for t in range(filled))
|
| 904 |
+
else: # only the newest state's median is still known
|
| 905 |
+
last = (pos - 1) % H
|
| 906 |
+
ok = st[last] == self._encode(raw[last], raw)
|
| 907 |
+
if not ok:
|
| 908 |
+
raise ValueError('stored states are not the median-binarisation of the raw buffer')
|
| 909 |
+
self._raw, self._states = raw.copy(), st.copy()
|
| 910 |
+
self._pos, self._filled, self._steps = pos, filled, steps
|
| 911 |
+
self._cache = None
|
| 912 |
+
|
| 913 |
+
|
| 914 |
+
# ====================================================================== lab experiment
|
| 915 |
+
_MECH_DYNAMICS = ('sparse_code', 'synaptic_delays', 'membrane_dynamics')
|
| 916 |
+
_PAIR_GROUPS = [[0, 1], [2, 3], [4, 5]]
|
| 917 |
+
_SEVEN_PLUS_ONE = [0] * 7 + [1]
|
| 918 |
+
_DEFAULTS: dict[str, Any] = {
|
| 919 |
+
'sizes': (2, 4, 8, 16, 32), 'alpha': 1.0, 'estimation_samples': 16_000, 'estimation_tolerance': 0.05,
|
| 920 |
+
'null_steps': 512, 'null_draws': 199, 'null_replicates': 10, 'emergence_noise': 0.1, 'permutation_noise': 0.3,
|
| 921 |
+
'unit_steps': 1024, 'unit_draws': 49, 'unit_replicates': 4, 'pair_copy_noise': 0.1, 'independent_keep': 0.9,
|
| 922 |
+
# 4 units (16 micro states) for the NEUROWEAVE report: ~11 (quick) / ~34 (default) transitions per micro
|
| 923 |
+
# state, against ~3 / ~9 with the observer's default of 6 units (64 states)
|
| 924 |
+
'units': 4, 'topology': 'clustered', 'neurons': 32, 'nw_steps': 600, 'nw_burn_in': 50, 'nw_null_draws': 49,
|
| 925 |
+
'mechanism_sets': {'baseline': (), 'dynamics': _MECH_DYNAMICS},
|
| 926 |
+
}
|
| 927 |
+
_QUICK: dict[str, Any] = {'estimation_samples': 4000, 'null_steps': 384, 'null_draws': 39, 'null_replicates': 2,
|
| 928 |
+
'unit_steps': 512, 'unit_draws': 19, 'unit_replicates': 1, 'neurons': 24, 'nw_steps': 200,
|
| 929 |
+
'nw_burn_in': 24, 'nw_null_draws': 19}
|
| 930 |
+
|
| 931 |
+
|
| 932 |
+
def _validate_config(cfg: dict[str, Any]) -> dict[str, Any]:
|
| 933 |
+
from ..neuroweave.spec import MECHANISM_IDS, TOPOLOGIES
|
| 934 |
+
c = dict(cfg)
|
| 935 |
+
try:
|
| 936 |
+
sizes = tuple(c['sizes'])
|
| 937 |
+
except TypeError as exc:
|
| 938 |
+
raise ValueError('sizes must be a sequence of ints') from exc
|
| 939 |
+
if not sizes or len(set(sizes)) != len(sizes):
|
| 940 |
+
raise ValueError('sizes must be non-empty and distinct')
|
| 941 |
+
c['sizes'] = [_check_int('size', s, 2, 512) for s in sizes]
|
| 942 |
+
c['alpha'] = _check_float('alpha', c['alpha'], 0.0, 100.0)
|
| 943 |
+
c['estimation_samples'] = _check_int('estimation_samples', c['estimation_samples'], 200, 10_000_000)
|
| 944 |
+
c['estimation_tolerance'] = _check_float('estimation_tolerance', c['estimation_tolerance'], 1e-4, 1.0)
|
| 945 |
+
c['null_steps'] = _check_int('null_steps', c['null_steps'], 64, 1_000_000)
|
| 946 |
+
c['null_draws'] = _check_int('null_draws', c['null_draws'], 19, 100_000)
|
| 947 |
+
c['null_replicates'] = _check_int('null_replicates', c['null_replicates'], 1, 10_000)
|
| 948 |
+
c['emergence_noise'] = _check_float('emergence_noise', c['emergence_noise'], 0.01, 0.3)
|
| 949 |
+
c['permutation_noise'] = _check_float('permutation_noise', c['permutation_noise'], 0.01, 0.5)
|
| 950 |
+
c['unit_steps'] = _check_int('unit_steps', c['unit_steps'], 64, 1_000_000)
|
| 951 |
+
c['unit_draws'] = _check_int('unit_draws', c['unit_draws'], 19, 100_000)
|
| 952 |
+
c['unit_replicates'] = _check_int('unit_replicates', c['unit_replicates'], 1, 10_000)
|
| 953 |
+
c['pair_copy_noise'] = _check_float('pair_copy_noise', c['pair_copy_noise'], 0.0, 0.5)
|
| 954 |
+
c['independent_keep'] = _check_float('independent_keep', c['independent_keep'], 0.6, 0.99)
|
| 955 |
+
c['units'] = _check_int('units', c['units'], 2, _MAX_OBSERVER_UNITS)
|
| 956 |
+
if c['topology'] not in TOPOLOGIES:
|
| 957 |
+
raise ValueError(f'topology must be one of {TOPOLOGIES}')
|
| 958 |
+
c['neurons'] = _check_int('neurons', c['neurons'], 8, 512)
|
| 959 |
+
c['nw_steps'] = _check_int('nw_steps', c['nw_steps'], 64, 100_000)
|
| 960 |
+
c['nw_burn_in'] = _check_int('nw_burn_in', c['nw_burn_in'], 0, c['nw_steps'] - 48)
|
| 961 |
+
c['nw_null_draws'] = _check_int('nw_null_draws', c['nw_null_draws'], 2, 999)
|
| 962 |
+
sets = c['mechanism_sets']
|
| 963 |
+
if not isinstance(sets, Mapping) or not 1 <= len(sets) <= 8:
|
| 964 |
+
raise ValueError('mechanism_sets must map 1 to 8 names to NEUROWEAVE mechanism tuples')
|
| 965 |
+
clean: dict[str, list[str]] = {}
|
| 966 |
+
for name, mechs in sets.items():
|
| 967 |
+
if not isinstance(name, str) or not name or isinstance(mechs, str):
|
| 968 |
+
raise ValueError('mechanism_sets must map names to sequences of mechanism ids')
|
| 969 |
+
try:
|
| 970 |
+
mechs = list(mechs)
|
| 971 |
+
except TypeError as exc:
|
| 972 |
+
raise ValueError('mechanism_sets must map names to sequences of mechanism ids') from exc
|
| 973 |
+
if any(m not in MECHANISM_IDS for m in mechs) or len(set(mechs)) != len(mechs):
|
| 974 |
+
raise ValueError('mechanism_sets values must be distinct NEUROWEAVE mechanism ids')
|
| 975 |
+
clean[name] = mechs
|
| 976 |
+
c['mechanism_sets'] = clean
|
| 977 |
+
return c
|
| 978 |
+
|
| 979 |
+
|
| 980 |
+
def _close(a: float, b: float, tol: float) -> bool:
|
| 981 |
+
return bool(abs(float(a) - float(b)) <= tol)
|
| 982 |
+
|
| 983 |
+
|
| 984 |
+
def _exact_checks(c: Mapping[str, Any]) -> tuple[dict[str, Any], dict[str, bool]]:
|
| 985 |
+
"""Seed-independent checks on exactly known TPMs (no sampling)."""
|
| 986 |
+
rng = np.random.default_rng(_PERM_OFFSET)
|
| 987 |
+
sizes = []
|
| 988 |
+
for n in c['sizes']:
|
| 989 |
+
P = np.eye(n)[rng.permutation(n)]
|
| 990 |
+
d_id, d_perm, d_uni = ei_decomposition(np.eye(n)), ei_decomposition(P), ei_decomposition(np.full((n, n), 1.0 / n))
|
| 991 |
+
sizes.append({'n': n, 'log2_n': math.log2(n), 'ei_identity': d_id['ei'], 'ei_permutation': d_perm['ei'],
|
| 992 |
+
'ei_uniform': d_uni['ei'], 'identity_determinism': d_id['determinism'],
|
| 993 |
+
'identity_degeneracy': d_id['degeneracy'], 'uniform_determinism': d_uni['determinism'],
|
| 994 |
+
'uniform_degeneracy': d_uni['degeneracy']})
|
| 995 |
+
ex = hoel2017_examples()
|
| 996 |
+
dec = {k: ei_decomposition(v) for k, v in ex.items()}
|
| 997 |
+
chain_exact = 3.0 - 7.0 / 8.0 * math.log2(7.0)
|
| 998 |
+
search = {k: best_state_partition(ex[k]) for k in ('chain8', 'chain8_varied')}
|
| 999 |
+
channel = best_state_partition(ex['channel4'])
|
| 1000 |
+
T_and, lab_and = and_gate_network(3)
|
| 1001 |
+
ce_and = causal_emergence(T_and, lab_and)
|
| 1002 |
+
p = PRINTED_VALUES
|
| 1003 |
+
hoel = {
|
| 1004 |
+
'M_ei': {k: dec[k]['ei'] for k in ('M1', 'M2', 'M3')},
|
| 1005 |
+
'chain8': {'ei_micro': dec['chain8']['ei'], 'ei_micro_closed_form': chain_exact,
|
| 1006 |
+
'effectiveness': dec['chain8']['effectiveness'], 'ei_macro': search['chain8']['ei_macro'],
|
| 1007 |
+
'ce': search['chain8']['ce'], 'best_labels': search['chain8']['labels'],
|
| 1008 |
+
'partitions_evaluated': search['chain8']['partitions_evaluated']},
|
| 1009 |
+
'chain8_varied': {'ei_micro': dec['chain8_varied']['ei'], 'ei_macro': search['chain8_varied']['ei_macro'],
|
| 1010 |
+
'ce': search['chain8_varied']['ce'], 'best_labels': search['chain8_varied']['labels']},
|
| 1011 |
+
'channel4': {'ei_micro': dec['channel4']['ei'], 'conditional_entropy': 2.0 - dec['channel4']['ei'],
|
| 1012 |
+
'ei_macro': channel['ei_macro'], 'ce': channel['ce'], 'best_labels': channel['labels'],
|
| 1013 |
+
'partitions_evaluated': channel['partitions_evaluated']},
|
| 1014 |
+
'and_gates': {'ei_micro': ce_and['micro']['ei'], 'determinism_micro': ce_and['micro']['determinism'],
|
| 1015 |
+
'degeneracy_micro': ce_and['micro']['degeneracy'],
|
| 1016 |
+
'effectiveness_micro': ce_and['micro']['effectiveness'], 'ei_macro': ce_and['macro']['ei'],
|
| 1017 |
+
'effectiveness_macro': ce_and['macro']['effectiveness'], 'ce': ce_and['ce'],
|
| 1018 |
+
'ei_micro_closed_form': 3.0 * entropy_bits([0.25, 0.75])},
|
| 1019 |
+
'printed': dict(p),
|
| 1020 |
+
}
|
| 1021 |
+
symmetric = []
|
| 1022 |
+
for n in (5, 8): # weakly symmetric channels: no partition beats the micro scale
|
| 1023 |
+
b = best_state_partition(noisy_permutation_tpm(n, c['permutation_noise']))
|
| 1024 |
+
symmetric.append({'n': n, 'noise': c['permutation_noise'], 'ei_micro': b['ei_micro'],
|
| 1025 |
+
'best_ei_macro': b['ei_macro'], 'best_ce': b['ce'], 'best_labels': b['labels'],
|
| 1026 |
+
'partitions_evaluated': b['partitions_evaluated']})
|
| 1027 |
+
pair = best_unit_coarse_graining(pair_count_copy_tpm(3, c['pair_copy_noise']), 6)
|
| 1028 |
+
indep = best_unit_coarse_graining(independent_flip_tpm(6, c['independent_keep']), 6)
|
| 1029 |
+
units = {'pair_copy': {'noise': c['pair_copy_noise'], **{k: pair[k] for k in (
|
| 1030 |
+
'ei_micro', 'ei_macro', 'ce', 'groups', 'macro_states', 'partitions_evaluated')}},
|
| 1031 |
+
'independent': {'keep': c['independent_keep'], **{k: indep[k] for k in (
|
| 1032 |
+
'ei_micro', 'ei_macro', 'ce', 'groups', 'macro_states', 'partitions_evaluated')}},
|
| 1033 |
+
'independent_ei_micro_closed_form': 6.0 * (1.0 - entropy_bits([c['independent_keep'],
|
| 1034 |
+
1.0 - c['independent_keep']]))}
|
| 1035 |
+
every = [*(ex[k] for k in ex), T_and, np.eye(8), np.full((5, 5), 0.2)]
|
| 1036 |
+
checks = {
|
| 1037 |
+
'identity_ei_equals_log2_n': all(_close(s['ei_identity'], s['log2_n'], 1e-9) and _close(s['identity_determinism'], 1.0, 1e-9)
|
| 1038 |
+
and _close(s['identity_degeneracy'], 0.0, 1e-9) for s in sizes),
|
| 1039 |
+
'permutation_ei_equals_log2_n': all(_close(s['ei_permutation'], s['log2_n'], 1e-9) for s in sizes),
|
| 1040 |
+
'uniform_ei_is_zero': all(_close(s['ei_uniform'], 0.0, 1e-9) and _close(s['uniform_determinism'], 0.0, 1e-9)
|
| 1041 |
+
and _close(s['uniform_degeneracy'], 0.0, 1e-9) for s in sizes),
|
| 1042 |
+
'ei_equals_size_times_effectiveness': all(
|
| 1043 |
+
_close(d['ei'], d['size_bits'] * d['effectiveness'], 1e-9)
|
| 1044 |
+
for d in (ei_decomposition(T) for T in every)),
|
| 1045 |
+
'hoel2017_M1_M2_M3_exact': all(_close(hoel['M_ei'][k], p[f'hoel2017_{k}_ei'], 1e-9) for k in ('M1', 'M2', 'M3')),
|
| 1046 |
+
'hoel2017_chain8_micro_closed_form': _close(hoel['chain8']['ei_micro'], chain_exact, 1e-9),
|
| 1047 |
+
'hoel2017_chain8_matches_printed': (_close(hoel['chain8']['ei_micro'], p['hoel2017_chain8_ei_micro'], 0.01)
|
| 1048 |
+
and _close(hoel['chain8']['effectiveness'], p['hoel2017_chain8_effectiveness'], 0.005)
|
| 1049 |
+
and _close(hoel['chain8']['ce'], p['hoel2017_chain8_ce'], 0.01)),
|
| 1050 |
+
'hoel2017_chain8_search_finds_1_bit_seven_plus_one': (
|
| 1051 |
+
_close(hoel['chain8']['ei_macro'], 1.0, 1e-9) and hoel['chain8']['best_labels'].tolist() == _SEVEN_PLUS_ONE),
|
| 1052 |
+
'hoel2017_chain8_varied_matches_printed': (
|
| 1053 |
+
_close(hoel['chain8_varied']['ei_micro'], p['hoel2017_chain8_varied_ei_micro'], 0.005)
|
| 1054 |
+
and _close(hoel['chain8_varied']['ei_macro'], 1.0, 1e-9)
|
| 1055 |
+
and hoel['chain8_varied']['best_labels'].tolist() == _SEVEN_PLUS_ONE),
|
| 1056 |
+
'hoel2017_channel4_matches_printed': (
|
| 1057 |
+
_close(hoel['channel4']['ei_micro'], p['hoel2017_channel4_ei_micro'], 0.005)
|
| 1058 |
+
and _close(hoel['channel4']['conditional_entropy'], p['hoel2017_channel4_conditional_entropy'], 0.005)
|
| 1059 |
+
and _close(hoel['channel4']['ei_macro'], p['hoel2017_channel4_ei_macro'], 1e-9)
|
| 1060 |
+
and hoel['channel4']['best_labels'].tolist() == [0, 0, 0, 1]),
|
| 1061 |
+
'and_gate_network_matches_printed': (
|
| 1062 |
+
_close(hoel['and_gates']['ei_micro'], p['hoel2013_and_ei_micro'], 0.005)
|
| 1063 |
+
and _close(hoel['and_gates']['determinism_micro'], 1.0, 1e-9)
|
| 1064 |
+
and _close(hoel['and_gates']['degeneracy_micro'], p['hoel2017_and_degeneracy'], 0.005)
|
| 1065 |
+
and _close(hoel['and_gates']['effectiveness_micro'], p['hoel2017_and_effectiveness'], 0.005)
|
| 1066 |
+
and _close(hoel['and_gates']['ei_macro'], 3.0, 1e-9)
|
| 1067 |
+
and _close(hoel['and_gates']['ce'], p['hoel2013_and_ce'], 0.005)),
|
| 1068 |
+
'weakly_symmetric_tpm_has_no_emergence': all(s['best_ce'] <= 1e-12 for s in symmetric),
|
| 1069 |
+
'unit_pair_copy_exact_ce_positive_for_pair_counts': bool(pair['ce'] > 0.0 and pair['groups'] == _PAIR_GROUPS),
|
| 1070 |
+
'unit_independent_exact_ce_negative': bool(indep['ce'] < 0.0 and _close(
|
| 1071 |
+
indep['ei_micro'], units['independent_ei_micro_closed_form'], 1e-9)),
|
| 1072 |
+
}
|
| 1073 |
+
return {'sizes': sizes, 'hoel': hoel, 'weakly_symmetric': symmetric, 'units_exact': units}, checks
|
| 1074 |
+
|
| 1075 |
+
|
| 1076 |
+
def _noisy_chain(eps: float) -> np.ndarray:
|
| 1077 |
+
T = np.zeros((8, 8))
|
| 1078 |
+
T[:7, :7] = (1.0 - eps) / 7.0
|
| 1079 |
+
T[:7, 7] = eps
|
| 1080 |
+
T[7, :7] = eps / 7.0
|
| 1081 |
+
T[7, 7] = 1.0 - eps
|
| 1082 |
+
return T
|
| 1083 |
+
|
| 1084 |
+
|
| 1085 |
+
def _sample_chain(T: np.ndarray, steps: int, rng: np.random.Generator) -> np.ndarray:
|
| 1086 |
+
cum = np.cumsum(T, axis=1)
|
| 1087 |
+
cum[:, -1] = 1.0
|
| 1088 |
+
u = rng.random(steps)
|
| 1089 |
+
s = np.empty(steps, dtype=np.int64)
|
| 1090 |
+
s[0] = int(rng.integers(T.shape[0]))
|
| 1091 |
+
for t in range(1, steps):
|
| 1092 |
+
s[t] = int(np.searchsorted(cum[s[t - 1]], u[t], side='right'))
|
| 1093 |
+
return s
|
| 1094 |
+
|
| 1095 |
+
|
| 1096 |
+
def _estimation(seed: int, c: Mapping[str, Any]) -> dict[str, Any]:
|
| 1097 |
+
"""Interventional samples of the Hoel (2017) 8-state chain: uniform current states, successors from the TPM."""
|
| 1098 |
+
T = hoel2017_examples()['chain8']
|
| 1099 |
+
rng = np.random.default_rng(seed + _EST_OFFSET)
|
| 1100 |
+
N = c['estimation_samples']
|
| 1101 |
+
cur = rng.integers(0, 8, N)
|
| 1102 |
+
cum = np.cumsum(T, axis=1)
|
| 1103 |
+
cum[:, -1] = 1.0
|
| 1104 |
+
nxt = (rng.random(N)[:, None] >= cum[cur]).sum(axis=1) # inverse CDF (searchsorted side='right')
|
| 1105 |
+
est = _smoothed(transition_counts(cur, 8, next_states=nxt).astype(np.float64), c['alpha'])
|
| 1106 |
+
labels = np.array(_SEVEN_PLUS_ONE)
|
| 1107 |
+
exact = causal_emergence(T, labels)
|
| 1108 |
+
fit = causal_emergence(est, labels)
|
| 1109 |
+
return {'seed': seed, 'samples': N, 'ei_micro_exact': exact['micro']['ei'], 'ei_micro_estimated': fit['micro']['ei'],
|
| 1110 |
+
'ce_exact': exact['ce'], 'ce_estimated': fit['ce'],
|
| 1111 |
+
'abs_error_ei_micro': abs(fit['micro']['ei'] - exact['micro']['ei']),
|
| 1112 |
+
'abs_error_ce': abs(fit['ce'] - exact['ce'])}
|
| 1113 |
+
|
| 1114 |
+
|
| 1115 |
+
def _chain_record(out: Mapping[str, Any]) -> dict[str, Any]:
|
| 1116 |
+
return {'ei_micro': out['ei_micro'], 'ei_macro': out['ei_macro'], 'ce': out['ce'], 'best_labels': out['labels'],
|
| 1117 |
+
'null_mean': out['null_mean'], 'null_sd': out['null_sd'], 'z': out['z'], 'p': out['p'],
|
| 1118 |
+
'block': out['block']}
|
| 1119 |
+
|
| 1120 |
+
|
| 1121 |
+
def _null_runs(seed: int, c: Mapping[str, Any], chunks: Sequence[_Candidates]) -> dict[str, Any]:
|
| 1122 |
+
"""Successor block-permutation null on 8-state sequences: i.i.d. states (calibration), the noisy ergodic
|
| 1123 |
+
version of the Hoel (2017) chain (exact CE > 0) and a weakly symmetric noisy permutation of the same length
|
| 1124 |
+
(exact CE <= 0 for every partition)."""
|
| 1125 |
+
iid = []
|
| 1126 |
+
for r in range(c['null_replicates']):
|
| 1127 |
+
rng = np.random.default_rng([seed + _IID_OFFSET, r])
|
| 1128 |
+
out = _successor_block_null(rng.integers(0, 8, c['null_steps']), 8, chunks, c['alpha'], c['null_draws'],
|
| 1129 |
+
None, (seed * 1009 + r) % (2**31 - 1))
|
| 1130 |
+
iid.append({'replicate': r, 'ce': out['ce'], 'null_mean': out['null_mean'], 'null_sd': out['null_sd'],
|
| 1131 |
+
'z': out['z'], 'p': out['p']})
|
| 1132 |
+
eps = c['emergence_noise']
|
| 1133 |
+
T = _noisy_chain(eps)
|
| 1134 |
+
states = _sample_chain(T, c['null_steps'], np.random.default_rng(seed + _CHAIN_OFFSET))
|
| 1135 |
+
out = _successor_block_null(states, 8, chunks, c['alpha'], c['null_draws'], None, seed)
|
| 1136 |
+
exact = causal_emergence(T, np.array(_SEVEN_PLUS_ONE))
|
| 1137 |
+
emerg = {'noise': eps, 'steps': c['null_steps'], 'ce_exact_seven_plus_one': exact['ce'],
|
| 1138 |
+
'ei_micro_exact': exact['micro']['ei'], 'ei_macro_exact': exact['macro']['ei'], **_chain_record(out)}
|
| 1139 |
+
Tp = noisy_permutation_tpm(8, c['permutation_noise'], seed=seed)
|
| 1140 |
+
sp = _sample_chain(Tp, c['null_steps'], np.random.default_rng([seed + _PERM8_OFFSET, 1]))
|
| 1141 |
+
outp = _successor_block_null(sp, 8, chunks, c['alpha'], c['null_draws'], None, seed)
|
| 1142 |
+
exact_p = best_state_partition(Tp)
|
| 1143 |
+
control = {'noise': c['permutation_noise'], 'steps': c['null_steps'], 'ei_micro_exact': exact_p['ei_micro'],
|
| 1144 |
+
'best_ce_exact': exact_p['ce'], **_chain_record(outp)}
|
| 1145 |
+
return {'seed': seed, 'iid': iid, 'emergence': emerg, 'permutation_control': control}
|
| 1146 |
+
|
| 1147 |
+
|
| 1148 |
+
def _unit_runs(seed: int, c: Mapping[str, Any], chunks: Sequence[_Candidates], groups: np.ndarray) -> dict[str, Any]:
|
| 1149 |
+
"""Six binary units sampled from the pair-count copy ring (exact CE > 0) and from independent slow flips
|
| 1150 |
+
(exact CE < 0), each scored with the observer's count-per-group search against both nulls."""
|
| 1151 |
+
weights = np.left_shift(1, np.arange(6, dtype=np.int64))
|
| 1152 |
+
out: dict[str, Any] = {'seed': seed, 'pair_copy': [], 'independent': []}
|
| 1153 |
+
for r in range(c['unit_replicates']):
|
| 1154 |
+
for name, offset in (('pair_copy', _PAIR_OFFSET), ('independent', _SLOW_OFFSET)):
|
| 1155 |
+
rng = np.random.default_rng([seed + offset, r])
|
| 1156 |
+
if name == 'pair_copy':
|
| 1157 |
+
bits = _sample_pair_count_copy(3, c['pair_copy_noise'], c['unit_steps'], rng)
|
| 1158 |
+
else:
|
| 1159 |
+
bits = _sample_independent_flips(6, c['independent_keep'], c['unit_steps'], rng)
|
| 1160 |
+
seq = bits.astype(np.int64) @ weights
|
| 1161 |
+
res = _ce_and_nulls(seq, 6, chunks, c['alpha'], c['unit_draws'], None,
|
| 1162 |
+
np.random.default_rng([seed + _UNIT_NULL_OFFSET, r, 0]),
|
| 1163 |
+
np.random.default_rng([seed + _UNIT_NULL_OFFSET, r, 1]))
|
| 1164 |
+
part = _groups(groups[res['best_index']], np.arange(6))
|
| 1165 |
+
st, si = res['successor'], res['independent']
|
| 1166 |
+
out[name].append({'replicate': r, 'visited_states': int(np.unique(seq[:-1]).size),
|
| 1167 |
+
'ei_micro': res['ei_micro'], 'ei_macro': res['ei_macro'], 'ce': res['ce'],
|
| 1168 |
+
'best_partition': part, 'pairs_recovered': part == _PAIR_GROUPS,
|
| 1169 |
+
'successor_excess': st['excess'], 'successor_z': st['z'], 'successor_p': st['p'],
|
| 1170 |
+
'independent_excess': si['excess'], 'independent_z': si['z'], 'independent_p': si['p']})
|
| 1171 |
+
return out
|
| 1172 |
+
|
| 1173 |
+
|
| 1174 |
+
def _neuroweave_activity(mechanisms: Sequence[str], seed: int, c: Mapping[str, Any]) -> np.ndarray:
|
| 1175 |
+
from ..neuroweave.engine import NeuroWeaveEngine
|
| 1176 |
+
from ..neuroweave.experiments import make_spec
|
| 1177 |
+
from ..neuroweave.tasks import make_stream
|
| 1178 |
+
steps = c['nw_steps']
|
| 1179 |
+
engine = NeuroWeaveEngine(make_spec(mechanisms, seed=seed, neurons=c['neurons'], topology=c['topology'],
|
| 1180 |
+
steps=steps))
|
| 1181 |
+
stream = make_stream(seed, steps)
|
| 1182 |
+
outs = [np.array(engine.step(stream.inputs[i], stream.sensory[i], reward=0.0, learn=False)['output'],
|
| 1183 |
+
dtype=np.float64) for i in range(steps)]
|
| 1184 |
+
return np.stack(outs)[c['nw_burn_in']:]
|
| 1185 |
+
|
| 1186 |
+
|
| 1187 |
+
_NW_KEYS = ('unit_sample', 'transitions', 'transitions_per_micro_state', 'visited_states', 'ei_micro',
|
| 1188 |
+
'determinism_micro', 'degeneracy_micro',
|
| 1189 |
+
'ei_macro', 'macro_partition', 'macro_states', 'ce', 'null_ready', 'null_ce_mean', 'null_ce_sd',
|
| 1190 |
+
'ce_excess', 'ce_z', 'ce_p', 'indep_ce_mean', 'indep_ce_sd', 'ce_excess_indep', 'ce_z_indep',
|
| 1191 |
+
'ce_p_indep')
|
| 1192 |
+
|
| 1193 |
+
|
| 1194 |
+
def _neuroweave_report(name: str, mechanisms: Sequence[str], seed: int, c: Mapping[str, Any]) -> dict[str, Any]:
|
| 1195 |
+
X = _neuroweave_activity(mechanisms, seed, c)
|
| 1196 |
+
obs = CausalEmergenceObserver(X.shape[1], seed=seed, history=min(8192, max(16, X.shape[0])), units=c['units'],
|
| 1197 |
+
alpha=c['alpha'], null_draws=c['nw_null_draws'],
|
| 1198 |
+
min_transitions=min(32, max(8, X.shape[0] - 2)))
|
| 1199 |
+
for row in X:
|
| 1200 |
+
obs.observe(row)
|
| 1201 |
+
s = obs.summary()
|
| 1202 |
+
return {'mechanism_set': name, 'seed': seed, 'neurons': int(X.shape[1]), **{k: s[k] for k in _NW_KEYS}}
|
| 1203 |
+
|
| 1204 |
+
|
| 1205 |
+
def _finite_tree(obj: Any) -> bool:
|
| 1206 |
+
if isinstance(obj, Mapping):
|
| 1207 |
+
return all(_finite_tree(v) for v in obj.values())
|
| 1208 |
+
if isinstance(obj, (list, tuple)):
|
| 1209 |
+
return all(_finite_tree(v) for v in obj)
|
| 1210 |
+
if isinstance(obj, np.ndarray):
|
| 1211 |
+
return bool(obj.dtype.kind not in 'fc' or np.all(np.isfinite(obj)))
|
| 1212 |
+
if isinstance(obj, (float, np.floating)):
|
| 1213 |
+
return math.isfinite(float(obj))
|
| 1214 |
+
return True
|
| 1215 |
+
|
| 1216 |
+
|
| 1217 |
+
def _mean_of(values: Sequence[Any]) -> float | None:
|
| 1218 |
+
v = [float(x) for x in values if x is not None]
|
| 1219 |
+
return float(np.mean(v)) if v else None
|
| 1220 |
+
|
| 1221 |
+
|
| 1222 |
+
def _rate(values: Sequence[Any], threshold: float = 0.05) -> float | None:
|
| 1223 |
+
v = [float(x) for x in values if x is not None]
|
| 1224 |
+
return float(np.mean([x <= threshold for x in v])) if v else None
|
| 1225 |
+
|
| 1226 |
+
|
| 1227 |
+
def run_experiment(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]:
|
| 1228 |
+
"""Known-answer validation of EI, its decomposition, coarse-graining search, TPM estimation and both nulls,
|
| 1229 |
+
then a descriptive EI/CE report on NEUROWEAVE activity under each mechanism set.
|
| 1230 |
+
|
| 1231 |
+
Exact checks (no sampling): identity and permutation TPMs give ``EI = log2 n`` (determinism 1, degeneracy 0),
|
| 1232 |
+
uniform TPMs ``EI = 0``, and ``EI = log2(n) * effectiveness``; the printed values of Hoel (2017) (M1/M2/M3,
|
| 1233 |
+
the 8-state chain with its closed form ``3 - (7/8) log2 7`` and the exhaustive search over its 4138 proper
|
| 1234 |
+
partitions finding the 1-bit seven-plus-one macro, the unequal-row variant, the 4-state channel) and of the
|
| 1235 |
+
six-AND-gate ring (Hoel et al. 2013, Fig. 4); weakly symmetric noisy permutations have no partition with
|
| 1236 |
+
``CE > 0``; the pair-count copy ring has exact ``CE > 0`` for the count-per-pair grouping and independent
|
| 1237 |
+
slow units have exact ``CE < 0``.
|
| 1238 |
+
|
| 1239 |
+
Sampled checks (every seed): Laplace-smoothed TPMs from interventional samples recover micro EI and CE within
|
| 1240 |
+
``estimation_tolerance``; the successor null is calibrated on i.i.d. states (at most 25 % of replicates with
|
| 1241 |
+
``p <= 0.05``, ``|mean z| < 1``); on 8-state sequences of the noisy chain the estimated CE is positive and
|
| 1242 |
+
above the successor null (``z > 3``, ``p <= 0.05``), while a weakly symmetric noisy permutation of the same
|
| 1243 |
+
length gives a negative CE that is not above it; on six binary units the pair-count copy ring is above the
|
| 1244 |
+
independent-units null (``z > 3``, ``p <= 0.05``) with the pair grouping recovered, and the independent-units
|
| 1245 |
+
null is calibrated on independent slow units (at most half of the replicates at ``p <= 0.05``,
|
| 1246 |
+
``|mean z| < 2``). How often the successor null flags those independent units (exact CE < 0) is reported,
|
| 1247 |
+
not checked. The NEUROWEAVE part is descriptive (only finiteness is checked): for each mechanism set and seed the
|
| 1248 |
+
frozen engine runs on the task stream and a :class:`CausalEmergenceObserver` over ``units`` (default 4) output
|
| 1249 |
+
units reports micro/macro EI, CE and both nulls.
|
| 1250 |
+
``kind='validation'``, ``verdict`` in ``('pass', 'fail')``."""
|
| 1251 |
+
from . import harness
|
| 1252 |
+
if type(quick) is not bool:
|
| 1253 |
+
raise ValueError('quick must be a boolean')
|
| 1254 |
+
seeds = _check_seeds(seeds)
|
| 1255 |
+
cfg = {k: (dict(v) if isinstance(v, Mapping) else v) for k, v in _DEFAULTS.items()}
|
| 1256 |
+
if quick:
|
| 1257 |
+
cfg.update(_QUICK)
|
| 1258 |
+
unknown = sorted(set(overrides) - set(cfg))
|
| 1259 |
+
if unknown:
|
| 1260 |
+
raise ValueError(f'unknown run_experiment overrides: {unknown}')
|
| 1261 |
+
cfg.update(overrides)
|
| 1262 |
+
c = _validate_config(cfg)
|
| 1263 |
+
t0 = time.perf_counter()
|
| 1264 |
+
exact, checks = _exact_checks(c)
|
| 1265 |
+
estimation = [_estimation(s, c) for s in seeds]
|
| 1266 |
+
cand = state_partition_candidates(8)
|
| 1267 |
+
chunks8 = _candidate_chunks(cand['labels'], 8, cand['m'])
|
| 1268 |
+
nulls = [_null_runs(s, c, chunks8) for s in seeds]
|
| 1269 |
+
unit_cand = unit_sum_candidates(6)
|
| 1270 |
+
unit_chunks = _candidate_chunks(unit_cand['labels'], 64, unit_cand['m'])
|
| 1271 |
+
units = [_unit_runs(s, c, unit_chunks, unit_cand['groups']) for s in seeds]
|
| 1272 |
+
t_val = time.perf_counter() - t0
|
| 1273 |
+
t1 = time.perf_counter()
|
| 1274 |
+
nw: dict[str, Any] = {}
|
| 1275 |
+
for name, mechs in c['mechanism_sets'].items():
|
| 1276 |
+
runs = [_neuroweave_report(name, mechs, s, c) for s in seeds]
|
| 1277 |
+
nw[name] = {'mechanisms': list(mechs), 'per_seed': runs,
|
| 1278 |
+
'mean': {k: _mean_of([r[k] for r in runs]) for k in (
|
| 1279 |
+
'ei_micro', 'ei_macro', 'ce', 'ce_excess', 'ce_z', 'ce_excess_indep', 'ce_z_indep',
|
| 1280 |
+
'visited_states')}}
|
| 1281 |
+
t_nw = time.perf_counter() - t1
|
| 1282 |
+
iid = [r for n in nulls for r in n['iid']]
|
| 1283 |
+
z_iid = [r['z'] for r in iid if r['z'] is not None]
|
| 1284 |
+
fpr = float(np.mean([r['p'] <= 0.05 for r in iid]))
|
| 1285 |
+
pair_rows = [r for u in units for r in u['pair_copy']]
|
| 1286 |
+
ind_rows = [r for u in units for r in u['independent']]
|
| 1287 |
+
ind_rate = _rate([r['independent_p'] for r in ind_rows])
|
| 1288 |
+
ind_mean_z = _mean_of([r['independent_z'] for r in ind_rows])
|
| 1289 |
+
unit_summary = {
|
| 1290 |
+
'pair_copy_replicates': len(pair_rows),
|
| 1291 |
+
'pair_copy_pairs_recovered_fraction': float(np.mean([r['pairs_recovered'] for r in pair_rows])),
|
| 1292 |
+
'pair_copy_min_independent_z': min((r['independent_z'] for r in pair_rows if r['independent_z'] is not None),
|
| 1293 |
+
default=None),
|
| 1294 |
+
'pair_copy_mean_ce': _mean_of([r['ce'] for r in pair_rows]),
|
| 1295 |
+
'independent_replicates': len(ind_rows),
|
| 1296 |
+
'independent_units_null_flag_rate_p_le_0.05': ind_rate,
|
| 1297 |
+
'independent_units_null_mean_z': ind_mean_z,
|
| 1298 |
+
'independent_successor_null_flag_rate_p_le_0.05': _rate([r['successor_p'] for r in ind_rows]),
|
| 1299 |
+
'independent_successor_null_mean_z': _mean_of([r['successor_z'] for r in ind_rows]),
|
| 1300 |
+
'independent_mean_ce': _mean_of([r['ce'] for r in ind_rows]),
|
| 1301 |
+
'note': ('independent slow units have exact CE < 0, yet the successor null flags them when micro states '
|
| 1302 |
+
'have few transitions each; the independent-units null does not'),
|
| 1303 |
+
}
|
| 1304 |
+
tol = c['estimation_tolerance']
|
| 1305 |
+
checks.update({
|
| 1306 |
+
'estimated_tpm_recovers_ei_and_ce': all(e['abs_error_ei_micro'] <= tol and e['abs_error_ce'] <= tol
|
| 1307 |
+
for e in estimation),
|
| 1308 |
+
'iid_null_false_positive_rate_at_most_0.25': bool(fpr <= 0.25),
|
| 1309 |
+
'iid_null_mean_z_within_1': bool(z_iid and abs(float(np.mean(z_iid))) < 1.0),
|
| 1310 |
+
'noisy_chain_ce_positive_and_above_successor_null': all(
|
| 1311 |
+
n['emergence']['ce'] > 0.0 and n['emergence']['z'] is not None and n['emergence']['z'] > 3.0
|
| 1312 |
+
and n['emergence']['p'] <= 0.05 for n in nulls),
|
| 1313 |
+
'permutation_control_ce_negative_and_not_above_successor_null': all(
|
| 1314 |
+
n['permutation_control']['ce'] < 0.0 and n['permutation_control']['p'] > 0.05 for n in nulls),
|
| 1315 |
+
'unit_pair_copy_above_independent_units_null_with_pairs_recovered': all(
|
| 1316 |
+
r['independent_z'] is not None and r['independent_z'] > 3.0 and r['independent_p'] <= 0.05
|
| 1317 |
+
and r['pairs_recovered'] for r in pair_rows),
|
| 1318 |
+
'unit_independent_units_null_calibrated': bool(ind_rate is not None and ind_rate <= 0.5
|
| 1319 |
+
and ind_mean_z is not None and abs(ind_mean_z) < 2.0),
|
| 1320 |
+
'neuroweave_values_finite': _finite_tree(nw),
|
| 1321 |
+
})
|
| 1322 |
+
receipt = harness.base_receipt(MODULE_ID, 'validation', {**c, 'quick': quick, 'seeds': list(seeds)})
|
| 1323 |
+
receipt['validations'] = {
|
| 1324 |
+
**exact, 'estimation': estimation,
|
| 1325 |
+
'null_iid': {'replicates': len(iid), 'false_positive_rate_p_le_0.05': fpr,
|
| 1326 |
+
'mean_z': float(np.mean(z_iid)) if z_iid else None, 'per_replicate': iid},
|
| 1327 |
+
'null_emergence': [n['emergence'] for n in nulls],
|
| 1328 |
+
'null_permutation_control': [n['permutation_control'] for n in nulls],
|
| 1329 |
+
'candidate_partitions': int(cand['labels'].shape[0]),
|
| 1330 |
+
'units': {'per_seed': units, 'summary': unit_summary,
|
| 1331 |
+
'candidate_coarse_grainings': int(unit_cand['labels'].shape[0])}}
|
| 1332 |
+
receipt['neuroweave'] = {'per_mechanism_set': nw, 'topology': c['topology'], 'units': c['units'],
|
| 1333 |
+
'note': ('descriptive only: values are reported, no verdict is drawn from them; read CE '
|
| 1334 |
+
'against the independent-units null (ce_excess_indep, ce_z_indep)')}
|
| 1335 |
+
receipt['checks'] = checks
|
| 1336 |
+
receipt['verdict'] = 'pass' if all(checks.values()) else 'fail'
|
| 1337 |
+
receipt['verdict_basis'] = 'all_known_answer_checks' if receipt['verdict'] == 'pass' else 'failed_checks: ' + ', '.join(
|
| 1338 |
+
k for k, v in checks.items() if not v)
|
| 1339 |
+
n_null_runs = len(seeds) * (c['null_replicates'] + 2)
|
| 1340 |
+
n_unit_runs = len(seeds) * c['unit_replicates'] * 2
|
| 1341 |
+
nw_cands = int(unit_sum_candidates(c['units'])['m'].size)
|
| 1342 |
+
receipt['estimated_cost'] = {
|
| 1343 |
+
'tpm_evaluations_null': int(n_null_runs * (c['null_draws'] + 1) * (cand['labels'].shape[0] + 1)),
|
| 1344 |
+
'tpm_evaluations_units': int(n_unit_runs * (2 * c['unit_draws'] + 1) * (unit_cand['labels'].shape[0] + 1)),
|
| 1345 |
+
'engine_steps': int(len(c['mechanism_sets']) * len(seeds) * c['nw_steps']),
|
| 1346 |
+
'tpm_evaluations_neuroweave': int(len(c['mechanism_sets']) * len(seeds) * (2 * c['nw_null_draws'] + 1)
|
| 1347 |
+
* (nw_cands + 1))}
|
| 1348 |
+
receipt['measured_wallclock_s'] = {'validation': t_val, 'neuroweave': t_nw, 'total': time.perf_counter() - t0}
|
| 1349 |
+
receipt['notes'] = (
|
| 1350 |
+
'EI and causal emergence follow the definitions of Hoel et al. (2013) and Hoel (2017): uniform '
|
| 1351 |
+
'(maximum-entropy) interventions, macro TPMs by uniform interventions on the micro states of each macro '
|
| 1352 |
+
'state. The six-AND-gate wiring is reconstructed from the papers\' text (pairs reading the next pair); its '
|
| 1353 |
+
'exact values match the printed ones (2.43 bits, effectiveness 0.4/0.41, degeneracy 0.6/0.59, macro 3 bits, '
|
| 1354 |
+
'CE 0.57 bits) at their printed precision. The 8-state chain has the closed form 3 - (7/8) log2 7 = 0.5436 '
|
| 1355 |
+
'bits (CE 0.4564), printed as 0.55 and 0.45 bits, so it is checked to 0.01. The pair-count copy ring and the '
|
| 1356 |
+
'independent slow units are constructed known-answer systems, not examples from the papers. Estimated EI '
|
| 1357 |
+
'from short discretised windows is dominated by Laplace smoothing and finite-sample effects (see '
|
| 1358 |
+
'transitions_per_micro_state): with few transitions per micro state the successor null flags any temporal '
|
| 1359 |
+
'dependence, so NEUROWEAVE CE is only meaningful against the independent-units null; the observer binarises '
|
| 1360 |
+
'at a running median and only searches count-per-group coarse-grainings of 2 to 6 units. Nothing here is '
|
| 1361 |
+
'evidence of consciousness, agency or biological causation.')
|
| 1362 |
+
return harness.seal(receipt)
|
| 1363 |
+
|
| 1364 |
+
|
| 1365 |
+
EXPERIMENTS: dict[str, Callable[..., dict[str, Any]]] = {MODULE_ID: run_experiment}
|
synapse/frontier/cli_commands.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Handlers for ``python -m synapse.cli frontier ...`` and global ``--frontier*`` CLI flags (opt-in only).
|
| 2 |
+
|
| 3 |
+
Every subcommand handler returns a JSON-serialisable dict with an ``ok`` flag; nothing here changes any
|
| 4 |
+
Sonapse or NEUROWEAVE default.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
from dataclasses import replace
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Any
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
|
| 15 |
+
from .harness import _jsonable
|
| 16 |
+
from .runtime import (
|
| 17 |
+
FrontierObserverHub,
|
| 18 |
+
experiment_catalog,
|
| 19 |
+
run_all_frontier_experiments,
|
| 20 |
+
run_frontier_experiment,
|
| 21 |
+
run_frontier_laboratory,
|
| 22 |
+
)
|
| 23 |
+
from .spec import (
|
| 24 |
+
EVIDENCE_TIER,
|
| 25 |
+
GRAFT_OPTIMIZERS,
|
| 26 |
+
MODULE_IDS,
|
| 27 |
+
OBSERVER_MODULE_IDS,
|
| 28 |
+
FrontierSpecV1,
|
| 29 |
+
module_catalog,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
__all__ = [
|
| 33 |
+
'parse_observer_modules',
|
| 34 |
+
'parse_seeds',
|
| 35 |
+
'cli_frontier_spec',
|
| 36 |
+
'register_frontier_cli',
|
| 37 |
+
'run_frontier_command',
|
| 38 |
+
]
|
| 39 |
+
|
| 40 |
+
MAX_CLI_JSON_BYTES = 1_000_000
|
| 41 |
+
MAX_CLI_OBSERVE_STEPS = 4096
|
| 42 |
+
MAX_CLI_OBSERVE_UNITS = 4096
|
| 43 |
+
_SYNTH_STREAM_OFFSET = 61_543
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _read_json_file(path: Path, limit: int = MAX_CLI_JSON_BYTES) -> Any:
|
| 47 |
+
p = Path(path)
|
| 48 |
+
size = p.stat().st_size
|
| 49 |
+
if size > limit:
|
| 50 |
+
raise ValueError(f'{p} exceeds {limit} bytes (checked before reading)')
|
| 51 |
+
|
| 52 |
+
def _reject(token: str) -> Any:
|
| 53 |
+
raise ValueError(f'non-standard JSON constant {token}')
|
| 54 |
+
|
| 55 |
+
return json.loads(p.read_text(encoding='utf-8'), parse_constant=_reject)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def parse_observer_modules(text: str | None) -> tuple[str, ...]:
|
| 59 |
+
"""``'all'`` -> every observer module, ``'none'``/``''`` -> ``()``, else a comma list of observer ids."""
|
| 60 |
+
if text is None:
|
| 61 |
+
return ()
|
| 62 |
+
t = text.strip()
|
| 63 |
+
if t.lower() == 'all':
|
| 64 |
+
return OBSERVER_MODULE_IDS
|
| 65 |
+
if t.lower() in ('', 'none'):
|
| 66 |
+
return ()
|
| 67 |
+
items = [m.strip() for m in t.split(',') if m.strip()]
|
| 68 |
+
unknown = [m for m in items if m not in MODULE_IDS]
|
| 69 |
+
if unknown:
|
| 70 |
+
raise ValueError(f'unknown frontier modules: {unknown}')
|
| 71 |
+
non_obs = [m for m in items if m not in OBSERVER_MODULE_IDS]
|
| 72 |
+
if non_obs:
|
| 73 |
+
raise ValueError(f'modules without a live observer: {non_obs} (observers: {OBSERVER_MODULE_IDS})')
|
| 74 |
+
return tuple(m for m in OBSERVER_MODULE_IDS if m in set(items))
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def parse_seeds(text: str | None, default: tuple[int, ...] = (0, 1, 2), max_count: int = 16) -> tuple[int, ...]:
|
| 78 |
+
if text is None or not str(text).strip():
|
| 79 |
+
return default
|
| 80 |
+
parts = [p.strip() for p in str(text).split(',') if p.strip()]
|
| 81 |
+
if not 1 <= len(parts) <= max_count:
|
| 82 |
+
raise ValueError(f'--seeds must list between 1 and {max_count} integers')
|
| 83 |
+
seeds: list[int] = []
|
| 84 |
+
for p in parts:
|
| 85 |
+
try:
|
| 86 |
+
val = int(p)
|
| 87 |
+
except ValueError as exc:
|
| 88 |
+
raise ValueError(f'invalid seed {p!r}') from exc
|
| 89 |
+
if not 0 <= val <= 2**31 - 1:
|
| 90 |
+
raise ValueError('seeds must be non-negative 31-bit ints')
|
| 91 |
+
seeds.append(val)
|
| 92 |
+
if len(set(seeds)) != len(seeds):
|
| 93 |
+
raise ValueError('seeds must be unique')
|
| 94 |
+
return tuple(seeds)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def cli_frontier_spec(enabled: bool | None, config_path: Path | None, seed: int, *,
|
| 98 |
+
modules: str | None = None, graft_optimizer: str | None = None) -> FrontierSpecV1 | None:
|
| 99 |
+
"""Build a :class:`FrontierSpecV1` from global CLI flags, or ``None`` when not requested."""
|
| 100 |
+
if config_path is not None:
|
| 101 |
+
if enabled is False:
|
| 102 |
+
raise ValueError('--no-frontier conflicts with --frontier-config')
|
| 103 |
+
data = _read_json_file(Path(config_path))
|
| 104 |
+
spec = FrontierSpecV1.from_dict(data)
|
| 105 |
+
if modules is not None:
|
| 106 |
+
spec = spec.with_modules(parse_observer_modules(modules))
|
| 107 |
+
if graft_optimizer is not None:
|
| 108 |
+
spec = replace(spec, graft_optimizer=graft_optimizer)
|
| 109 |
+
return spec
|
| 110 |
+
has_opt_in = bool(enabled) or (modules is not None) or (graft_optimizer not in (None, 'adam'))
|
| 111 |
+
if not has_opt_in:
|
| 112 |
+
return None
|
| 113 |
+
if enabled is False:
|
| 114 |
+
raise ValueError('--no-frontier conflicts with frontier module or graft-optimizer options')
|
| 115 |
+
obs_mods = OBSERVER_MODULE_IDS if modules is None and enabled else parse_observer_modules(modules)
|
| 116 |
+
return FrontierSpecV1(
|
| 117 |
+
enabled=True,
|
| 118 |
+
seed=int(seed),
|
| 119 |
+
modules=obs_mods,
|
| 120 |
+
graft_optimizer='adam' if graft_optimizer is None else graft_optimizer,
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def register_frontier_cli(parser: Any, subparsers: Any = None) -> None:
|
| 125 |
+
"""Add global ``--frontier*`` options to ``parser`` and optionally a ``frontier`` subcommand."""
|
| 126 |
+
parser.add_argument('--frontier', dest='frontier_enabled', action='store_true', default=None,
|
| 127 |
+
help='Enable read-only live frontier observers on the brain')
|
| 128 |
+
parser.add_argument('--no-frontier', dest='frontier_enabled', action='store_false',
|
| 129 |
+
help='Disable live frontier observers')
|
| 130 |
+
parser.add_argument('--frontier-config', type=Path, default=None,
|
| 131 |
+
help='Path to a FrontierSpecV1 JSON file')
|
| 132 |
+
parser.add_argument('--frontier-modules', type=str, default=None,
|
| 133 |
+
help='Comma-separated observer modules (or "all" / "none")')
|
| 134 |
+
parser.add_argument('--frontier-graft-optimizer', choices=GRAFT_OPTIMIZERS, default=None,
|
| 135 |
+
help='Opt-in optimizer for the live neural-graft fit (adam or muon)')
|
| 136 |
+
if subparsers is not None:
|
| 137 |
+
fp = subparsers.add_parser('frontier', help='Frontier pack catalog, observers and experiments')
|
| 138 |
+
fp.add_argument('frontier_action', choices=('catalog', 'experiment', 'observe', 'laboratory'),
|
| 139 |
+
nargs='?', default='catalog')
|
| 140 |
+
fp.add_argument('--id', dest='frontier_id', type=str, default='all',
|
| 141 |
+
help='Experiment id to run (or "all")')
|
| 142 |
+
fp.add_argument('--quick', dest='frontier_quick', action='store_true', default=False,
|
| 143 |
+
help='Run experiment(s) in fast quick mode')
|
| 144 |
+
fp.add_argument('--seeds', dest='frontier_seeds', type=str, default='0,1,2',
|
| 145 |
+
help='Comma-separated integer seeds')
|
| 146 |
+
fp.add_argument('--modules', dest='frontier_sub_modules', type=str, default='all',
|
| 147 |
+
help='Observer modules for observe/laboratory')
|
| 148 |
+
fp.add_argument('--steps', dest='frontier_steps', type=int, default=32,
|
| 149 |
+
help='Synthetic observation steps for "frontier observe"')
|
| 150 |
+
fp.add_argument('--units', dest='frontier_units', type=int, default=32,
|
| 151 |
+
help='Synthetic unit count for "frontier observe"')
|
| 152 |
+
fp.add_argument('--out', dest='frontier_out', type=Path, default=None,
|
| 153 |
+
help='Optional path to write the JSON receipt')
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def _write_optional(out_path: Path | None, payload: Any) -> dict[str, Any] | None:
|
| 157 |
+
if out_path is None:
|
| 158 |
+
return None
|
| 159 |
+
p = Path(out_path)
|
| 160 |
+
p.parent.mkdir(parents=True, exist_ok=True)
|
| 161 |
+
text = json.dumps(_jsonable(payload), indent=2, sort_keys=True)
|
| 162 |
+
p.write_text(text, encoding='utf-8')
|
| 163 |
+
return {'path': str(p), 'bytes': len(text.encode('utf-8'))}
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def run_frontier_command(args: Any) -> dict[str, Any]:
|
| 167 |
+
"""Execute ``python -m synapse.cli frontier <action>`` and return a JSON-safe response."""
|
| 168 |
+
action = getattr(args, 'frontier_action', 'catalog')
|
| 169 |
+
seed = int(getattr(args, 'seed', 7))
|
| 170 |
+
out_path = getattr(args, 'frontier_out', None)
|
| 171 |
+
try:
|
| 172 |
+
if action == 'catalog':
|
| 173 |
+
res: dict[str, Any] = {
|
| 174 |
+
'ok': True,
|
| 175 |
+
'action': 'catalog',
|
| 176 |
+
'evidence_tier': EVIDENCE_TIER,
|
| 177 |
+
'modules': module_catalog(),
|
| 178 |
+
'observer_module_ids': list(OBSERVER_MODULE_IDS),
|
| 179 |
+
'experiments': experiment_catalog(include_unregistered=True),
|
| 180 |
+
}
|
| 181 |
+
elif action == 'experiment':
|
| 182 |
+
exp_id = str(getattr(args, 'frontier_id', 'all')).strip()
|
| 183 |
+
quick = bool(getattr(args, 'frontier_quick', False))
|
| 184 |
+
seeds = parse_seeds(getattr(args, 'frontier_seeds', '0,1,2'),
|
| 185 |
+
default=(0, 1) if quick else (0, 1, 2))
|
| 186 |
+
if exp_id.lower() == 'all':
|
| 187 |
+
receipts = run_all_frontier_experiments(
|
| 188 |
+
quick=quick, seeds=seeds, primary_only=True, include_unregistered=True)
|
| 189 |
+
res = {'ok': True, 'action': 'experiment', 'count': len(receipts), 'receipts': receipts}
|
| 190 |
+
else:
|
| 191 |
+
receipt = run_frontier_experiment(exp_id, quick=quick, seeds=seeds, include_unregistered=True)
|
| 192 |
+
res = {'ok': True, 'action': 'experiment', 'receipt': receipt}
|
| 193 |
+
elif action == 'observe':
|
| 194 |
+
steps = int(getattr(args, 'frontier_steps', 32))
|
| 195 |
+
units = int(getattr(args, 'frontier_units', 32))
|
| 196 |
+
if not 1 <= steps <= MAX_CLI_OBSERVE_STEPS:
|
| 197 |
+
raise ValueError(f'--steps must be in [1, {MAX_CLI_OBSERVE_STEPS}]')
|
| 198 |
+
if not 2 <= units <= MAX_CLI_OBSERVE_UNITS:
|
| 199 |
+
raise ValueError(f'--units must be in [2, {MAX_CLI_OBSERVE_UNITS}]')
|
| 200 |
+
mods = parse_observer_modules(getattr(args, 'frontier_sub_modules', 'all'))
|
| 201 |
+
spec = FrontierSpecV1(enabled=True, seed=seed, modules=mods,
|
| 202 |
+
history=max(16, min(256, steps * 2)),
|
| 203 |
+
fc_window=max(8, min(128, max(16, steps))))
|
| 204 |
+
hub = FrontierObserverHub(spec, n_units=units)
|
| 205 |
+
rng = np.random.default_rng(seed + _SYNTH_STREAM_OFFSET)
|
| 206 |
+
for _ in range(steps):
|
| 207 |
+
hub.observe(np.tanh(rng.standard_normal(units)))
|
| 208 |
+
res = {'ok': True, 'action': 'observe', 'summary': hub.summary()}
|
| 209 |
+
elif action == 'laboratory':
|
| 210 |
+
quick = bool(getattr(args, 'frontier_quick', True))
|
| 211 |
+
seeds = parse_seeds(getattr(args, 'frontier_seeds', '0,1'), default=(0, 1))
|
| 212 |
+
mods = parse_observer_modules(getattr(args, 'frontier_sub_modules', 'all'))
|
| 213 |
+
spec = FrontierSpecV1(enabled=True, seed=seed, modules=mods)
|
| 214 |
+
lab = run_frontier_laboratory(spec, experiments=True, quick=quick, seeds=seeds)
|
| 215 |
+
res = {'ok': True, 'action': 'laboratory', 'receipt': lab}
|
| 216 |
+
else:
|
| 217 |
+
raise ValueError(f'unknown frontier action: {action!r}')
|
| 218 |
+
written = _write_optional(out_path, res)
|
| 219 |
+
if written is not None:
|
| 220 |
+
res['written'] = written
|
| 221 |
+
return _jsonable(res)
|
| 222 |
+
except Exception as exc:
|
| 223 |
+
return {'ok': False, 'action': action, 'error': str(exc)}
|
synapse/frontier/connectomics.py
ADDED
|
@@ -0,0 +1,1205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Structural, functional and effective connectivity (frontier module ``connectomics``).
|
| 2 |
+
|
| 3 |
+
Inspired by the strictly separated structural / functional / effective connectomics of SONAPSE-CONNECTOME
|
| 4 |
+
(kai9987kai; ``sonapse_connectome/connectome/functional.py`` and ``effective.py``). This module re-implements
|
| 5 |
+
those ideas for NEUROWEAVE brains with known-answer validation. It is a synthetic computational abstraction: the
|
| 6 |
+
"structure" is a toy synapse table and the "function" is the activity of abstract units, not imaging data.
|
| 7 |
+
|
| 8 |
+
What is computed
|
| 9 |
+
----------------
|
| 10 |
+
* **Functional connectivity (FC).** Pearson and Spearman correlation matrices, and partial correlation from a
|
| 11 |
+
ridge-regularised precision matrix: ``Omega = (R + ridge * I)^-1`` on the correlation matrix ``R`` and
|
| 12 |
+
``P_ij = -Omega_ij / sqrt(Omega_ii Omega_jj)``. Zero-variance units get zero rows and a zero diagonal.
|
| 13 |
+
* **Dynamic FC (dFC).** Sliding-window Pearson FC, k-means clustering of the windowed upper triangles into FC
|
| 14 |
+
states, the number of states chosen by the average silhouette width, and dwell times (run lengths of the state
|
| 15 |
+
sequence). In the spirit of Allen et al. (2014); see the doc for what differs.
|
| 16 |
+
* **Effective connectivity (EC).** A ridge VAR(1) (lagged regression, Granger-style predictive influence, not an
|
| 17 |
+
interventional effect): ``x_{t+1} = A x_t + e``, ``A[target, source]``. The significance mask comes from a
|
| 18 |
+
per-target conditional block-permutation null (each target keeps its own past; the other sources are
|
| 19 |
+
block-permuted jointly in time), a two-sided normal p-value from the null mean and spread, and
|
| 20 |
+
Benjamini-Hochberg FDR control over the off-diagonal edges.
|
| 21 |
+
* **Structure-function coupling.** Spearman correlation between symmetric structural weights and FC over node
|
| 22 |
+
pairs (all pairs and structurally connected pairs), and the same for weighted communicability
|
| 23 |
+
``exp(D^-1/2 S D^-1/2)`` as an analytic predictor of FC.
|
| 24 |
+
* **FC modularity proxy.** Newman-Girvan modularity of the positive part of FC under a leading-eigenvector
|
| 25 |
+
partition (recursive bisection, no vertex-moving refinement), so it is a lower bound on the maximum modularity.
|
| 26 |
+
|
| 27 |
+
References (verified 2026-11-19; full list and notes in ``docs/frontier/modules/connectomics.md``)
|
| 28 |
+
---------------------------------------------------------------------------------------------------
|
| 29 |
+
* C. J. Honey, O. Sporns, L. Cammoun, X. Gigandet, J. P. Thiran, R. Meuli, P. Hagmann, "Predicting human
|
| 30 |
+
resting-state functional connectivity from structural connectivity", PNAS 106(6):2035-2040, February 2009,
|
| 31 |
+
https://doi.org/10.1073/pnas.0811168106
|
| 32 |
+
* E. A. Allen, E. Damaraju, S. M. Plis, E. B. Erhardt, T. Eichele, V. D. Calhoun, "Tracking whole-brain
|
| 33 |
+
connectivity dynamics in the resting state", Cerebral Cortex 24(3):663-676, March 2014,
|
| 34 |
+
https://doi.org/10.1093/cercor/bhs352
|
| 35 |
+
* E. Estrada, N. Hatano, "Communicability in complex networks", Phys. Rev. E 77:036111, March 2008,
|
| 36 |
+
https://doi.org/10.1103/PhysRevE.77.036111
|
| 37 |
+
* J. J. Crofts, D. J. Higham, "A weighted communicability measure applied to complex brain networks",
|
| 38 |
+
J. R. Soc. Interface 6(33):411-414, April 2009, https://doi.org/10.1098/rsif.2008.0484 (eq. 2.2)
|
| 39 |
+
* M. E. J. Newman, "Modularity and community structure in networks", PNAS 103(23):8577-8582, June 2006,
|
| 40 |
+
https://doi.org/10.1073/pnas.0601602103
|
| 41 |
+
* C. W. J. Granger, "Investigating causal relations by econometric models and cross-spectral methods",
|
| 42 |
+
Econometrica 37(3):424-438, August 1969, https://doi.org/10.2307/1912791
|
| 43 |
+
* Y. Benjamini, Y. Hochberg, "Controlling the false discovery rate: a practical and powerful approach to multiple
|
| 44 |
+
testing", J. R. Stat. Soc. B 57(1):289-300, 1995, https://doi.org/10.1111/j.2517-6161.1995.tb02031.x
|
| 45 |
+
* P. J. Rousseeuw, "Silhouettes: a graphical aid to the interpretation and validation of cluster analysis",
|
| 46 |
+
J. Comput. Appl. Math. 20:53-65, November 1987, https://doi.org/10.1016/0377-0427(87)90125-7
|
| 47 |
+
"""
|
| 48 |
+
from __future__ import annotations
|
| 49 |
+
|
| 50 |
+
import math
|
| 51 |
+
import time
|
| 52 |
+
from typing import Any, Callable, Mapping, Sequence
|
| 53 |
+
|
| 54 |
+
import numpy as np
|
| 55 |
+
|
| 56 |
+
__all__ = ['MODULE_ID', 'ConnectivityObserver', 'pearson_fc', 'spearman_fc', 'partial_correlation',
|
| 57 |
+
'partial_from_covariance', 'precision_to_partial', 'sliding_window_fc', 'kmeans', 'silhouette_score',
|
| 58 |
+
'dwell_statistics', 'dynamic_fc_states', 'var1_fit', 'block_permutation', 'var1_permutation_null',
|
| 59 |
+
'benjamini_hochberg', 'effective_connectivity', 'auroc', 'structural_matrix', 'weighted_communicability',
|
| 60 |
+
'structure_function_coupling', 'modularity', 'fc_communities', 'run_experiment', 'EXPERIMENTS']
|
| 61 |
+
|
| 62 |
+
MODULE_ID = 'connectomics'
|
| 63 |
+
OBSERVER_STATE_SCHEMA = 'ConnectivityObserverStateV1'
|
| 64 |
+
_VAR_OFFSET = 63_001
|
| 65 |
+
_CHAIN_OFFSET = 63_011
|
| 66 |
+
_SWITCH_OFFSET = 63_021
|
| 67 |
+
_KMEANS_OFFSET = 63_031
|
| 68 |
+
_PERM_OFFSET = 63_041
|
| 69 |
+
_OBS_UNITS_OFFSET = 63_051
|
| 70 |
+
_OBS_PERM_OFFSET = 63_061
|
| 71 |
+
_STATIONARY_OFFSET = 63_071
|
| 72 |
+
_TOP_EDGES = 5
|
| 73 |
+
_EPS = 1e-12
|
| 74 |
+
_SPEC_OBSERVER_PARAMS = frozenset({'sync_pairs', 'sae_features', 'sae_k', 'fc_window', 'max_observed_units',
|
| 75 |
+
'observe_every'})
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# ====================================================================== validation helpers
|
| 79 |
+
def _check_int(name: str, value: Any, low: int, high: int) -> int:
|
| 80 |
+
if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, np.integer)) or not low <= int(value) <= high:
|
| 81 |
+
raise ValueError(f'{name} must be an int in [{low}, {high}]')
|
| 82 |
+
return int(value)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _check_float(name: str, value: Any, low: float, high: float) -> float:
|
| 86 |
+
if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
|
| 87 |
+
raise ValueError(f'{name} must be a number in [{low}, {high}]')
|
| 88 |
+
v = float(value)
|
| 89 |
+
if not (math.isfinite(v) and low <= v <= high):
|
| 90 |
+
raise ValueError(f'{name} must be a finite number in [{low}, {high}]')
|
| 91 |
+
return v
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _check_seeds(seeds: Any) -> tuple[int, ...]:
|
| 95 |
+
try:
|
| 96 |
+
out = tuple(_check_int('seed', s, 0, 2**31 - 1) for s in seeds)
|
| 97 |
+
except TypeError as exc:
|
| 98 |
+
raise ValueError('seeds must be an iterable of ints') from exc
|
| 99 |
+
if not out or len(set(out)) != len(out):
|
| 100 |
+
raise ValueError('seeds must be non-empty and unique')
|
| 101 |
+
return out
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _series(name: str, value: Any, *, min_rows: int = 3, min_cols: int = 2) -> np.ndarray:
|
| 105 |
+
"""A private float64 copy of a finite ``(T, n)`` array with ``T >= min_rows`` and ``n >= min_cols``."""
|
| 106 |
+
try:
|
| 107 |
+
arr = np.array(value, dtype=np.float64)
|
| 108 |
+
except (TypeError, ValueError) as exc:
|
| 109 |
+
raise ValueError(f'{name} must be numeric') from exc
|
| 110 |
+
if arr.ndim != 2 or arr.shape[0] < min_rows or arr.shape[1] < min_cols:
|
| 111 |
+
raise ValueError(f'{name} must be a 2-D array with at least {min_rows} rows and {min_cols} columns')
|
| 112 |
+
if not np.all(np.isfinite(arr)):
|
| 113 |
+
raise ValueError(f'{name} must be finite')
|
| 114 |
+
return arr
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _square(name: str, value: Any, n: int | None = None) -> np.ndarray:
|
| 118 |
+
try:
|
| 119 |
+
arr = np.array(value, dtype=np.float64)
|
| 120 |
+
except (TypeError, ValueError) as exc:
|
| 121 |
+
raise ValueError(f'{name} must be numeric') from exc
|
| 122 |
+
if arr.ndim != 2 or arr.shape[0] != arr.shape[1] or arr.shape[0] < 1 or (n is not None and arr.shape[0] != n):
|
| 123 |
+
raise ValueError(f'{name} must be a square matrix' + ('' if n is None else f' of size {n}'))
|
| 124 |
+
if not np.all(np.isfinite(arr)):
|
| 125 |
+
raise ValueError(f'{name} must be finite')
|
| 126 |
+
return arr
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
# ====================================================================== functional connectivity
|
| 130 |
+
def _zscore_columns(X: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
| 131 |
+
"""Column z-scores (population sd) and the mask of non-constant columns (constant columns become 0)."""
|
| 132 |
+
# A power-of-two rescaling keeps centering and squaring in range even
|
| 133 |
+
# when different units are recorded at very different amplitudes.
|
| 134 |
+
_, exponents = np.frexp(np.max(np.abs(X), axis=0))
|
| 135 |
+
Z = np.ldexp(X, -exponents)
|
| 136 |
+
Z -= Z[0].copy()
|
| 137 |
+
Z -= Z.mean(axis=0)
|
| 138 |
+
sd = np.sqrt((Z * Z).mean(axis=0))
|
| 139 |
+
ok = sd > 0.0
|
| 140 |
+
out = np.zeros_like(Z)
|
| 141 |
+
out[:, ok] = Z[:, ok] / sd[ok]
|
| 142 |
+
return out, ok
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def _pearson(X: np.ndarray) -> np.ndarray:
|
| 146 |
+
Z, ok = _zscore_columns(X)
|
| 147 |
+
C = np.clip((Z.T @ Z) / X.shape[0], -1.0, 1.0)
|
| 148 |
+
np.fill_diagonal(C, ok.astype(np.float64))
|
| 149 |
+
return C
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def pearson_fc(X: Any) -> np.ndarray:
|
| 153 |
+
"""Pearson FC of a ``(T, n)`` series. Constant units get zero rows/columns and a zero diagonal entry."""
|
| 154 |
+
return _pearson(_series('X', X))
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def spearman_fc(X: Any) -> np.ndarray:
|
| 158 |
+
"""Spearman FC: Pearson correlation of per-unit ranks (average ranks for ties)."""
|
| 159 |
+
from scipy.stats import rankdata
|
| 160 |
+
return _pearson(rankdata(_series('X', X), axis=0))
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def precision_to_partial(precision: Any) -> np.ndarray:
|
| 164 |
+
"""Partial correlations ``-Omega_ij / sqrt(Omega_ii Omega_jj)`` (unit diagonal) from a precision matrix."""
|
| 165 |
+
Om = _square('precision', precision)
|
| 166 |
+
d = np.diag(Om)
|
| 167 |
+
if np.any(d <= 0.0):
|
| 168 |
+
raise ValueError('precision matrix must have a positive diagonal')
|
| 169 |
+
s = np.sqrt(d)
|
| 170 |
+
P = -Om / np.outer(s, s)
|
| 171 |
+
np.fill_diagonal(P, 1.0)
|
| 172 |
+
return np.clip(0.5 * (P + P.T), -1.0, 1.0)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def partial_from_covariance(cov: Any, *, ridge: float = 0.0) -> np.ndarray:
|
| 176 |
+
"""Partial correlations from a covariance matrix through the ridge-regularised precision ``(R + ridge I)^-1``
|
| 177 |
+
of its correlation matrix ``R``. Units with zero variance get zero rows and a zero diagonal entry. With
|
| 178 |
+
``ridge = 0`` the result is exact; a singular ``R`` then raises ``ValueError``."""
|
| 179 |
+
C = _square('cov', cov)
|
| 180 |
+
ridge = _check_float('ridge', ridge, 0.0, 1e6)
|
| 181 |
+
if not np.allclose(C, C.T, rtol=1e-9, atol=1e-12):
|
| 182 |
+
raise ValueError('cov must be symmetric')
|
| 183 |
+
C = 0.5 * (C + C.T)
|
| 184 |
+
d = np.diag(C).copy()
|
| 185 |
+
if np.any(d < 0):
|
| 186 |
+
raise ValueError('cov must have non-negative variances')
|
| 187 |
+
ok = d > 0
|
| 188 |
+
if np.any(C[~ok] != 0):
|
| 189 |
+
raise ValueError('zero-variance units must have zero covariance')
|
| 190 |
+
n = C.shape[0]
|
| 191 |
+
R = np.eye(n)
|
| 192 |
+
s = np.sqrt(d[ok])
|
| 193 |
+
R[np.ix_(ok, ok)] = C[np.ix_(ok, ok)] / np.outer(s, s)
|
| 194 |
+
np.fill_diagonal(R, 1.0)
|
| 195 |
+
S = R + ridge * np.eye(n)
|
| 196 |
+
w = np.linalg.eigvalsh(S)
|
| 197 |
+
if not w[0] > 1e-10 * max(1.0, float(w[-1])):
|
| 198 |
+
raise ValueError('correlation matrix is singular or not positive definite; use ridge > 0')
|
| 199 |
+
P = precision_to_partial(np.linalg.inv(S))
|
| 200 |
+
P[~ok, :] = 0.0
|
| 201 |
+
P[:, ~ok] = 0.0
|
| 202 |
+
np.fill_diagonal(P, ok.astype(np.float64))
|
| 203 |
+
return P
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def partial_correlation(X: Any, *, ridge: float = 1e-2) -> np.ndarray:
|
| 207 |
+
"""Partial correlations of a ``(T, n)`` series from the ridge-regularised precision of its correlation matrix."""
|
| 208 |
+
X = _series('X', X)
|
| 209 |
+
return partial_from_covariance(_pearson(X), ridge=ridge)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
# ====================================================================== dynamic FC
|
| 213 |
+
def sliding_window_fc(X: Any, window: int, step: int) -> tuple[np.ndarray, np.ndarray]:
|
| 214 |
+
"""Window start indices and Pearson FC per window, shape ``(W, n, n)``."""
|
| 215 |
+
X = _series('X', X)
|
| 216 |
+
T = X.shape[0]
|
| 217 |
+
window = _check_int('window', window, 3, T)
|
| 218 |
+
step = _check_int('step', step, 1, T)
|
| 219 |
+
starts = np.arange(0, T - window + 1, step, dtype=np.int64)
|
| 220 |
+
mats = np.stack([_pearson(X[s:s + window]) for s in starts])
|
| 221 |
+
return starts, mats
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def _sq_dists(V: np.ndarray, C: np.ndarray) -> np.ndarray:
|
| 225 |
+
d = (V * V).sum(1)[:, None] - 2.0 * (V @ C.T) + (C * C).sum(1)[None, :]
|
| 226 |
+
return np.maximum(d, 0.0)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def _canonical_labels(labels: np.ndarray, centers: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
| 230 |
+
"""Relabel clusters in order of first appearance so labels do not depend on initialisation order."""
|
| 231 |
+
order: list[int] = []
|
| 232 |
+
for v in labels.tolist():
|
| 233 |
+
if v not in order:
|
| 234 |
+
order.append(v)
|
| 235 |
+
order += [j for j in range(centers.shape[0]) if j not in order]
|
| 236 |
+
remap = np.empty(centers.shape[0], dtype=np.int64)
|
| 237 |
+
remap[np.asarray(order, dtype=np.int64)] = np.arange(centers.shape[0])
|
| 238 |
+
return remap[labels], centers[np.asarray(order, dtype=np.int64)]
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def kmeans(data: Any, k: int, *, seed: int = 0, n_init: int = 8, max_iter: int = 100) -> dict[str, Any]:
|
| 242 |
+
"""Deterministic k-means (Lloyd iterations, D^2-weighted seeding, ``n_init`` restarts, best inertia kept).
|
| 243 |
+
|
| 244 |
+
Seeding and restarts use ``numpy.random.default_rng(seed + offset)``. Empty clusters are re-seeded with the
|
| 245 |
+
point farthest from its centroid among clusters that keep at least one other member, so degenerate data
|
| 246 |
+
(repeated points) never leaves a cluster empty. Labels are canonicalised to order of first appearance."""
|
| 247 |
+
V = _series('data', data, min_rows=1, min_cols=1)
|
| 248 |
+
W = V.shape[0]
|
| 249 |
+
k = _check_int('k', k, 1, W)
|
| 250 |
+
seed = _check_int('seed', seed, 0, 2**31 - 1)
|
| 251 |
+
n_init = _check_int('n_init', n_init, 1, 1000)
|
| 252 |
+
max_iter = _check_int('max_iter', max_iter, 1, 100_000)
|
| 253 |
+
rng = np.random.default_rng(seed + _KMEANS_OFFSET)
|
| 254 |
+
best: tuple[np.ndarray, np.ndarray, float] | None = None
|
| 255 |
+
for _ in range(n_init):
|
| 256 |
+
idx = [int(rng.integers(W))]
|
| 257 |
+
d2 = _sq_dists(V, V[idx])[:, 0]
|
| 258 |
+
for _j in range(1, k):
|
| 259 |
+
total = float(d2.sum())
|
| 260 |
+
nxt = int(rng.integers(W)) if total <= 0.0 else int(rng.choice(W, p=d2 / total))
|
| 261 |
+
idx.append(nxt)
|
| 262 |
+
d2 = np.minimum(d2, _sq_dists(V, V[[nxt]])[:, 0])
|
| 263 |
+
C = V[idx].copy()
|
| 264 |
+
labels = np.full(W, -1, dtype=np.int64)
|
| 265 |
+
for _it in range(max_iter):
|
| 266 |
+
D = _sq_dists(V, C)
|
| 267 |
+
new = D.argmin(axis=1).astype(np.int64)
|
| 268 |
+
for j in range(k): # re-seed empty clusters deterministically
|
| 269 |
+
if not np.any(new == j):
|
| 270 |
+
# the point farthest from its centroid, taken only from a cluster with >= 2 members so
|
| 271 |
+
# that no other cluster is emptied (k <= W guarantees one exists); ties -> lowest index
|
| 272 |
+
sizes = np.bincount(new, minlength=k)
|
| 273 |
+
dist = np.where(sizes[new] > 1, D[np.arange(W), new], -np.inf)
|
| 274 |
+
far = int(dist.argmax())
|
| 275 |
+
new[far] = j
|
| 276 |
+
D[far] = np.inf
|
| 277 |
+
D[far, j] = 0.0
|
| 278 |
+
if np.array_equal(new, labels):
|
| 279 |
+
break
|
| 280 |
+
labels = new
|
| 281 |
+
for j in range(k):
|
| 282 |
+
C[j] = V[labels == j].mean(axis=0)
|
| 283 |
+
inertia = float(_sq_dists(V, C)[np.arange(W), labels].sum())
|
| 284 |
+
if best is None or inertia < best[2] - 1e-12 * max(1.0, best[2]):
|
| 285 |
+
best = (labels.copy(), C.copy(), inertia)
|
| 286 |
+
assert best is not None
|
| 287 |
+
labels, C = _canonical_labels(best[0], best[1])
|
| 288 |
+
return {'labels': labels, 'centroids': C, 'inertia': best[2], 'k': k}
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def silhouette_score(data: Any, labels: Any) -> float | None:
|
| 292 |
+
"""Mean silhouette width (Rousseeuw, 1987) with Euclidean distances; ``None`` unless 2 <= clusters < points.
|
| 293 |
+
Points alone in their cluster score 0."""
|
| 294 |
+
V = _series('data', data, min_rows=1, min_cols=1)
|
| 295 |
+
lab = np.asarray(labels)
|
| 296 |
+
if lab.shape != (V.shape[0],) or lab.dtype.kind not in 'iu':
|
| 297 |
+
raise ValueError('labels must be one integer per row of data')
|
| 298 |
+
uniq, inv = np.unique(lab, return_inverse=True)
|
| 299 |
+
W, k = V.shape[0], uniq.size
|
| 300 |
+
if k < 2 or k >= W:
|
| 301 |
+
return None
|
| 302 |
+
D = np.sqrt(_sq_dists(V, V))
|
| 303 |
+
onehot = np.zeros((W, k))
|
| 304 |
+
onehot[np.arange(W), inv] = 1.0
|
| 305 |
+
sums = D @ onehot
|
| 306 |
+
sizes = onehot.sum(0)
|
| 307 |
+
own_size = sizes[inv]
|
| 308 |
+
a = np.where(own_size > 1, sums[np.arange(W), inv] / np.maximum(own_size - 1.0, 1.0), 0.0)
|
| 309 |
+
mean_other = sums / sizes[None, :]
|
| 310 |
+
mean_other[np.arange(W), inv] = np.inf
|
| 311 |
+
b = mean_other.min(axis=1)
|
| 312 |
+
denom = np.maximum(a, b)
|
| 313 |
+
s = np.where((own_size > 1) & (denom > 0), (b - a) / np.where(denom > 0, denom, 1.0), 0.0)
|
| 314 |
+
return float(s.mean())
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def dwell_statistics(labels: Any, n_states: int | None = None) -> dict[str, Any]:
|
| 318 |
+
"""Run lengths of a state sequence: per-state mean dwell, overall mean dwell, occupancy and transitions."""
|
| 319 |
+
lab = np.asarray(labels)
|
| 320 |
+
if lab.ndim != 1 or lab.size == 0 or lab.dtype.kind not in 'iu' or lab.min() < 0:
|
| 321 |
+
raise ValueError('labels must be a non-empty 1-D array of non-negative integers')
|
| 322 |
+
k = int(lab.max()) + 1 if n_states is None else _check_int('n_states', n_states, int(lab.max()) + 1, 1_000_000)
|
| 323 |
+
change = np.flatnonzero(np.diff(lab) != 0)
|
| 324 |
+
starts = np.r_[0, change + 1]
|
| 325 |
+
lengths = np.diff(np.r_[starts, lab.size])
|
| 326 |
+
run_state = lab[starts]
|
| 327 |
+
per_state = []
|
| 328 |
+
for s in range(k):
|
| 329 |
+
r = lengths[run_state == s]
|
| 330 |
+
per_state.append(float(r.mean()) if r.size else None)
|
| 331 |
+
return {'n_states': k, 'runs': int(lengths.size), 'transitions': int(change.size),
|
| 332 |
+
'mean_dwell': float(lengths.mean()), 'mean_dwell_per_state': per_state,
|
| 333 |
+
'occupancy': (np.bincount(lab, minlength=k) / lab.size).tolist()}
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def dynamic_fc_states(X: Any, *, window: int, step: int | None = None, k_max: int = 4,
|
| 337 |
+
min_silhouette: float = 0.25, seed: int = 0, n_init: int = 8) -> dict[str, Any]:
|
| 338 |
+
"""Sliding-window FC states.
|
| 339 |
+
|
| 340 |
+
Windowed FC upper triangles are clustered with :func:`kmeans` for ``k = 2 .. k_max``; the k with the largest
|
| 341 |
+
mean silhouette wins. When no k reaches ``min_silhouette`` (a heuristic default of 0.25) or there are fewer
|
| 342 |
+
than three windows, the series is reported as a single FC state. Dwell times are run lengths of the window
|
| 343 |
+
state sequence, in windows and in samples (``x step``)."""
|
| 344 |
+
X = _series('X', X)
|
| 345 |
+
T, n = X.shape
|
| 346 |
+
window = _check_int('window', window, 3, T)
|
| 347 |
+
step = max(1, window // 4) if step is None else _check_int('step', step, 1, T)
|
| 348 |
+
k_max = _check_int('k_max', k_max, 2, 16)
|
| 349 |
+
min_silhouette = _check_float('min_silhouette', min_silhouette, -1.0, 1.0)
|
| 350 |
+
seed = _check_int('seed', seed, 0, 2**31 - 1)
|
| 351 |
+
starts, mats = sliding_window_fc(X, window, step)
|
| 352 |
+
iu = np.triu_indices(n, 1)
|
| 353 |
+
V = mats[:, iu[0], iu[1]]
|
| 354 |
+
W = int(starts.size)
|
| 355 |
+
scores: dict[int, float | None] = {}
|
| 356 |
+
best_k, best_s, labels = 1, None, np.zeros(W, dtype=np.int64)
|
| 357 |
+
if W >= 3:
|
| 358 |
+
for k in range(2, min(k_max, W - 1) + 1):
|
| 359 |
+
# modulo keeps the derived seed valid for seeds near 2**31 - 1 (unchanged for all smaller seeds)
|
| 360 |
+
km = kmeans(V, k, seed=(seed + 101 * k) % 2**31, n_init=n_init)
|
| 361 |
+
s = silhouette_score(V, km['labels'])
|
| 362 |
+
scores[k] = s
|
| 363 |
+
if s is not None and (best_s is None or s > best_s + 1e-12):
|
| 364 |
+
best_k, best_s, labels = k, s, km['labels']
|
| 365 |
+
if best_s is None or best_s < min_silhouette:
|
| 366 |
+
best_k, labels = 1, np.zeros(W, dtype=np.int64)
|
| 367 |
+
dw = dwell_statistics(labels, best_k)
|
| 368 |
+
centroids = np.stack([mats[labels == j].mean(axis=0) for j in range(best_k)])
|
| 369 |
+
return {'n_states': best_k, 'labels': labels, 'starts': starts, 'window': window, 'step': step, 'windows': W,
|
| 370 |
+
'silhouette': {int(k): v for k, v in scores.items()}, 'best_silhouette': best_s,
|
| 371 |
+
'mean_dwell_windows': dw['mean_dwell'], 'mean_dwell_samples': dw['mean_dwell'] * step,
|
| 372 |
+
'mean_dwell_per_state_windows': dw['mean_dwell_per_state'], 'occupancy': dw['occupancy'],
|
| 373 |
+
'transitions': dw['transitions'], 'state_fc': centroids}
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
# ====================================================================== effective connectivity
|
| 377 |
+
def _var_design(X: Any, ridge: float, standardize: bool) -> tuple[np.ndarray, np.ndarray, float]:
|
| 378 |
+
X = _series('X', X, min_rows=4)
|
| 379 |
+
ridge = _check_float('ridge', ridge, 0.0, 1e6)
|
| 380 |
+
if type(standardize) is not bool:
|
| 381 |
+
raise ValueError('standardize must be a boolean')
|
| 382 |
+
if standardize:
|
| 383 |
+
X, _ok = _zscore_columns(X)
|
| 384 |
+
P = X[:-1] - X[:-1].mean(axis=0)
|
| 385 |
+
F = X[1:] - X[1:].mean(axis=0)
|
| 386 |
+
return P, F, ridge * P.shape[0]
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def _solve(G: np.ndarray, R: np.ndarray) -> np.ndarray:
|
| 390 |
+
try:
|
| 391 |
+
return np.linalg.solve(G, R)
|
| 392 |
+
except np.linalg.LinAlgError as exc:
|
| 393 |
+
raise ValueError('lagged design is singular; use ridge > 0') from exc
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def var1_fit(X: Any, *, ridge: float = 1e-2, standardize: bool = True) -> np.ndarray:
|
| 397 |
+
"""Ridge VAR(1): ``A = argmin sum_t ||x_{t+1} - A x_t||^2 + lambda ||A||_F^2`` with ``lambda = ridge * (T-1)``
|
| 398 |
+
on (optionally z-scored) series with intercepts. Returns ``A[target, source]``."""
|
| 399 |
+
P, F, lam = _var_design(X, ridge, standardize)
|
| 400 |
+
n = P.shape[1]
|
| 401 |
+
return _solve(P.T @ P + lam * np.eye(n), P.T @ F).T
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def block_permutation(length: int, block: int, rng: np.random.Generator) -> np.ndarray:
|
| 405 |
+
"""A permutation of ``range(length)`` that reorders consecutive blocks of ``block`` indices (the last block
|
| 406 |
+
may be shorter) and keeps the order inside each block."""
|
| 407 |
+
length = _check_int('length', length, 1, 2**40)
|
| 408 |
+
block = _check_int('block', block, 1, length)
|
| 409 |
+
nb = -(-length // block)
|
| 410 |
+
order = rng.permutation(nb)
|
| 411 |
+
idx = (order[:, None] * block + np.arange(block)[None, :]).ravel()
|
| 412 |
+
return idx[idx < length]
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def _default_block(T: int) -> int:
|
| 416 |
+
return max(2, int(round(T ** (1.0 / 3.0)))) if T >= 8 else 1
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def _null_coefficients(P: np.ndarray, F: np.ndarray, lam: float, draws: int, block: int,
|
| 420 |
+
rng: np.random.Generator) -> np.ndarray:
|
| 421 |
+
"""Per-target conditional block-permutation null for the ridge VAR(1).
|
| 422 |
+
|
| 423 |
+
For draw b the rows of the source matrix are block-permuted (one permutation for all sources), except that
|
| 424 |
+
target i keeps its own unpermuted past. Each target's ridge system is assembled from shared cross-products and
|
| 425 |
+
all targets are solved in one batched call. Returns ``(draws, n, n)`` coefficients ``[target, source]``."""
|
| 426 |
+
Tm, n = P.shape
|
| 427 |
+
ar = np.arange(n)
|
| 428 |
+
self_g = (P * P).sum(axis=0)
|
| 429 |
+
self_r = (P * F).sum(axis=0)
|
| 430 |
+
ridge_eye = lam * np.eye(n)
|
| 431 |
+
out = np.empty((draws, n, n))
|
| 432 |
+
for b in range(draws):
|
| 433 |
+
Pp = P[block_permutation(Tm, block, rng)]
|
| 434 |
+
cpp = Pp.T @ Pp
|
| 435 |
+
cross = P.T @ Pp # cross[i, j] = P_i . Pp_j
|
| 436 |
+
rf = Pp.T @ F # rf[j, i] = Pp_j . F_i
|
| 437 |
+
G = np.repeat(cpp[None, :, :], n, axis=0)
|
| 438 |
+
G[ar, ar, :] = cross # row i of target i's Gram
|
| 439 |
+
G[ar, :, ar] = cross # column i of target i's Gram
|
| 440 |
+
G[ar, ar, ar] = self_g
|
| 441 |
+
r = rf.T.copy()
|
| 442 |
+
r[ar, ar] = self_r
|
| 443 |
+
out[b] = _solve(G + ridge_eye, r[..., None])[..., 0]
|
| 444 |
+
return out
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def var1_permutation_null(X: Any, *, ridge: float = 1e-2, standardize: bool = True, draws: int = 99,
|
| 448 |
+
block: int | None = None, seed: int = 0) -> np.ndarray:
|
| 449 |
+
"""Null coefficients ``(draws, n, n)`` of the per-target conditional block-permutation null (see
|
| 450 |
+
:func:`effective_connectivity`)."""
|
| 451 |
+
P, F, lam = _var_design(X, ridge, standardize)
|
| 452 |
+
draws = _check_int('draws', draws, 1, 100_000)
|
| 453 |
+
block = _default_block(P.shape[0]) if block is None else _check_int('block', block, 1, P.shape[0])
|
| 454 |
+
rng = np.random.default_rng(_check_int('seed', seed, 0, 2**31 - 1) + _PERM_OFFSET)
|
| 455 |
+
return _null_coefficients(P, F, lam, draws, block, rng)
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
def benjamini_hochberg(p_values: Any, alpha: float = 0.05) -> np.ndarray:
|
| 459 |
+
"""Benjamini-Hochberg step-up rejections at FDR level ``alpha`` (boolean mask, same shape as the input)."""
|
| 460 |
+
p = np.asarray(p_values, dtype=np.float64)
|
| 461 |
+
alpha = _check_float('alpha', alpha, 0.0, 1.0)
|
| 462 |
+
if not np.all(np.isfinite(p)) or np.any(p < 0.0) or np.any(p > 1.0):
|
| 463 |
+
raise ValueError('p-values must be finite and in [0, 1]')
|
| 464 |
+
flat = p.ravel()
|
| 465 |
+
m = flat.size
|
| 466 |
+
reject = np.zeros(m, dtype=bool)
|
| 467 |
+
if m:
|
| 468 |
+
order = np.argsort(flat, kind='stable')
|
| 469 |
+
below = flat[order] <= alpha * np.arange(1, m + 1) / m
|
| 470 |
+
if below.any():
|
| 471 |
+
reject[order[:int(np.flatnonzero(below).max()) + 1]] = True
|
| 472 |
+
return reject.reshape(p.shape)
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
def _ec_from_design(P: np.ndarray, F: np.ndarray, lam: float, draws: int, block: int, alpha: float,
|
| 476 |
+
rng: np.random.Generator) -> dict[str, Any]:
|
| 477 |
+
n = P.shape[1]
|
| 478 |
+
A = _solve(P.T @ P + lam * np.eye(n), P.T @ F).T
|
| 479 |
+
null = _null_coefficients(P, F, lam, draws, block, rng)
|
| 480 |
+
mu = null.mean(axis=0)
|
| 481 |
+
sd = null.std(axis=0, ddof=1) if draws > 1 else np.zeros((n, n))
|
| 482 |
+
dev = A - mu
|
| 483 |
+
z = np.divide(dev, sd, out=np.zeros((n, n)), where=sd > _EPS)
|
| 484 |
+
p_norm = np.vectorize(lambda v: math.erfc(abs(v) / math.sqrt(2.0)))(z) if n else np.zeros((0, 0))
|
| 485 |
+
p_rank = (1.0 + (np.abs(null - mu[None]) >= np.abs(dev)[None] - 1e-15).sum(axis=0)) / (1.0 + draws)
|
| 486 |
+
off = ~np.eye(n, dtype=bool)
|
| 487 |
+
mask = np.zeros((n, n), dtype=bool)
|
| 488 |
+
mask[off] = benjamini_hochberg(p_norm[off], alpha)
|
| 489 |
+
mask &= sd > _EPS
|
| 490 |
+
pairs = n * (n - 1)
|
| 491 |
+
return {'A': A, 'z': z, 'p': p_norm, 'p_rank': p_rank, 'mask': mask, 'null_mean': mu, 'null_sd': sd,
|
| 492 |
+
'density': float(mask.sum() / pairs) if pairs else 0.0, 'significant': int(mask.sum()),
|
| 493 |
+
'draws': int(draws), 'block': int(block), 'alpha': float(alpha)}
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
def effective_connectivity(X: Any, *, ridge: float = 1e-2, null_draws: int = 99, block: int | None = None,
|
| 497 |
+
alpha: float = 0.05, seed: int = 0, standardize: bool = True) -> dict[str, Any]:
|
| 498 |
+
"""Ridge VAR(1) effective connectivity with a block-permutation significance mask.
|
| 499 |
+
|
| 500 |
+
``A[target, source]`` comes from :func:`var1_fit`. For every target the null refits its ridge regression with
|
| 501 |
+
its own past intact and the other sources block-permuted jointly in time (``null_draws`` draws, block length
|
| 502 |
+
``round((T-1)^(1/3))`` by default), which keeps each source's autocorrelation inside blocks but breaks lagged
|
| 503 |
+
coupling. Each edge gets ``z = (A - mean_null) / sd_null`` and a two-sided normal p-value; the mask is
|
| 504 |
+
Benjamini-Hochberg at FDR ``alpha`` over the off-diagonal edges. Rank p-values ``(1 + #{|null| >= |A|}) /
|
| 505 |
+
(1 + draws)`` are reported too. Lagged regression measures predictive (Granger-style) influence only."""
|
| 506 |
+
P, F, lam = _var_design(X, ridge, standardize)
|
| 507 |
+
draws = _check_int('null_draws', null_draws, 2, 100_000)
|
| 508 |
+
block = _default_block(P.shape[0]) if block is None else _check_int('block', block, 1, P.shape[0])
|
| 509 |
+
alpha = _check_float('alpha', alpha, 0.0, 1.0)
|
| 510 |
+
rng = np.random.default_rng(_check_int('seed', seed, 0, 2**31 - 1) + _PERM_OFFSET)
|
| 511 |
+
out = _ec_from_design(P, F, lam, draws, block, alpha, rng)
|
| 512 |
+
out['ridge'] = float(ridge)
|
| 513 |
+
return out
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
def auroc(scores: Any, labels: Any) -> float | None:
|
| 517 |
+
"""Area under the ROC curve via the Mann-Whitney statistic (average ranks for ties); ``None`` if a class is empty."""
|
| 518 |
+
from scipy.stats import rankdata
|
| 519 |
+
s = np.asarray(scores, dtype=np.float64).ravel()
|
| 520 |
+
y = np.asarray(labels).ravel().astype(bool)
|
| 521 |
+
if s.shape != y.shape or not np.all(np.isfinite(s)):
|
| 522 |
+
raise ValueError('scores must be finite and match labels')
|
| 523 |
+
pos, neg = int(y.sum()), int((~y).sum())
|
| 524 |
+
if pos == 0 or neg == 0:
|
| 525 |
+
return None
|
| 526 |
+
r = rankdata(s)
|
| 527 |
+
return float((r[y].sum() - pos * (pos + 1) / 2.0) / (pos * neg))
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
# ====================================================================== structure and coupling
|
| 531 |
+
def structural_matrix(n: int, src: Any, dst: Any, weight: Any, *, absolute: bool = True,
|
| 532 |
+
symmetric: bool = False) -> np.ndarray:
|
| 533 |
+
"""Dense ``(n, n)`` structural matrix ``W[src, dst]`` (duplicate edges summed, diagonal zeroed).
|
| 534 |
+
``absolute`` takes ``|w|``; ``symmetric`` returns ``W + W.T``."""
|
| 535 |
+
n = _check_int('n', n, 1, 100_000)
|
| 536 |
+
s = np.asarray(src)
|
| 537 |
+
d = np.asarray(dst)
|
| 538 |
+
w = np.asarray(weight, dtype=np.float64)
|
| 539 |
+
if s.ndim != 1 or s.shape != d.shape or s.shape != w.shape or (s.size and (s.dtype.kind not in 'iu' or d.dtype.kind not in 'iu')):
|
| 540 |
+
raise ValueError('src, dst and weight must be 1-D arrays of equal length (integer endpoints)')
|
| 541 |
+
if s.size and (s.min() < 0 or s.max() >= n or d.min() < 0 or d.max() >= n):
|
| 542 |
+
raise ValueError('edge endpoint out of range')
|
| 543 |
+
if not np.all(np.isfinite(w)):
|
| 544 |
+
raise ValueError('weights must be finite')
|
| 545 |
+
W = np.zeros((n, n))
|
| 546 |
+
np.add.at(W, (s.astype(np.int64), d.astype(np.int64)), np.abs(w) if absolute else w)
|
| 547 |
+
np.fill_diagonal(W, 0.0)
|
| 548 |
+
return W + W.T if symmetric else W
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
def weighted_communicability(S: Any) -> np.ndarray:
|
| 552 |
+
"""Weighted communicability ``exp(D^-1/2 S D^-1/2)`` (Crofts & Higham, 2009, eq. 2.2) of a symmetric
|
| 553 |
+
non-negative matrix, ``D = diag(sum_k S_ik)``; isolated nodes keep their (zero) rows."""
|
| 554 |
+
S = _square('S', S)
|
| 555 |
+
if not np.allclose(S, S.T, rtol=1e-9, atol=1e-12) or np.any(S < 0.0):
|
| 556 |
+
raise ValueError('S must be symmetric and non-negative')
|
| 557 |
+
S = 0.5 * (S + S.T)
|
| 558 |
+
d = S.sum(axis=1)
|
| 559 |
+
inv = np.where(d > _EPS, 1.0 / np.sqrt(np.where(d > _EPS, d, 1.0)), 0.0)
|
| 560 |
+
N = inv[:, None] * S * inv[None, :]
|
| 561 |
+
vals, vecs = np.linalg.eigh(N)
|
| 562 |
+
return (vecs * np.exp(vals)[None, :]) @ vecs.T
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
def _spearman(a: np.ndarray, b: np.ndarray) -> float | None:
|
| 566 |
+
from scipy.stats import rankdata
|
| 567 |
+
if a.size < 3 or np.ptp(a) <= 0.0 or np.ptp(b) <= 0.0:
|
| 568 |
+
return None
|
| 569 |
+
ra, rb = rankdata(a), rankdata(b)
|
| 570 |
+
ra -= ra.mean()
|
| 571 |
+
rb -= rb.mean()
|
| 572 |
+
den = math.sqrt(float((ra * ra).sum() * (rb * rb).sum()))
|
| 573 |
+
return float(np.clip((ra * rb).sum() / den, -1.0, 1.0)) if den > 0 else None
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
def structure_function_coupling(structure: Any, fc: Any) -> dict[str, Any]:
|
| 577 |
+
"""Spearman coupling between symmetric structural weights and FC over node pairs ``i < j``.
|
| 578 |
+
|
| 579 |
+
``structure`` is any non-negative ``(n, n)`` matrix (it is symmetrised as ``(S + S.T) / 2``). Reports the
|
| 580 |
+
coupling over all pairs and over structurally connected pairs, against signed and absolute FC, and the
|
| 581 |
+
same for weighted communicability (an analytic predictor that also credits indirect walks)."""
|
| 582 |
+
S = _square('structure', structure)
|
| 583 |
+
F = _square('fc', fc, S.shape[0])
|
| 584 |
+
if np.any(S < 0.0):
|
| 585 |
+
raise ValueError('structure must be non-negative')
|
| 586 |
+
S = 0.5 * (S + S.T)
|
| 587 |
+
np.fill_diagonal(S, 0.0)
|
| 588 |
+
n = S.shape[0]
|
| 589 |
+
iu = np.triu_indices(n, 1)
|
| 590 |
+
s, f = S[iu], F[iu]
|
| 591 |
+
conn = s > 0.0
|
| 592 |
+
G = weighted_communicability(S)
|
| 593 |
+
g = G[iu]
|
| 594 |
+
return {'pairs': int(s.size), 'connected_pairs': int(conn.sum()),
|
| 595 |
+
'sc_fc_spearman': _spearman(s, f), 'sc_absfc_spearman': _spearman(s, np.abs(f)),
|
| 596 |
+
'sc_fc_spearman_connected': _spearman(s[conn], f[conn]) if conn.sum() >= 3 else None,
|
| 597 |
+
'communicability_fc_spearman': _spearman(g, f),
|
| 598 |
+
'communicability_absfc_spearman': _spearman(g, np.abs(f)),
|
| 599 |
+
'mean_fc_connected': float(f[conn].mean()) if conn.any() else None,
|
| 600 |
+
'mean_fc_unconnected': float(f[~conn].mean()) if (~conn).any() else None}
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
def modularity(W: Any, labels: Any) -> float:
|
| 604 |
+
"""Newman-Girvan modularity ``Q = (1/2m) sum_ij (W_ij - k_i k_j / 2m) [c_i == c_j]`` of a symmetric
|
| 605 |
+
non-negative weight matrix (0 for an empty graph)."""
|
| 606 |
+
A = _square('W', W)
|
| 607 |
+
if np.any(A < 0.0):
|
| 608 |
+
raise ValueError('W must be non-negative')
|
| 609 |
+
A = 0.5 * (A + A.T)
|
| 610 |
+
lab = np.asarray(labels)
|
| 611 |
+
if lab.shape != (A.shape[0],):
|
| 612 |
+
raise ValueError('labels must have one entry per node')
|
| 613 |
+
two_m = float(A.sum())
|
| 614 |
+
if two_m <= _EPS:
|
| 615 |
+
return 0.0
|
| 616 |
+
k = A.sum(axis=1)
|
| 617 |
+
same = lab[:, None] == lab[None, :]
|
| 618 |
+
return float(((A - np.outer(k, k) / two_m) * same).sum() / two_m)
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
def fc_communities(fc: Any, *, max_communities: int = 8) -> dict[str, Any]:
|
| 622 |
+
"""Leading-eigenvector communities (Newman, 2006) of the positive part of an FC matrix.
|
| 623 |
+
|
| 624 |
+
Recursive bisection: a group g splits by the signs of the leading eigenvector of its generalised modularity
|
| 625 |
+
matrix ``B^(g)_ij = B_ij - delta_ij sum_{l in g} B_il`` while the leading eigenvalue and the gain
|
| 626 |
+
``s^T B^(g) s / 4m`` are positive and fewer than ``max_communities`` groups exist. No vertex-moving
|
| 627 |
+
refinement, so the reported modularity is a proxy (a lower bound on the maximum)."""
|
| 628 |
+
F = _square('fc', fc)
|
| 629 |
+
max_communities = _check_int('max_communities', max_communities, 1, 4096)
|
| 630 |
+
W = np.clip(0.5 * (F + F.T), 0.0, None)
|
| 631 |
+
np.fill_diagonal(W, 0.0)
|
| 632 |
+
n = W.shape[0]
|
| 633 |
+
two_m = float(W.sum())
|
| 634 |
+
labels = np.zeros(n, dtype=np.int64)
|
| 635 |
+
if two_m <= _EPS or n < 2:
|
| 636 |
+
return {'labels': labels, 'communities': 1, 'modularity': 0.0}
|
| 637 |
+
k = W.sum(axis=1)
|
| 638 |
+
B = W - np.outer(k, k) / two_m
|
| 639 |
+
pending, final = [np.arange(n)], []
|
| 640 |
+
while pending:
|
| 641 |
+
g = pending.pop(0)
|
| 642 |
+
if g.size < 2 or len(final) + len(pending) + 1 >= max_communities:
|
| 643 |
+
final.append(g)
|
| 644 |
+
continue
|
| 645 |
+
Bg = B[np.ix_(g, g)].copy()
|
| 646 |
+
Bg[np.diag_indices(g.size)] -= Bg.sum(axis=1)
|
| 647 |
+
vals, vecs = np.linalg.eigh(Bg)
|
| 648 |
+
lead = vecs[:, -1]
|
| 649 |
+
s = np.where(lead >= 0.0, 1.0, -1.0)
|
| 650 |
+
gain = float(s @ Bg @ s) / (2.0 * two_m)
|
| 651 |
+
tol = 1e-10 * (1.0 + float(np.abs(vals).max()))
|
| 652 |
+
if vals[-1] <= tol or gain <= 1e-12 or np.all(s == s[0]):
|
| 653 |
+
final.append(g)
|
| 654 |
+
continue
|
| 655 |
+
pending += [g[s > 0], g[s < 0]]
|
| 656 |
+
final.sort(key=lambda grp: int(grp.min()))
|
| 657 |
+
for c, grp in enumerate(final):
|
| 658 |
+
labels[grp] = c
|
| 659 |
+
return {'labels': labels, 'communities': len(final), 'modularity': modularity(W, labels)}
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
# ====================================================================== live observer
|
| 663 |
+
_METRIC_INT = ('computed_at', 'rows', 'constant_units')
|
| 664 |
+
_METRIC_OPT_INT = ('fc_communities', 'dfc_window', 'dfc_windows', 'dfc_states', 'dfc_transitions', 'ec_significant')
|
| 665 |
+
_METRIC_OPT_FLOAT = ('mean_abs_fc', 'fc_modularity', 'dfc_silhouette', 'dfc_mean_dwell_windows',
|
| 666 |
+
'dfc_mean_dwell_steps', 'ec_density')
|
| 667 |
+
_METRIC_KEYS = _METRIC_INT + _METRIC_OPT_INT + _METRIC_OPT_FLOAT + ('ec_top_edges',)
|
| 668 |
+
_EDGE_KEYS = ('source', 'target', 'weight', 'z', 'significant')
|
| 669 |
+
|
| 670 |
+
|
| 671 |
+
class ConnectivityObserver:
|
| 672 |
+
"""Read-only live observer: FC, dynamic FC states and ridge-VAR(1) EC over a bounded activity history.
|
| 673 |
+
|
| 674 |
+
* A deterministic subset of at most ``max_units`` observed units (seeded) is kept in a ring buffer of
|
| 675 |
+
``history`` rows. ``observe`` copies the values; it never writes to its input.
|
| 676 |
+
* Metrics are recomputed at most every ``max(8, window // 4)`` observations, once ``window`` rows exist:
|
| 677 |
+
static FC and EC on the last ``window`` rows, dynamic FC on the whole buffer (window ``max(8, window // 4)``,
|
| 678 |
+
step half of it). EC uses ``ec_null_draws`` per-target block-permutation draws seeded by
|
| 679 |
+
``(seed, observed steps)``, so results do not depend on how often ``summary`` is called.
|
| 680 |
+
* ``summary()`` returns the cached metrics: mean |FC|, the FC modularity proxy and community count, the
|
| 681 |
+
number of dFC states with silhouette and mean dwell, EC density with the top-5 directed edges by |z|, and
|
| 682 |
+
the observed step count. Unit indices refer to positions in the observed vector.
|
| 683 |
+
* ``window`` defaults to 128; the FrontierSpecV1 name ``fc_window`` is accepted as the same parameter
|
| 684 |
+
(clipped to ``history``), and the spec parameters of other observers are accepted and ignored."""
|
| 685 |
+
|
| 686 |
+
module_id = MODULE_ID
|
| 687 |
+
|
| 688 |
+
def __init__(self, n_units: int, *, seed: int = 7, history: int = 256, window: int | None = None,
|
| 689 |
+
max_units: int = 32, k_max: int = 4, ec_null_draws: int = 31, ridge: float = 0.05,
|
| 690 |
+
alpha: float = 0.05, min_silhouette: float = 0.25, **params: Any) -> None:
|
| 691 |
+
unknown = sorted(set(params) - _SPEC_OBSERVER_PARAMS)
|
| 692 |
+
if unknown:
|
| 693 |
+
raise ValueError(f'unknown ConnectivityObserver parameters: {unknown}')
|
| 694 |
+
self.n_units = _check_int('n_units', n_units, 2, 1_000_000)
|
| 695 |
+
self.seed = _check_int('seed', seed, 0, 2**31 - 1)
|
| 696 |
+
self.history = _check_int('history', history, 16, 8192)
|
| 697 |
+
fc_window = params.get('fc_window') # FrontierSpecV1 name of the static FC / EC window
|
| 698 |
+
if fc_window is not None:
|
| 699 |
+
fc_window = min(_check_int('fc_window', fc_window, 8, 1_000_000), self.history)
|
| 700 |
+
if window is not None and window != fc_window:
|
| 701 |
+
raise ValueError('window and fc_window disagree')
|
| 702 |
+
if window is None:
|
| 703 |
+
window = 128 if fc_window is None else fc_window
|
| 704 |
+
self.window = _check_int('window', window, 8, self.history)
|
| 705 |
+
self.max_units = _check_int('max_units', max_units, 2, 256)
|
| 706 |
+
self.k_max = _check_int('k_max', k_max, 2, 8)
|
| 707 |
+
self.ec_null_draws = _check_int('ec_null_draws', ec_null_draws, 2, 999)
|
| 708 |
+
self.ridge = _check_float('ridge', ridge, 1e-6, 1e3)
|
| 709 |
+
self.alpha = _check_float('alpha', alpha, 1e-6, 0.5)
|
| 710 |
+
self.min_silhouette = _check_float('min_silhouette', min_silhouette, 0.0, 1.0)
|
| 711 |
+
self.recompute_every = max(8, self.window // 4)
|
| 712 |
+
self.dfc_window = max(8, self.window // 4)
|
| 713 |
+
m = min(self.n_units, self.max_units)
|
| 714 |
+
if m == self.n_units:
|
| 715 |
+
units = np.arange(m, dtype=np.int64)
|
| 716 |
+
else:
|
| 717 |
+
units = np.sort(np.random.default_rng(self.seed + _OBS_UNITS_OFFSET).choice(self.n_units, m, replace=False))
|
| 718 |
+
self._units = units.astype(np.int64)
|
| 719 |
+
self.reset()
|
| 720 |
+
|
| 721 |
+
@classmethod
|
| 722 |
+
def from_spec(cls, n_units: int, spec: Any) -> 'ConnectivityObserver':
|
| 723 |
+
"""Build from a ``FrontierSpecV1`` (``seed``, ``history``, ``fc_window`` clipped to ``history``)."""
|
| 724 |
+
from .spec import FrontierSpecV1
|
| 725 |
+
if not isinstance(spec, FrontierSpecV1):
|
| 726 |
+
raise ValueError('spec must be a FrontierSpecV1')
|
| 727 |
+
return cls(n_units, seed=int(spec.seed), history=int(spec.history),
|
| 728 |
+
window=min(int(spec.fc_window), int(spec.history)))
|
| 729 |
+
|
| 730 |
+
def reset(self) -> None:
|
| 731 |
+
self._buf = np.zeros((self.history, self._units.size))
|
| 732 |
+
self._steps = 0
|
| 733 |
+
self._last = -1
|
| 734 |
+
self._metrics: dict[str, Any] | None = None
|
| 735 |
+
|
| 736 |
+
@property
|
| 737 |
+
def observed_steps(self) -> int:
|
| 738 |
+
return self._steps
|
| 739 |
+
|
| 740 |
+
@property
|
| 741 |
+
def units(self) -> np.ndarray:
|
| 742 |
+
return self._units.copy()
|
| 743 |
+
|
| 744 |
+
def _rows(self) -> np.ndarray:
|
| 745 |
+
count = min(self._steps, self.history)
|
| 746 |
+
if self._steps <= self.history:
|
| 747 |
+
return self._buf[:count].copy()
|
| 748 |
+
pos = self._steps % self.history
|
| 749 |
+
return np.concatenate([self._buf[pos:], self._buf[:pos]])
|
| 750 |
+
|
| 751 |
+
def observe(self, x: np.ndarray) -> None:
|
| 752 |
+
try:
|
| 753 |
+
v = np.array(x, dtype=np.float64) # private copy: the caller's array is never touched
|
| 754 |
+
except (TypeError, ValueError) as exc:
|
| 755 |
+
raise ValueError(f'observation must be a finite 1-D array of length {self.n_units}') from exc
|
| 756 |
+
if v.shape != (self.n_units,) or not np.all(np.isfinite(v)):
|
| 757 |
+
raise ValueError(f'observation must be a finite 1-D array of length {self.n_units}')
|
| 758 |
+
self._buf[self._steps % self.history] = v[self._units]
|
| 759 |
+
self._steps += 1
|
| 760 |
+
if self._steps >= self.window and (self._last < 0 or self._steps - self._last >= self.recompute_every):
|
| 761 |
+
self._metrics = self._compute()
|
| 762 |
+
self._last = self._steps
|
| 763 |
+
|
| 764 |
+
def _compute(self) -> dict[str, Any]:
|
| 765 |
+
rows = self._rows()
|
| 766 |
+
static = rows[-self.window:]
|
| 767 |
+
fc = _pearson(static)
|
| 768 |
+
ok = np.diag(fc) > 0.5
|
| 769 |
+
idx = np.flatnonzero(ok)
|
| 770 |
+
m: dict[str, Any] = {k: None for k in _METRIC_KEYS}
|
| 771 |
+
m.update(computed_at=int(self._steps), rows=int(rows.shape[0]), constant_units=int((~ok).sum()),
|
| 772 |
+
ec_top_edges=[])
|
| 773 |
+
if idx.size < 2:
|
| 774 |
+
return m
|
| 775 |
+
sub = fc[np.ix_(idx, idx)]
|
| 776 |
+
iu = np.triu_indices(idx.size, 1)
|
| 777 |
+
m['mean_abs_fc'] = float(np.abs(sub[iu]).mean())
|
| 778 |
+
com = fc_communities(sub)
|
| 779 |
+
m['fc_modularity'] = float(com['modularity'])
|
| 780 |
+
m['fc_communities'] = int(com['communities'])
|
| 781 |
+
data = rows[:, idx]
|
| 782 |
+
w = min(self.dfc_window, data.shape[0])
|
| 783 |
+
step = max(1, w // 2)
|
| 784 |
+
n_win = (data.shape[0] - w) // step + 1
|
| 785 |
+
if n_win >= 3:
|
| 786 |
+
d = dynamic_fc_states(data, window=w, step=step, k_max=self.k_max, min_silhouette=self.min_silhouette,
|
| 787 |
+
seed=self.seed, n_init=4)
|
| 788 |
+
m.update(dfc_window=int(w), dfc_windows=int(d['windows']), dfc_states=int(d['n_states']),
|
| 789 |
+
dfc_silhouette=None if d['best_silhouette'] is None else float(d['best_silhouette']),
|
| 790 |
+
dfc_mean_dwell_windows=float(d['mean_dwell_windows']),
|
| 791 |
+
dfc_mean_dwell_steps=float(d['mean_dwell_samples']), dfc_transitions=int(d['transitions']))
|
| 792 |
+
Z, _ok = _zscore_columns(static[:, idx])
|
| 793 |
+
P = Z[:-1] - Z[:-1].mean(axis=0)
|
| 794 |
+
F = Z[1:] - Z[1:].mean(axis=0)
|
| 795 |
+
rng = np.random.default_rng([self.seed + _OBS_PERM_OFFSET, self._steps])
|
| 796 |
+
ec = _ec_from_design(P, F, self.ridge * P.shape[0], self.ec_null_draws, _default_block(P.shape[0]),
|
| 797 |
+
self.alpha, rng)
|
| 798 |
+
m['ec_density'] = float(ec['density'])
|
| 799 |
+
m['ec_significant'] = int(ec['significant'])
|
| 800 |
+
off = ~np.eye(idx.size, dtype=bool)
|
| 801 |
+
tgt, src = np.nonzero(off)
|
| 802 |
+
mag = np.abs(ec['z'][tgt, src])
|
| 803 |
+
order = np.lexsort((src, tgt, -mag))[:_TOP_EDGES]
|
| 804 |
+
units = self._units[idx]
|
| 805 |
+
m['ec_top_edges'] = [{'source': int(units[src[e]]), 'target': int(units[tgt[e]]),
|
| 806 |
+
'weight': float(ec['A'][tgt[e], src[e]]), 'z': float(ec['z'][tgt[e], src[e]]),
|
| 807 |
+
'significant': bool(ec['mask'][tgt[e], src[e]])} for e in order]
|
| 808 |
+
return m
|
| 809 |
+
|
| 810 |
+
def summary(self) -> dict[str, Any]:
|
| 811 |
+
out: dict[str, Any] = {'module': MODULE_ID, 'evidence_tier': 'synthetic_abstraction',
|
| 812 |
+
'n_units': self.n_units, 'analysed_units': int(self._units.size),
|
| 813 |
+
'unit_sample': self._units.tolist(), 'history': self.history, 'window': self.window,
|
| 814 |
+
'recompute_every': self.recompute_every, 'observed_steps': self._steps,
|
| 815 |
+
'buffered': min(self._steps, self.history), 'ready': self._metrics is not None}
|
| 816 |
+
metrics = self._metrics if self._metrics is not None else {k: None for k in _METRIC_KEYS}
|
| 817 |
+
for key in _METRIC_KEYS:
|
| 818 |
+
value = metrics[key]
|
| 819 |
+
out[key] = [dict(e) for e in value] if key == 'ec_top_edges' and value is not None else value
|
| 820 |
+
if out['ec_top_edges'] is None:
|
| 821 |
+
out['ec_top_edges'] = []
|
| 822 |
+
return out
|
| 823 |
+
|
| 824 |
+
def _config(self) -> dict[str, Any]:
|
| 825 |
+
return {'n_units': self.n_units, 'seed': self.seed, 'history': self.history, 'window': self.window,
|
| 826 |
+
'max_units': self.max_units, 'k_max': self.k_max, 'ec_null_draws': self.ec_null_draws,
|
| 827 |
+
'ridge': self.ridge, 'alpha': self.alpha, 'min_silhouette': self.min_silhouette}
|
| 828 |
+
|
| 829 |
+
def export_state(self) -> dict[str, Any]:
|
| 830 |
+
metrics = None if self._metrics is None else {
|
| 831 |
+
k: ([dict(e) for e in v] if k == 'ec_top_edges' else v) for k, v in self._metrics.items()}
|
| 832 |
+
return {'module': MODULE_ID, 'schema': OBSERVER_STATE_SCHEMA, **self._config(), 'units': self._units.tolist(),
|
| 833 |
+
'buffer': self._buf.tolist(), 'steps': self._steps, 'last': self._last, 'metrics': metrics}
|
| 834 |
+
|
| 835 |
+
def _validate_metrics(self, metrics: Any, steps: int, last: int) -> dict[str, Any] | None:
|
| 836 |
+
if last < 0:
|
| 837 |
+
if metrics is not None:
|
| 838 |
+
raise ValueError('connectivity observer state has metrics but no recompute')
|
| 839 |
+
return None
|
| 840 |
+
if not isinstance(metrics, Mapping) or set(metrics) != set(_METRIC_KEYS):
|
| 841 |
+
raise ValueError('connectivity observer metrics have the wrong keys')
|
| 842 |
+
out: dict[str, Any] = {}
|
| 843 |
+
for key in _METRIC_INT:
|
| 844 |
+
out[key] = _check_int(f'metrics.{key}', metrics[key], 0, 2**62)
|
| 845 |
+
for key in _METRIC_OPT_INT:
|
| 846 |
+
out[key] = None if metrics[key] is None else _check_int(f'metrics.{key}', metrics[key], 0, 2**62)
|
| 847 |
+
for key in _METRIC_OPT_FLOAT:
|
| 848 |
+
out[key] = None if metrics[key] is None else _check_float(f'metrics.{key}', metrics[key], -1.0, 1e12)
|
| 849 |
+
if out['computed_at'] != last or out['rows'] != min(last, self.history) or out['constant_units'] > self._units.size:
|
| 850 |
+
raise ValueError('connectivity observer metrics do not match the recompute step')
|
| 851 |
+
for key in ('mean_abs_fc', 'ec_density'):
|
| 852 |
+
if out[key] is not None and not 0.0 <= out[key] <= 1.0:
|
| 853 |
+
raise ValueError(f'metrics.{key} must lie in [0, 1]')
|
| 854 |
+
edges = metrics['ec_top_edges']
|
| 855 |
+
if not isinstance(edges, list) or len(edges) > _TOP_EDGES:
|
| 856 |
+
raise ValueError('metrics.ec_top_edges must be a list of at most 5 edges')
|
| 857 |
+
clean = []
|
| 858 |
+
allowed = set(self._units.tolist())
|
| 859 |
+
for e in edges:
|
| 860 |
+
if not isinstance(e, Mapping) or set(e) != set(_EDGE_KEYS):
|
| 861 |
+
raise ValueError('ec_top_edges entries have the wrong keys')
|
| 862 |
+
s = _check_int('edge.source', e['source'], 0, self.n_units - 1)
|
| 863 |
+
t = _check_int('edge.target', e['target'], 0, self.n_units - 1)
|
| 864 |
+
if s == t or s not in allowed or t not in allowed or type(e['significant']) is not bool:
|
| 865 |
+
raise ValueError('ec_top_edges entry is invalid')
|
| 866 |
+
clean.append({'source': s, 'target': t, 'weight': _check_float('edge.weight', e['weight'], -1e12, 1e12),
|
| 867 |
+
'z': _check_float('edge.z', e['z'], -1e12, 1e12), 'significant': e['significant']})
|
| 868 |
+
out['ec_top_edges'] = clean
|
| 869 |
+
return out
|
| 870 |
+
|
| 871 |
+
def import_state(self, state: Mapping[str, Any]) -> None:
|
| 872 |
+
"""Validate the whole state first; nothing changes unless every check passes."""
|
| 873 |
+
if not isinstance(state, Mapping) or state.get('module') != MODULE_ID or state.get('schema') != OBSERVER_STATE_SCHEMA:
|
| 874 |
+
raise ValueError('state is not a connectivity observer state')
|
| 875 |
+
for key, value in self._config().items():
|
| 876 |
+
if state.get(key) != value:
|
| 877 |
+
raise ValueError(f'connectivity observer state does not match this observer ({key})')
|
| 878 |
+
if state.get('units') != self._units.tolist():
|
| 879 |
+
raise ValueError('connectivity observer state units do not match this observer')
|
| 880 |
+
try:
|
| 881 |
+
buf = np.array(state.get('buffer'), dtype=np.float64)
|
| 882 |
+
except (TypeError, ValueError) as exc:
|
| 883 |
+
raise ValueError('buffer must be numeric') from exc
|
| 884 |
+
if buf.shape != self._buf.shape or not np.all(np.isfinite(buf)):
|
| 885 |
+
raise ValueError('connectivity observer buffer has the wrong shape or non-finite values')
|
| 886 |
+
steps = _check_int('steps', state.get('steps'), 0, 2**62)
|
| 887 |
+
last = state.get('last')
|
| 888 |
+
if last != -1:
|
| 889 |
+
last = _check_int('last', last, self.window, steps)
|
| 890 |
+
if steps >= self.window:
|
| 891 |
+
if last == -1 or steps - last >= self.recompute_every:
|
| 892 |
+
raise ValueError('connectivity observer state skipped a scheduled recompute')
|
| 893 |
+
if (last - self.window) % self.recompute_every:
|
| 894 |
+
raise ValueError('connectivity observer state recomputed off the schedule')
|
| 895 |
+
elif last != -1:
|
| 896 |
+
raise ValueError('connectivity observer state recomputed before the window filled')
|
| 897 |
+
if steps < self.history and np.any(buf[steps:] != 0.0):
|
| 898 |
+
raise ValueError('connectivity observer buffer has values beyond the observed steps')
|
| 899 |
+
metrics = self._validate_metrics(state.get('metrics'), steps, int(last))
|
| 900 |
+
self._buf, self._steps, self._last, self._metrics = buf, steps, int(last), metrics
|
| 901 |
+
|
| 902 |
+
|
| 903 |
+
# ====================================================================== lab experiment
|
| 904 |
+
_DEFAULTS: dict[str, Any] = {
|
| 905 |
+
'var_units': 8, 'var_steps': 3000, 'var_edge_prob': 0.15, 'var_spectral_radius': 0.8,
|
| 906 |
+
'ec_ridge': 1e-2, 'ec_null_draws': 199, 'ec_alpha': 0.05,
|
| 907 |
+
'chain_steps': 4000, 'chain_coupling': 0.8, 'pc_ridge': 1e-3,
|
| 908 |
+
'switch_units': 6, 'switch_block': 150, 'switch_blocks': 8, 'switch_corr': 0.8,
|
| 909 |
+
'dfc_window': 40, 'dfc_step': 8, 'dfc_k_max': 4, 'min_silhouette': 0.25,
|
| 910 |
+
'topologies': ('clustered', 'ring_lattice', 'hub_skewed', 'multi_region'), 'neurons': 32, 'nw_steps': 600,
|
| 911 |
+
'nw_burn_in': 50, 'mechanisms': (), 'nw_null_draws': 99, 'nw_pc_ridge': 0.1,
|
| 912 |
+
}
|
| 913 |
+
_QUICK: dict[str, Any] = {'var_steps': 1500, 'ec_null_draws': 99, 'chain_steps': 2000, 'switch_blocks': 6,
|
| 914 |
+
'topologies': ('clustered', 'ring_lattice', 'hub_skewed'), 'neurons': 24, 'nw_steps': 240,
|
| 915 |
+
'nw_burn_in': 40, 'nw_null_draws': 49}
|
| 916 |
+
|
| 917 |
+
|
| 918 |
+
def _validate_config(cfg: dict[str, Any]) -> dict[str, Any]:
|
| 919 |
+
from ..neuroweave.spec import MECHANISM_IDS, TOPOLOGIES
|
| 920 |
+
c = dict(cfg)
|
| 921 |
+
c['var_units'] = _check_int('var_units', c['var_units'], 3, 64)
|
| 922 |
+
c['var_steps'] = _check_int('var_steps', c['var_steps'], 100, 1_000_000)
|
| 923 |
+
c['var_edge_prob'] = _check_float('var_edge_prob', c['var_edge_prob'], 0.01, 0.9)
|
| 924 |
+
c['var_spectral_radius'] = _check_float('var_spectral_radius', c['var_spectral_radius'], 0.05, 0.99)
|
| 925 |
+
c['ec_ridge'] = _check_float('ec_ridge', c['ec_ridge'], 0.0, 1e3)
|
| 926 |
+
c['ec_null_draws'] = _check_int('ec_null_draws', c['ec_null_draws'], 2, 100_000)
|
| 927 |
+
c['ec_alpha'] = _check_float('ec_alpha', c['ec_alpha'], 1e-6, 0.5)
|
| 928 |
+
c['chain_steps'] = _check_int('chain_steps', c['chain_steps'], 100, 10_000_000)
|
| 929 |
+
c['chain_coupling'] = _check_float('chain_coupling', c['chain_coupling'], 0.1, 5.0)
|
| 930 |
+
c['pc_ridge'] = _check_float('pc_ridge', c['pc_ridge'], 0.0, 1.0)
|
| 931 |
+
c['switch_units'] = _check_int('switch_units', c['switch_units'], 4, 64)
|
| 932 |
+
c['switch_block'] = _check_int('switch_block', c['switch_block'], 20, 1_000_000)
|
| 933 |
+
c['switch_blocks'] = _check_int('switch_blocks', c['switch_blocks'], 4, 10_000)
|
| 934 |
+
c['switch_corr'] = _check_float('switch_corr', c['switch_corr'], 0.1, 0.95)
|
| 935 |
+
c['dfc_window'] = _check_int('dfc_window', c['dfc_window'], 8, c['switch_block'])
|
| 936 |
+
c['dfc_step'] = _check_int('dfc_step', c['dfc_step'], 1, c['dfc_window'])
|
| 937 |
+
c['dfc_k_max'] = _check_int('dfc_k_max', c['dfc_k_max'], 2, 8)
|
| 938 |
+
c['min_silhouette'] = _check_float('min_silhouette', c['min_silhouette'], 0.0, 1.0)
|
| 939 |
+
try:
|
| 940 |
+
topologies = tuple(c['topologies'])
|
| 941 |
+
mechanisms = tuple(c['mechanisms'])
|
| 942 |
+
except TypeError as exc:
|
| 943 |
+
raise ValueError('topologies and mechanisms must be sequences of names') from exc
|
| 944 |
+
if not topologies or len(set(topologies)) != len(topologies) or any(t not in TOPOLOGIES for t in topologies):
|
| 945 |
+
raise ValueError(f'topologies must be distinct names from {TOPOLOGIES}')
|
| 946 |
+
if any(m not in MECHANISM_IDS for m in mechanisms):
|
| 947 |
+
raise ValueError('mechanisms must be NEUROWEAVE mechanism ids')
|
| 948 |
+
c['topologies'], c['mechanisms'] = list(topologies), list(mechanisms)
|
| 949 |
+
c['neurons'] = _check_int('neurons', c['neurons'], 8, 512)
|
| 950 |
+
c['nw_steps'] = _check_int('nw_steps', c['nw_steps'], 40, 100_000)
|
| 951 |
+
c['nw_burn_in'] = _check_int('nw_burn_in', c['nw_burn_in'], 0, c['nw_steps'] - 30)
|
| 952 |
+
if c['nw_steps'] - c['nw_burn_in'] < c['dfc_window']:
|
| 953 |
+
raise ValueError('nw_steps - nw_burn_in must be at least dfc_window (the NEUROWEAVE dFC needs one window)')
|
| 954 |
+
c['nw_null_draws'] = _check_int('nw_null_draws', c['nw_null_draws'], 2, 100_000)
|
| 955 |
+
c['nw_pc_ridge'] = _check_float('nw_pc_ridge', c['nw_pc_ridge'], 1e-6, 10.0)
|
| 956 |
+
return c
|
| 957 |
+
|
| 958 |
+
|
| 959 |
+
def _simulate_sparse_var(rng: np.random.Generator, n: int, steps: int, edge_prob: float,
|
| 960 |
+
radius: float) -> tuple[np.ndarray, np.ndarray]:
|
| 961 |
+
off = ~np.eye(n, dtype=bool)
|
| 962 |
+
support = (rng.random((n, n)) < edge_prob) & off
|
| 963 |
+
if not support.any():
|
| 964 |
+
i, j = np.argwhere(off)[int(rng.integers(n * (n - 1)))]
|
| 965 |
+
support[i, j] = True
|
| 966 |
+
A = np.zeros((n, n))
|
| 967 |
+
k = int(support.sum())
|
| 968 |
+
A[support] = rng.uniform(0.25, 0.5, k) * rng.choice(np.array([-1.0, 1.0]), k)
|
| 969 |
+
A[np.diag_indices(n)] = rng.uniform(0.2, 0.5, n)
|
| 970 |
+
rho = float(np.max(np.abs(np.linalg.eigvals(A))))
|
| 971 |
+
if rho > radius:
|
| 972 |
+
A *= radius / rho
|
| 973 |
+
burn = 100
|
| 974 |
+
noise = rng.standard_normal((steps + burn, n))
|
| 975 |
+
X = np.empty((steps + burn, n))
|
| 976 |
+
x = np.zeros(n)
|
| 977 |
+
for t in range(steps + burn):
|
| 978 |
+
x = A @ x + noise[t]
|
| 979 |
+
X[t] = x
|
| 980 |
+
return A, X[burn:]
|
| 981 |
+
|
| 982 |
+
|
| 983 |
+
def _validate_var(seed: int, c: Mapping[str, Any]) -> dict[str, Any]:
|
| 984 |
+
rng = np.random.default_rng(seed + _VAR_OFFSET)
|
| 985 |
+
A, X = _simulate_sparse_var(rng, c['var_units'], c['var_steps'], c['var_edge_prob'], c['var_spectral_radius'])
|
| 986 |
+
ec = effective_connectivity(X, ridge=c['ec_ridge'], null_draws=c['ec_null_draws'], alpha=c['ec_alpha'],
|
| 987 |
+
seed=seed, standardize=False)
|
| 988 |
+
n = A.shape[0]
|
| 989 |
+
off = ~np.eye(n, dtype=bool)
|
| 990 |
+
truth = (A != 0.0)[off]
|
| 991 |
+
est = ec['A'][off]
|
| 992 |
+
mask = ec['mask'][off]
|
| 993 |
+
tp, fp = int((mask & truth).sum()), int((mask & ~truth).sum())
|
| 994 |
+
return {'seed': seed, 'units': n, 'steps': c['var_steps'], 'true_edges': int(truth.sum()),
|
| 995 |
+
'spectral_radius': float(np.max(np.abs(np.linalg.eigvals(A)))),
|
| 996 |
+
'support_auroc': auroc(np.abs(est), truth),
|
| 997 |
+
'sign_accuracy': float((np.sign(est[truth]) == np.sign(A[off][truth])).mean()),
|
| 998 |
+
'max_abs_coefficient_error': float(np.max(np.abs(ec['A'] - A))),
|
| 999 |
+
'mask_true_positives': tp, 'mask_false_positives': fp,
|
| 1000 |
+
'mask_precision': float(tp / (tp + fp)) if tp + fp else None,
|
| 1001 |
+
'mask_recall': float(tp / max(1, int(truth.sum()))), 'ec_density': ec['density'], 'block': ec['block']}
|
| 1002 |
+
|
| 1003 |
+
|
| 1004 |
+
def _validate_chain(seed: int, c: Mapping[str, Any]) -> dict[str, Any]:
|
| 1005 |
+
rng = np.random.default_rng(seed + _CHAIN_OFFSET)
|
| 1006 |
+
T, a = c['chain_steps'], c['chain_coupling']
|
| 1007 |
+
x = rng.standard_normal(T)
|
| 1008 |
+
y = a * x + rng.standard_normal(T)
|
| 1009 |
+
z = a * y + rng.standard_normal(T)
|
| 1010 |
+
X = np.column_stack([x, y, z])
|
| 1011 |
+
fc = pearson_fc(X)
|
| 1012 |
+
pc = partial_correlation(X, ridge=c['pc_ridge'])
|
| 1013 |
+
exact = {'xy': a / (1.0 + a * a), 'yz': a / math.sqrt(1.0 + a * a), 'xz': 0.0,
|
| 1014 |
+
'fc_xz': a * a / math.sqrt(a * a * (a * a + 1.0) + 1.0)}
|
| 1015 |
+
tol = 4.0 / math.sqrt(T)
|
| 1016 |
+
est = {'xy': float(pc[0, 1]), 'yz': float(pc[1, 2]), 'xz': float(pc[0, 2])}
|
| 1017 |
+
return {'seed': seed, 'steps': T, 'tolerance': tol, 'partial': est, 'exact_partial': exact,
|
| 1018 |
+
'fc_xz': float(fc[0, 2]), 'spearman_xz': float(spearman_fc(X)[0, 2]),
|
| 1019 |
+
'max_partial_error': float(max(abs(est[k] - exact[k]) for k in ('xy', 'yz', 'xz')))}
|
| 1020 |
+
|
| 1021 |
+
|
| 1022 |
+
def _two_state_cov(n: int, r: float) -> tuple[np.ndarray, np.ndarray]:
|
| 1023 |
+
h = n // 2
|
| 1024 |
+
A, B = np.eye(n), np.eye(n)
|
| 1025 |
+
A[:h, :h] = r
|
| 1026 |
+
B[h:, h:] = r
|
| 1027 |
+
np.fill_diagonal(A, 1.0)
|
| 1028 |
+
np.fill_diagonal(B, 1.0)
|
| 1029 |
+
return A, B
|
| 1030 |
+
|
| 1031 |
+
|
| 1032 |
+
def _validate_switching(seed: int, c: Mapping[str, Any]) -> dict[str, Any]:
|
| 1033 |
+
rng = np.random.default_rng(seed + _SWITCH_OFFSET)
|
| 1034 |
+
n, L, nb = c['switch_units'], c['switch_block'], c['switch_blocks']
|
| 1035 |
+
CA, CB = _two_state_cov(n, c['switch_corr'])
|
| 1036 |
+
chol = [np.linalg.cholesky(CA), np.linalg.cholesky(CB)]
|
| 1037 |
+
X = np.vstack([rng.standard_normal((L, n)) @ chol[b % 2].T for b in range(nb)])
|
| 1038 |
+
w, step = c['dfc_window'], c['dfc_step']
|
| 1039 |
+
kw = dict(window=w, step=step, k_max=c['dfc_k_max'], min_silhouette=c['min_silhouette'], seed=seed)
|
| 1040 |
+
d = dynamic_fc_states(X, **kw)
|
| 1041 |
+
starts = d['starts']
|
| 1042 |
+
pure = (starts // L) == ((starts + w - 1) // L)
|
| 1043 |
+
truth = (starts // L) % 2
|
| 1044 |
+
accuracy = None
|
| 1045 |
+
if d['n_states'] == 2 and pure.any():
|
| 1046 |
+
lab = d['labels'][pure]
|
| 1047 |
+
accuracy = float(max((lab == truth[pure]).mean(), (lab != truth[pure]).mean()))
|
| 1048 |
+
rng2 = np.random.default_rng(seed + _STATIONARY_OFFSET)
|
| 1049 |
+
Xs = rng2.standard_normal((L * nb, n)) @ np.linalg.cholesky(0.5 * (CA + CB)).T
|
| 1050 |
+
ds = dynamic_fc_states(Xs, **kw)
|
| 1051 |
+
return {'seed': seed, 'units': n, 'block': L, 'blocks': nb, 'windows': d['windows'], 'n_states': d['n_states'],
|
| 1052 |
+
'silhouette': d['silhouette'], 'pure_windows': int(pure.sum()), 'pure_window_accuracy': accuracy,
|
| 1053 |
+
'mean_dwell_samples': d['mean_dwell_samples'], 'expected_dwell_samples_upper': float(L),
|
| 1054 |
+
'stationary_control_states': ds['n_states'], 'stationary_control_silhouette': ds['silhouette']}
|
| 1055 |
+
|
| 1056 |
+
|
| 1057 |
+
def _neuroweave_run(topology: str, seed: int, c: Mapping[str, Any]) -> dict[str, Any]:
|
| 1058 |
+
from ..neuroweave.engine import NeuroWeaveEngine
|
| 1059 |
+
from ..neuroweave.experiments import engine_topology, make_spec
|
| 1060 |
+
from ..neuroweave.tasks import make_stream
|
| 1061 |
+
from ..neuroweave.topology import topology_metrics
|
| 1062 |
+
steps = c['nw_steps']
|
| 1063 |
+
engine = NeuroWeaveEngine(make_spec(c['mechanisms'], seed=seed, neurons=c['neurons'], topology=topology,
|
| 1064 |
+
steps=steps))
|
| 1065 |
+
stream = make_stream(seed, steps)
|
| 1066 |
+
outs = []
|
| 1067 |
+
for i in range(steps): # frozen dynamics: the structure that generates the activity stays fixed
|
| 1068 |
+
outs.append(np.array(engine.step(stream.inputs[i], stream.sensory[i], reward=0.0, learn=False)['output']))
|
| 1069 |
+
X = np.stack(outs)[c['nw_burn_in']:]
|
| 1070 |
+
topo = engine_topology(engine)
|
| 1071 |
+
n = int(topo.n)
|
| 1072 |
+
W = structural_matrix(n, topo.src, topo.dst, topo.weight, absolute=False)
|
| 1073 |
+
S = np.abs(W) + np.abs(W).T
|
| 1074 |
+
fc = pearson_fc(X)
|
| 1075 |
+
pc = partial_correlation(X, ridge=c['nw_pc_ridge'])
|
| 1076 |
+
ok = np.diag(fc) > 0.5
|
| 1077 |
+
iu = np.triu_indices(n, 1)
|
| 1078 |
+
both = ok[iu[0]] & ok[iu[1]]
|
| 1079 |
+
coupling = structure_function_coupling(S, fc)
|
| 1080 |
+
ec = effective_connectivity(X, ridge=c['ec_ridge'], null_draws=c['nw_null_draws'], alpha=c['ec_alpha'],
|
| 1081 |
+
seed=seed)
|
| 1082 |
+
off = ~np.eye(n, dtype=bool)
|
| 1083 |
+
present = (W.T != 0.0) # present[target, source]: a synapse source -> target exists
|
| 1084 |
+
sig = ec['mask'] & off
|
| 1085 |
+
sign_ok = np.sign(ec['A'][sig & present]) == np.sign(W.T[sig & present])
|
| 1086 |
+
d = dynamic_fc_states(X, window=c['dfc_window'], step=c['dfc_step'], k_max=c['dfc_k_max'],
|
| 1087 |
+
min_silhouette=c['min_silhouette'], seed=seed)
|
| 1088 |
+
com = fc_communities(fc[np.ix_(ok, ok)]) if ok.sum() >= 2 else {'modularity': 0.0, 'communities': 1}
|
| 1089 |
+
tm = topology_metrics(topo)
|
| 1090 |
+
return {
|
| 1091 |
+
'seed': seed, 'neurons': n, 'samples': int(X.shape[0]), 'synapses': int(topo.edges),
|
| 1092 |
+
'constant_units': int((~ok).sum()),
|
| 1093 |
+
'structure': {k: tm[k] for k in ('density', 'clustering_mean', 'modularity', 'mean_shortest_path',
|
| 1094 |
+
'global_efficiency', 'inter_region_edge_fraction')},
|
| 1095 |
+
'mean_abs_fc': float(np.abs(fc[iu][both]).mean()) if both.any() else None,
|
| 1096 |
+
'mean_abs_partial': float(np.abs(pc[iu][both]).mean()) if both.any() else None,
|
| 1097 |
+
'fc_modularity_proxy': float(com['modularity']), 'fc_communities': int(com['communities']),
|
| 1098 |
+
'coupling': coupling,
|
| 1099 |
+
'ec': {'density': ec['density'], 'significant': ec['significant'], 'block': ec['block'],
|
| 1100 |
+
'structure_auroc': auroc(np.abs(ec['A'][off]), present[off]),
|
| 1101 |
+
'significant_on_synapses_fraction': float((sig & present).sum() / sig.sum()) if sig.any() else None,
|
| 1102 |
+
'sign_agreement_on_synapses': float(sign_ok.mean()) if sign_ok.size else None},
|
| 1103 |
+
'dfc': {'n_states': d['n_states'], 'best_silhouette': d['best_silhouette'], 'windows': d['windows'],
|
| 1104 |
+
'mean_dwell_samples': d['mean_dwell_samples']},
|
| 1105 |
+
}
|
| 1106 |
+
|
| 1107 |
+
|
| 1108 |
+
def _finite_tree(obj: Any) -> bool:
|
| 1109 |
+
if isinstance(obj, Mapping):
|
| 1110 |
+
return all(_finite_tree(v) for v in obj.values())
|
| 1111 |
+
if isinstance(obj, (list, tuple)):
|
| 1112 |
+
return all(_finite_tree(v) for v in obj)
|
| 1113 |
+
if isinstance(obj, (float, np.floating)):
|
| 1114 |
+
return math.isfinite(float(obj))
|
| 1115 |
+
return True
|
| 1116 |
+
|
| 1117 |
+
|
| 1118 |
+
def _mean_of(values: Sequence[Any]) -> float | None:
|
| 1119 |
+
v = [float(x) for x in values if x is not None]
|
| 1120 |
+
return float(np.mean(v)) if v else None
|
| 1121 |
+
|
| 1122 |
+
|
| 1123 |
+
def run_experiment(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]:
|
| 1124 |
+
"""Known-answer validation of the connectivity estimators, then a descriptive NEUROWEAVE report.
|
| 1125 |
+
|
| 1126 |
+
Validation (per seed, checks must hold for every seed): (1) a sparse stable VAR(1) with known ``A``: EC support
|
| 1127 |
+
AUROC > 0.9, sign accuracy on true edges >= 0.9 and pooled mask precision >= 0.8; (2) a Gaussian chain
|
| 1128 |
+
X -> Y -> Z: partial correlations within ``4 / sqrt(T)`` of their exact values (X-Z exactly 0) while
|
| 1129 |
+
FC(X, Z) stays clearly non-zero; (3) a two-state switching process: dFC finds 2 states with pure-window
|
| 1130 |
+
accuracy >= 0.9, and a stationary control with the averaged covariance gives 1 state. Then (4) NEUROWEAVE: for
|
| 1131 |
+
each topology the frozen engine runs on the task stream and the module reports structure-function coupling,
|
| 1132 |
+
communicability coupling, EC/structure agreement and dFC/FC summaries. Part (4) is descriptive: no verdict is
|
| 1133 |
+
drawn from it beyond finiteness. ``kind='validation'``, ``verdict`` in ``('pass', 'fail')``."""
|
| 1134 |
+
from . import harness
|
| 1135 |
+
if type(quick) is not bool:
|
| 1136 |
+
raise ValueError('quick must be a boolean')
|
| 1137 |
+
seeds = _check_seeds(seeds)
|
| 1138 |
+
cfg = dict(_DEFAULTS)
|
| 1139 |
+
if quick:
|
| 1140 |
+
cfg.update(_QUICK)
|
| 1141 |
+
unknown = sorted(set(overrides) - set(cfg))
|
| 1142 |
+
if unknown:
|
| 1143 |
+
raise ValueError(f'unknown run_experiment overrides: {unknown}')
|
| 1144 |
+
cfg.update(overrides)
|
| 1145 |
+
c = _validate_config(cfg)
|
| 1146 |
+
t0 = time.perf_counter()
|
| 1147 |
+
var = [_validate_var(s, c) for s in seeds]
|
| 1148 |
+
chain = [_validate_chain(s, c) for s in seeds]
|
| 1149 |
+
switch = [_validate_switching(s, c) for s in seeds]
|
| 1150 |
+
t_val = time.perf_counter() - t0
|
| 1151 |
+
t1 = time.perf_counter()
|
| 1152 |
+
nw: dict[str, Any] = {}
|
| 1153 |
+
for topo in c['topologies']:
|
| 1154 |
+
runs = [_neuroweave_run(topo, s, c) for s in seeds]
|
| 1155 |
+
nw[topo] = {'per_seed': runs, 'mean': {
|
| 1156 |
+
'sc_fc_spearman': _mean_of([r['coupling']['sc_fc_spearman'] for r in runs]),
|
| 1157 |
+
'sc_fc_spearman_connected': _mean_of([r['coupling']['sc_fc_spearman_connected'] for r in runs]),
|
| 1158 |
+
'communicability_fc_spearman': _mean_of([r['coupling']['communicability_fc_spearman'] for r in runs]),
|
| 1159 |
+
'communicability_absfc_spearman': _mean_of([r['coupling']['communicability_absfc_spearman'] for r in runs]),
|
| 1160 |
+
'mean_abs_fc': _mean_of([r['mean_abs_fc'] for r in runs]),
|
| 1161 |
+
'ec_structure_auroc': _mean_of([r['ec']['structure_auroc'] for r in runs]),
|
| 1162 |
+
'ec_density': _mean_of([r['ec']['density'] for r in runs]),
|
| 1163 |
+
'dfc_states': _mean_of([r['dfc']['n_states'] for r in runs])}}
|
| 1164 |
+
t_nw = time.perf_counter() - t1
|
| 1165 |
+
tp = sum(v['mask_true_positives'] for v in var)
|
| 1166 |
+
fp = sum(v['mask_false_positives'] for v in var)
|
| 1167 |
+
pooled_precision = tp / (tp + fp) if tp + fp else 0.0
|
| 1168 |
+
checks = {
|
| 1169 |
+
'var_support_auroc_above_0.9': all(v['support_auroc'] is not None and v['support_auroc'] > 0.9 for v in var),
|
| 1170 |
+
'var_sign_accuracy_at_least_0.9': all(v['sign_accuracy'] >= 0.9 for v in var),
|
| 1171 |
+
'var_mask_pooled_precision_at_least_0.8': bool(pooled_precision >= 0.8),
|
| 1172 |
+
'chain_partials_match_exact_values': all(ch['max_partial_error'] <= ch['tolerance'] for ch in chain),
|
| 1173 |
+
'chain_fc_xz_clearly_nonzero': all(abs(ch['fc_xz']) > 0.3 for ch in chain),
|
| 1174 |
+
'switching_two_states_recovered': all(s['n_states'] == 2 for s in switch),
|
| 1175 |
+
'switching_pure_window_accuracy_at_least_0.9': all(
|
| 1176 |
+
s['pure_window_accuracy'] is not None and s['pure_window_accuracy'] >= 0.9 for s in switch),
|
| 1177 |
+
'stationary_control_single_state': all(s['stationary_control_states'] == 1 for s in switch),
|
| 1178 |
+
'neuroweave_values_finite': _finite_tree(nw),
|
| 1179 |
+
}
|
| 1180 |
+
receipt = harness.base_receipt(MODULE_ID, 'validation', {**c, 'quick': quick, 'seeds': list(seeds)})
|
| 1181 |
+
receipt['validations'] = {'var_recovery': var, 'var_pooled_mask_precision': pooled_precision,
|
| 1182 |
+
'chain_partial_correlation': chain, 'dfc_switching': switch}
|
| 1183 |
+
receipt['neuroweave'] = {'per_topology': nw, 'mechanisms': list(c['mechanisms']),
|
| 1184 |
+
'note': 'descriptive only: values are reported, no verdict is drawn from them'}
|
| 1185 |
+
receipt['checks'] = checks
|
| 1186 |
+
receipt['verdict'] = 'pass' if all(checks.values()) else 'fail'
|
| 1187 |
+
receipt['verdict_basis'] = 'all_known_answer_checks' if receipt['verdict'] == 'pass' else 'failed_checks: ' + ', '.join(
|
| 1188 |
+
k for k, v in checks.items() if not v)
|
| 1189 |
+
nets = len(c['topologies']) * len(seeds)
|
| 1190 |
+
receipt['estimated_cost'] = {
|
| 1191 |
+
'engine_steps': int(nets * c['nw_steps']),
|
| 1192 |
+
'ec_null_ridge_solves': int(len(seeds) * c['ec_null_draws'] * c['var_units']
|
| 1193 |
+
+ nets * c['nw_null_draws'] * c['neurons']),
|
| 1194 |
+
'fc_windows': int(sum(s['windows'] for s in switch) * 2)}
|
| 1195 |
+
receipt['measured_wallclock_s'] = {'validation': t_val, 'neuroweave': t_nw, 'total': time.perf_counter() - t0}
|
| 1196 |
+
receipt['notes'] = (
|
| 1197 |
+
'Synthetic validation of FC, partial correlation, dFC states and ridge VAR(1) EC on processes with known '
|
| 1198 |
+
'answers, then a descriptive structure-function report on frozen NEUROWEAVE brains (the synapse table '
|
| 1199 |
+
'that generated the activity). EC is lagged predictive influence (Granger-style), not an interventional '
|
| 1200 |
+
'effect; the dFC state count uses a silhouette heuristic (0.25 by default); the FC modularity is a '
|
| 1201 |
+
'leading-eigenvector proxy. Nothing here is imaging data or evidence of biological fidelity.')
|
| 1202 |
+
return harness.seal(receipt)
|
| 1203 |
+
|
| 1204 |
+
|
| 1205 |
+
EXPERIMENTS: dict[str, Callable[..., dict[str, Any]]] = {MODULE_ID: run_experiment}
|
synapse/frontier/continuum_memory.py
ADDED
|
@@ -0,0 +1,767 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Continuum memory: linear associative memories updated at geometrically spaced periods.
|
| 2 |
+
|
| 3 |
+
Inspired by the *continuum memory system* (CMS) of Nested Learning (Behrouz, Razaviyayn, Zhong & Mirrokni,
|
| 4 |
+
"Nested Learning: The Illusion of Deep Learning Architectures", NeurIPS 2025; arXiv:2512.24695, Dec 2025) and by
|
| 5 |
+
the neural long-term memory of Titans (Behrouz, Zhong & Mirrokni, "Titans: Learning to Memorize at Test Time",
|
| 6 |
+
NeurIPS 2025; arXiv:2501.00663, Dec 2024). It is a small synthetic abstraction, not a reproduction of either paper:
|
| 7 |
+
linear memories instead of MLP blocks, fixed instead of learned data-dependent gates, no attention and no language
|
| 8 |
+
modelling.
|
| 9 |
+
|
| 10 |
+
Model
|
| 11 |
+
-----
|
| 12 |
+
``levels`` linear associative memories ``M_l`` (``value_dim x key_dim``) form an *independent (head-wise)* CMS
|
| 13 |
+
(Nested Learning Eq. 74) with a sum aggregation. Level ``l`` reads its own key ``k_l`` (one key per level, i.e.
|
| 14 |
+
a level-specific key projection, or one key shared by every level)::
|
| 15 |
+
|
| 16 |
+
read: r_l = M_l k_l (``read`` returns every r_l) y = sum_l r_l (``predict``)
|
| 17 |
+
loss: L_t = ||y_t - v_t||^2 grad_l = dL_t/dM_l = 2 (y_t - v_t) k_{l,t}^T
|
| 18 |
+
|
| 19 |
+
Level ``l`` has period ``P_l = base_period * 2**l``. It accumulates ``grad_l`` over its chunk of ``P_l`` writes,
|
| 20 |
+
each evaluated with the memories as they are at that write, and applies the chunk gradient ``G_l`` only when the
|
| 21 |
+
chunk closes (Nested Learning Eq. 71). ``G_l`` is the chunk *sum* (Eq. 71 with a constant learning rate) or, with
|
| 22 |
+
``chunk_reduce='mean'``, the chunk mean (Eq. 71 with ``lr / P_l``). The update uses Titans' surprise momentum and
|
| 23 |
+
forgetting gate (Titans Eqs. 10 and 13) with constant ``momentum`` (Titans' ``eta``) and ``lr`` (``theta``)::
|
| 24 |
+
|
| 25 |
+
S_l <- momentum * S_l - lr * G_l
|
| 26 |
+
M_l <- (1 - alpha_l) * M_l + S_l
|
| 27 |
+
alpha_l = min(max_forget, forget + surprise_forget * mean_chunk_surprise)
|
| 28 |
+
|
| 29 |
+
Titans learns ``alpha_t`` as a function of the input; here it is a fixed number, optionally raised by this module's
|
| 30 |
+
own bounded surprise score ``s_t = e_t / (e_t + ||v_t||^2)``, ``e_t = ||y_t - v_t||^2`` (0 for a perfect read, 1/2
|
| 31 |
+
for an empty memory, towards 1 for a confidently wrong read; Titans' "momentary surprise" is the gradient term
|
| 32 |
+
itself). ``M`` and ``S`` are clipped to ``[-bound, bound]`` and every array has a fixed shape, so the state stays
|
| 33 |
+
finite and bounded.
|
| 34 |
+
|
| 35 |
+
Engine extension
|
| 36 |
+
----------------
|
| 37 |
+
``ContinuumMemoryExtension`` stores the predictive association *previous fused task+sensory context -> current
|
| 38 |
+
sensory frame* (only when ``ctx['learn']``) and exposes a fixed random projection of the per-level reads for the
|
| 39 |
+
current context (a multi-timescale forecast of the next frame) as readout features. It never changes the drive.
|
| 40 |
+
|
| 41 |
+
Benchmark
|
| 42 |
+
---------
|
| 43 |
+
``run_recall_benchmark`` streams key -> value associations: some recur after short gaps, some after long gaps,
|
| 44 |
+
and one-off associations fill the remaining steps as interference. It compares the CMS with a single-level
|
| 45 |
+
Titans-style memory holding the same number of entries (one ``value_dim x (levels * key_dim)`` memory reading the
|
| 46 |
+
concatenated key) and with a no-memory predictor (running mean of the values), with hyperparameters tuned per
|
| 47 |
+
arm on separate tuning seeds.
|
| 48 |
+
"""
|
| 49 |
+
from __future__ import annotations
|
| 50 |
+
|
| 51 |
+
import copy
|
| 52 |
+
import itertools
|
| 53 |
+
import math
|
| 54 |
+
import time
|
| 55 |
+
from typing import Any, Callable, Mapping, Sequence
|
| 56 |
+
|
| 57 |
+
import numpy as np
|
| 58 |
+
|
| 59 |
+
from ..neuroweave.spec import SENSORY_DIM, TASK_INPUT_DIM
|
| 60 |
+
from .extension import EngineExtension
|
| 61 |
+
|
| 62 |
+
__all__ = ['MODULE_ID', 'RECALL_ID', 'SOURCE', 'EXPERIMENTS', 'CHUNK_REDUCTIONS', 'KIND_CODES', 'ContinuumMemory',
|
| 63 |
+
'ContinuumMemoryExtension', 'make_recall_stream', 'run_recall_benchmark', 'run_experiment',
|
| 64 |
+
'RECALL_DEFAULTS', 'RECALL_QUICK']
|
| 65 |
+
|
| 66 |
+
MODULE_ID = 'continuum_memory'
|
| 67 |
+
RECALL_ID = 'continuum_memory_recall'
|
| 68 |
+
SOURCE = ('Behrouz, Razaviyayn, Zhong & Mirrokni, "Nested Learning: The Illusion of Deep Learning Architectures", '
|
| 69 |
+
'NeurIPS 2025, arXiv:2512.24695 (continuum memory system); Behrouz, Zhong & Mirrokni, "Titans: Learning to '
|
| 70 |
+
'Memorize at Test Time", NeurIPS 2025, arXiv:2501.00663 (surprise momentum and forgetting gate)')
|
| 71 |
+
CONTEXT_DIM = TASK_INPUT_DIM + SENSORY_DIM
|
| 72 |
+
CHUNK_REDUCTIONS = ('sum', 'mean')
|
| 73 |
+
KIND_CODES = {'fresh': 0, 'first': 1, 'short': 2, 'long': 3, 'remap': 4}
|
| 74 |
+
_KEY_OFFSET = 51_407
|
| 75 |
+
_FEATURE_OFFSET = 51_419
|
| 76 |
+
_STREAM_OFFSET = 51_431
|
| 77 |
+
_MAX_ABS_INPUT = 1e6
|
| 78 |
+
# Far above any accumulator reachable from valid writes (inputs <= 1e6, |M| <= bound <= 1e6, chunks <= 2**23 writes
|
| 79 |
+
# give |acc| < 1e30) and far below float64 overflow, so an imported accumulator can never turn the state into inf/NaN.
|
| 80 |
+
_MAX_ACCUMULATOR = 1e100
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
# ====================================================================== validation helpers
|
| 84 |
+
def _check_int(name: str, value: Any, low: int, high: int) -> int:
|
| 85 |
+
if type(value) is not int or not low <= value <= high:
|
| 86 |
+
raise ValueError(f'{name} must be an int in [{low}, {high}]')
|
| 87 |
+
return value
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _check_float(name: str, value: Any, low: float, high: float, *, high_open: bool = False,
|
| 91 |
+
low_open: bool = False) -> float:
|
| 92 |
+
if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
|
| 93 |
+
raise ValueError(f'{name} must be a number')
|
| 94 |
+
v = float(value)
|
| 95 |
+
ok = math.isfinite(v) and (v > low if low_open else v >= low) and (v < high if high_open else v <= high)
|
| 96 |
+
if not ok:
|
| 97 |
+
raise ValueError(f'{name} must be in {"(" if low_open else "["}{low}, {high}{")" if high_open else "]"}')
|
| 98 |
+
return v
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _finite(name: str, value: Any) -> np.ndarray:
|
| 102 |
+
try:
|
| 103 |
+
arr = np.asarray(value, dtype=np.float64)
|
| 104 |
+
except (TypeError, ValueError) as exc:
|
| 105 |
+
raise ValueError(f'{name} must be numeric') from exc
|
| 106 |
+
if not np.all(np.isfinite(arr)) or float(np.max(np.abs(arr), initial=0.0)) > _MAX_ABS_INPUT:
|
| 107 |
+
raise ValueError(f'{name} must be finite with magnitude <= {_MAX_ABS_INPUT:g}')
|
| 108 |
+
return arr
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _vector(name: str, value: Any, size: int) -> np.ndarray:
|
| 112 |
+
arr = _finite(name, value)
|
| 113 |
+
if arr.shape != (size,):
|
| 114 |
+
raise ValueError(f'{name} must have shape ({size},), got {arr.shape}')
|
| 115 |
+
return arr
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _array(name: str, value: Any, shape: tuple[int, ...]) -> np.ndarray:
|
| 119 |
+
try:
|
| 120 |
+
arr = np.asarray(value, dtype=np.float64)
|
| 121 |
+
except (TypeError, ValueError) as exc:
|
| 122 |
+
raise ValueError(f'{name} must be a numeric array') from exc
|
| 123 |
+
if arr.shape != shape or not np.all(np.isfinite(arr)):
|
| 124 |
+
raise ValueError(f'{name} must be a finite array of shape {shape}')
|
| 125 |
+
return arr
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _check_seeds(name: str, seeds: Any) -> tuple[int, ...]:
|
| 129 |
+
try:
|
| 130 |
+
out = tuple(seeds)
|
| 131 |
+
except TypeError as exc:
|
| 132 |
+
raise ValueError(f'{name} must be a sequence of ints') from exc
|
| 133 |
+
if not out or len(set(out)) != len(out):
|
| 134 |
+
raise ValueError(f'{name} must be non-empty and unique')
|
| 135 |
+
for s in out:
|
| 136 |
+
_check_int(f'{name} entry', s, 0, 2**31 - 1)
|
| 137 |
+
return out
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _check_pair(name: str, value: Any, low: int, high: int) -> tuple[int, int]:
|
| 141 |
+
try:
|
| 142 |
+
lo, hi = value
|
| 143 |
+
except (TypeError, ValueError) as exc:
|
| 144 |
+
raise ValueError(f'{name} must be a (low, high) pair of ints') from exc
|
| 145 |
+
_check_int(f'{name}[0]', lo, low, high)
|
| 146 |
+
_check_int(f'{name}[1]', hi, lo, high)
|
| 147 |
+
return int(lo), int(hi)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _check_grid(name: str, value: Any, low: float, high: float, *, high_open: bool = False) -> tuple[float, ...]:
|
| 151 |
+
try:
|
| 152 |
+
out = tuple(value)
|
| 153 |
+
except TypeError as exc:
|
| 154 |
+
raise ValueError(f'{name} must be a sequence of numbers') from exc
|
| 155 |
+
if not 1 <= len(out) <= 16:
|
| 156 |
+
raise ValueError(f'{name} must hold 1..16 values')
|
| 157 |
+
return tuple(_check_float(f'{name} entry', v, low, high, high_open=high_open) for v in out)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _grid_edges(chosen: Mapping[str, float], grids: Mapping[str, Sequence[float]],
|
| 161 |
+
natural: Mapping[str, Sequence[float]] | None = None) -> list[str]:
|
| 162 |
+
"""Tuned hyperparameters (grids with at least two distinct values) whose chosen value is the smallest or largest
|
| 163 |
+
grid value, so the best setting may lie outside the grid. A value in ``natural[name]`` (a natural bound such as
|
| 164 |
+
momentum 0 = no momentum) is not counted as an edge."""
|
| 165 |
+
natural = natural or {}
|
| 166 |
+
out = []
|
| 167 |
+
for name, grid in grids.items():
|
| 168 |
+
values = sorted({float(v) for v in grid})
|
| 169 |
+
value = float(chosen[name])
|
| 170 |
+
if len(values) >= 2 and value in (values[0], values[-1]) and value not in {float(v) for v in natural.get(name, ())}:
|
| 171 |
+
out.append(name)
|
| 172 |
+
return out
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
# ====================================================================== memory
|
| 176 |
+
class ContinuumMemory:
|
| 177 |
+
"""``levels`` linear associative memories with periods ``base_period * 2**l`` (see the module docstring).
|
| 178 |
+
|
| 179 |
+
Keys may be one ``(key_dim,)`` vector shared by every level or a ``(levels, key_dim)`` array with one key
|
| 180 |
+
per level. With a shared key and ``chunk_reduce='sum'`` several levels can apply the same error in one
|
| 181 |
+
write, so a smaller ``lr`` (about ``1 / levels`` of the per-level-key value) keeps the joint update stable;
|
| 182 |
+
the ``bound`` clip keeps the state finite either way. The memory has no randomness."""
|
| 183 |
+
|
| 184 |
+
def __init__(self, key_dim: int, value_dim: int, levels: int = 4, base_period: int = 1, lr: float = 0.5,
|
| 185 |
+
momentum: float = 0.0, forget: float = 0.01, *, surprise_forget: float = 0.0,
|
| 186 |
+
max_forget: float = 0.5, chunk_reduce: str = 'sum', bound: float = 100.0) -> None:
|
| 187 |
+
self.key_dim = _check_int('key_dim', key_dim, 1, 4096)
|
| 188 |
+
self.value_dim = _check_int('value_dim', value_dim, 1, 4096)
|
| 189 |
+
self.levels = _check_int('levels', levels, 1, 12)
|
| 190 |
+
self.base_period = _check_int('base_period', base_period, 1, 4096)
|
| 191 |
+
if self.key_dim * self.value_dim * self.levels > 4_000_000:
|
| 192 |
+
raise ValueError('levels * key_dim * value_dim must be <= 4,000,000')
|
| 193 |
+
self.lr = _check_float('lr', lr, 0.0, 10.0)
|
| 194 |
+
self.momentum = _check_float('momentum', momentum, 0.0, 1.0, high_open=True)
|
| 195 |
+
self.forget = _check_float('forget', forget, 0.0, 1.0, high_open=True)
|
| 196 |
+
self.surprise_forget = _check_float('surprise_forget', surprise_forget, 0.0, 1.0)
|
| 197 |
+
self.max_forget = _check_float('max_forget', max_forget, 0.0, 1.0, high_open=True)
|
| 198 |
+
if self.max_forget < self.forget:
|
| 199 |
+
raise ValueError('max_forget must be >= forget')
|
| 200 |
+
if chunk_reduce not in CHUNK_REDUCTIONS:
|
| 201 |
+
raise ValueError(f'chunk_reduce must be one of {CHUNK_REDUCTIONS}')
|
| 202 |
+
self.chunk_reduce = chunk_reduce
|
| 203 |
+
self.bound = _check_float('bound', bound, 0.0, 1e6, low_open=True)
|
| 204 |
+
self.periods: tuple[int, ...] = tuple(self.base_period * 2 ** level for level in range(self.levels))
|
| 205 |
+
self.reset()
|
| 206 |
+
|
| 207 |
+
# ------------------------------------------------------------------ state
|
| 208 |
+
def reset(self) -> None:
|
| 209 |
+
"""Empty memories, momentum and chunk accumulators (a fresh memory)."""
|
| 210 |
+
shape = (self.levels, self.value_dim, self.key_dim)
|
| 211 |
+
self.M = np.zeros(shape)
|
| 212 |
+
self.S = np.zeros(shape)
|
| 213 |
+
self._acc = np.zeros(shape)
|
| 214 |
+
self._acc_surprise = np.zeros(self.levels)
|
| 215 |
+
self._acc_count = np.zeros(self.levels, dtype=np.int64)
|
| 216 |
+
self.writes = 0
|
| 217 |
+
self.update_counts = np.zeros(self.levels, dtype=np.int64)
|
| 218 |
+
self.last_alpha = np.full(self.levels, self.forget)
|
| 219 |
+
self.last_surprise = 0.0
|
| 220 |
+
self.last_error = 0.0
|
| 221 |
+
|
| 222 |
+
@property
|
| 223 |
+
def parameter_count(self) -> int:
|
| 224 |
+
"""Number of memory entries (the fast weights ``M``)."""
|
| 225 |
+
return int(self.M.size)
|
| 226 |
+
|
| 227 |
+
@property
|
| 228 |
+
def state_numbers(self) -> int:
|
| 229 |
+
"""All stored numbers: memories, momentum, chunk accumulators and counters."""
|
| 230 |
+
return int(self.M.size + self.S.size + self._acc.size + self._acc_surprise.size + self._acc_count.size
|
| 231 |
+
+ self.update_counts.size + self.last_alpha.size + 3)
|
| 232 |
+
|
| 233 |
+
def config(self) -> dict[str, Any]:
|
| 234 |
+
return {'key_dim': self.key_dim, 'value_dim': self.value_dim, 'levels': self.levels,
|
| 235 |
+
'base_period': self.base_period, 'lr': self.lr, 'momentum': self.momentum, 'forget': self.forget,
|
| 236 |
+
'surprise_forget': self.surprise_forget, 'max_forget': self.max_forget,
|
| 237 |
+
'chunk_reduce': self.chunk_reduce, 'bound': self.bound}
|
| 238 |
+
|
| 239 |
+
# ------------------------------------------------------------------ read / write
|
| 240 |
+
def _keys(self, name: str, key: Any) -> np.ndarray:
|
| 241 |
+
arr = _finite(name, key)
|
| 242 |
+
if arr.shape == (self.key_dim,):
|
| 243 |
+
return np.broadcast_to(arr, (self.levels, self.key_dim))
|
| 244 |
+
if arr.shape != (self.levels, self.key_dim):
|
| 245 |
+
raise ValueError(f'{name} must have shape ({self.key_dim},) or ({self.levels}, {self.key_dim}), '
|
| 246 |
+
f'got {arr.shape}')
|
| 247 |
+
return arr
|
| 248 |
+
|
| 249 |
+
def read(self, query: Any) -> np.ndarray:
|
| 250 |
+
"""Every level's read ``M_l q_l`` as a ``(levels, value_dim)`` array (no state change)."""
|
| 251 |
+
return np.einsum('lvk,lk->lv', self.M, self._keys('query', query))
|
| 252 |
+
|
| 253 |
+
def predict(self, query: Any) -> np.ndarray:
|
| 254 |
+
"""Combined read ``sum_l M_l q_l``."""
|
| 255 |
+
return self.read(query).sum(axis=0)
|
| 256 |
+
|
| 257 |
+
def write(self, key: Any, value: Any) -> dict[str, Any]:
|
| 258 |
+
"""One write: score the joint read, accumulate every level's gradient, apply the levels that are due."""
|
| 259 |
+
ks = self._keys('key', key)
|
| 260 |
+
v = _vector('value', value, self.value_dim)
|
| 261 |
+
err = np.einsum('lvk,lk->v', self.M, ks) - v
|
| 262 |
+
e = float(err @ err)
|
| 263 |
+
surprise = e / (e + float(v @ v)) if e > 0.0 else 0.0
|
| 264 |
+
self._acc += 2.0 * err[None, :, None] * ks[:, None, :]
|
| 265 |
+
self._acc_surprise += surprise
|
| 266 |
+
self._acc_count += 1
|
| 267 |
+
self.writes += 1
|
| 268 |
+
updated: list[int] = []
|
| 269 |
+
for level, period in enumerate(self.periods):
|
| 270 |
+
if self.writes % period:
|
| 271 |
+
continue
|
| 272 |
+
n = int(self._acc_count[level])
|
| 273 |
+
grad = self._acc[level] / n if self.chunk_reduce == 'mean' else self._acc[level]
|
| 274 |
+
alpha = min(self.max_forget, self.forget + self.surprise_forget * float(self._acc_surprise[level]) / n)
|
| 275 |
+
self.S[level] = np.clip(self.momentum * self.S[level] - self.lr * grad, -self.bound, self.bound)
|
| 276 |
+
self.M[level] = np.clip((1.0 - alpha) * self.M[level] + self.S[level], -self.bound, self.bound)
|
| 277 |
+
self._acc[level] = 0.0
|
| 278 |
+
self._acc_surprise[level] = 0.0
|
| 279 |
+
self._acc_count[level] = 0
|
| 280 |
+
self.update_counts[level] += 1
|
| 281 |
+
self.last_alpha[level] = alpha
|
| 282 |
+
updated.append(level)
|
| 283 |
+
self.last_surprise = surprise
|
| 284 |
+
self.last_error = e / self.value_dim
|
| 285 |
+
return {'error': self.last_error, 'surprise': surprise, 'updated_levels': updated}
|
| 286 |
+
|
| 287 |
+
# ------------------------------------------------------------------ persistence
|
| 288 |
+
def export_state(self) -> dict[str, Any]:
|
| 289 |
+
return {'config': self.config(), 'M': self.M.tolist(), 'S': self.S.tolist(), 'acc': self._acc.tolist(),
|
| 290 |
+
'acc_surprise': self._acc_surprise.tolist(), 'acc_count': self._acc_count.tolist(),
|
| 291 |
+
'writes': int(self.writes), 'update_counts': self.update_counts.tolist(),
|
| 292 |
+
'last_alpha': self.last_alpha.tolist(), 'last_surprise': float(self.last_surprise),
|
| 293 |
+
'last_error': float(self.last_error)}
|
| 294 |
+
|
| 295 |
+
def import_state(self, state: Mapping[str, Any]) -> None:
|
| 296 |
+
"""Validate everything first, then replace the state (the configuration must match)."""
|
| 297 |
+
if not isinstance(state, Mapping):
|
| 298 |
+
raise ValueError('continuum memory state must be a mapping')
|
| 299 |
+
if state.get('config') != self.config():
|
| 300 |
+
raise ValueError('continuum memory state was made with a different configuration')
|
| 301 |
+
shape = (self.levels, self.value_dim, self.key_dim)
|
| 302 |
+
M = _array('M', state.get('M'), shape)
|
| 303 |
+
S = _array('S', state.get('S'), shape)
|
| 304 |
+
acc = _array('acc', state.get('acc'), shape)
|
| 305 |
+
acc_s = _array('acc_surprise', state.get('acc_surprise'), (self.levels,))
|
| 306 |
+
alpha = _array('last_alpha', state.get('last_alpha'), (self.levels,))
|
| 307 |
+
if np.max(np.abs(M), initial=0.0) > self.bound or np.max(np.abs(S), initial=0.0) > self.bound:
|
| 308 |
+
raise ValueError('memory state exceeds the configured bound')
|
| 309 |
+
if np.max(np.abs(acc), initial=0.0) > _MAX_ACCUMULATOR:
|
| 310 |
+
raise ValueError('gradient accumulator is out of range')
|
| 311 |
+
writes = _check_int('writes', state.get('writes'), 0, 2**62)
|
| 312 |
+
raw_counters = (state.get('acc_count'), state.get('update_counts'))
|
| 313 |
+
if not all(isinstance(c, (list, tuple, np.ndarray)) and np.ndim(c) == 1 and all(
|
| 314 |
+
isinstance(x, (int, np.integer)) and not isinstance(x, (bool, np.bool_)) for x in c)
|
| 315 |
+
for c in raw_counters):
|
| 316 |
+
raise ValueError('counters must be one-dimensional sequences of ints')
|
| 317 |
+
try:
|
| 318 |
+
counts = np.asarray(raw_counters[0], dtype=np.int64)
|
| 319 |
+
upd = np.asarray(raw_counters[1], dtype=np.int64)
|
| 320 |
+
except (TypeError, ValueError, OverflowError) as exc:
|
| 321 |
+
raise ValueError('counters must be integer arrays') from exc
|
| 322 |
+
expected_counts = np.array([writes % p for p in self.periods], dtype=np.int64)
|
| 323 |
+
expected_upd = np.array([writes // p for p in self.periods], dtype=np.int64)
|
| 324 |
+
if counts.shape != (self.levels,) or not np.array_equal(counts, expected_counts):
|
| 325 |
+
raise ValueError('chunk counters do not match the write count')
|
| 326 |
+
if upd.shape != (self.levels,) or not np.array_equal(upd, expected_upd):
|
| 327 |
+
raise ValueError('update counters do not match the write count')
|
| 328 |
+
if np.any(acc_s < 0.0) or np.any(acc_s > counts) or np.any(alpha < 0.0) or np.any(alpha > self.max_forget):
|
| 329 |
+
raise ValueError('surprise accumulators / forgetting gates out of range')
|
| 330 |
+
if np.any(acc[counts == 0] != 0.0):
|
| 331 |
+
raise ValueError('a level with an empty chunk must have a zero gradient accumulator')
|
| 332 |
+
ls = _check_float('last_surprise', state.get('last_surprise'), 0.0, 1.0)
|
| 333 |
+
le = _check_float('last_error', state.get('last_error'), 0.0, 1e300)
|
| 334 |
+
self.M, self.S, self._acc = M.copy(), S.copy(), acc.copy()
|
| 335 |
+
self._acc_surprise, self._acc_count, self.update_counts = acc_s.copy(), counts.copy(), upd.copy()
|
| 336 |
+
self.last_alpha = alpha.copy()
|
| 337 |
+
self.writes = int(writes)
|
| 338 |
+
self.last_surprise, self.last_error = ls, le
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
# ====================================================================== engine extension
|
| 342 |
+
def _fit(vec: np.ndarray, size: int) -> np.ndarray:
|
| 343 |
+
out = np.zeros(size)
|
| 344 |
+
m = min(size, vec.size)
|
| 345 |
+
out[:m] = vec[:m]
|
| 346 |
+
return out
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
class ContinuumMemoryExtension(EngineExtension):
|
| 350 |
+
"""Readout-only NEUROWEAVE extension around a :class:`ContinuumMemory`.
|
| 351 |
+
|
| 352 |
+
Context ``c_t`` = task input (fitted to ``TASK_INPUT_DIM``; zeros when absent) followed by the fused sensory
|
| 353 |
+
frame. The key is a fixed binary random-feature map ``k = sign(R c + b) / sqrt(levels * key_dim)`` split
|
| 354 |
+
into one ``key_dim`` block per level (unit norm overall). After every engine step the extension writes
|
| 355 |
+
``key(c_{t-1}) -> sensory_t`` (only when ``ctx['learn']``; never before a previous context exists, e.g.
|
| 356 |
+
right after :meth:`reset`) and then reads every level with ``key(c_t)``. ``features()`` are
|
| 357 |
+
``features_per_level`` fixed unit-norm projections of each level's 16-channel read, clipped to [-10, 10].
|
| 358 |
+
The brain output is not used and the drive is never changed."""
|
| 359 |
+
|
| 360 |
+
id = MODULE_ID
|
| 361 |
+
|
| 362 |
+
def __init__(self, levels: int = 4, key_dim: int = 8, base_period: int = 1, lr: float = 0.25,
|
| 363 |
+
momentum: float = 0.0, forget: float = 0.01, *, features_per_level: int = 2,
|
| 364 |
+
surprise_forget: float = 0.0, max_forget: float = 0.5, chunk_reduce: str = 'sum',
|
| 365 |
+
seed: int = 0) -> None:
|
| 366 |
+
self.seed = _check_int('seed', seed, 0, 2**31 - 1)
|
| 367 |
+
self.features_per_level = _check_int('features_per_level', features_per_level, 1, 64)
|
| 368 |
+
self.memory = ContinuumMemory(key_dim, SENSORY_DIM, levels, base_period, lr, momentum, forget,
|
| 369 |
+
surprise_forget=surprise_forget, max_forget=max_forget,
|
| 370 |
+
chunk_reduce=chunk_reduce)
|
| 371 |
+
self.levels = self.memory.levels
|
| 372 |
+
self.key_dim = self.memory.key_dim
|
| 373 |
+
self.feature_dim = self.levels * self.features_per_level
|
| 374 |
+
if self.feature_dim > 4096:
|
| 375 |
+
raise ValueError('levels * features_per_level must be <= 4096')
|
| 376 |
+
rng = np.random.default_rng(self.seed + _KEY_OFFSET)
|
| 377 |
+
self._R = rng.standard_normal((self.levels * self.key_dim, CONTEXT_DIM))
|
| 378 |
+
self._b = 0.5 * rng.standard_normal(self.levels * self.key_dim)
|
| 379 |
+
prng = np.random.default_rng(self.seed + _FEATURE_OFFSET)
|
| 380 |
+
proj = prng.standard_normal((self.levels, self.features_per_level, SENSORY_DIM))
|
| 381 |
+
self._P = proj / np.linalg.norm(proj, axis=2, keepdims=True)
|
| 382 |
+
self._key_scale = 1.0 / math.sqrt(self.levels * self.key_dim)
|
| 383 |
+
self._prev_key: np.ndarray | None = None
|
| 384 |
+
self._features = np.zeros(self.feature_dim)
|
| 385 |
+
self._steps = 0
|
| 386 |
+
self._frozen_steps = 0
|
| 387 |
+
|
| 388 |
+
# ------------------------------------------------------------------ lifecycle
|
| 389 |
+
def bind(self, engine: Any) -> None:
|
| 390 |
+
"""Nothing is sized from the engine (the context has a fixed width); start a fresh episode."""
|
| 391 |
+
self.reset()
|
| 392 |
+
|
| 393 |
+
def reset(self) -> None:
|
| 394 |
+
self._prev_key = None
|
| 395 |
+
self._features = np.zeros(self.feature_dim)
|
| 396 |
+
|
| 397 |
+
# ------------------------------------------------------------------ hooks
|
| 398 |
+
def key(self, context: Any) -> np.ndarray:
|
| 399 |
+
"""``(levels, key_dim)`` binary random-feature key of a ``CONTEXT_DIM`` context vector."""
|
| 400 |
+
c = _vector('context', context, CONTEXT_DIM)
|
| 401 |
+
z = self._R @ c + self._b
|
| 402 |
+
return (np.where(z >= 0.0, 1.0, -1.0) * self._key_scale).reshape(self.levels, self.key_dim)
|
| 403 |
+
|
| 404 |
+
def after_step(self, output: np.ndarray, ctx: Mapping[str, Any]) -> None:
|
| 405 |
+
if not isinstance(ctx, Mapping):
|
| 406 |
+
raise ValueError('continuum memory needs the engine step context')
|
| 407 |
+
learn = ctx.get('learn')
|
| 408 |
+
if type(learn) is not bool:
|
| 409 |
+
raise ValueError("ctx['learn'] must be a boolean")
|
| 410 |
+
sensory = _vector("ctx['sensory']", ctx.get('sensory'), SENSORY_DIM)
|
| 411 |
+
task = ctx.get('task_input')
|
| 412 |
+
task_vec = np.zeros(TASK_INPUT_DIM) if task is None else _fit(_finite("ctx['task_input']", task).ravel(),
|
| 413 |
+
TASK_INPUT_DIM)
|
| 414 |
+
key = self.key(np.concatenate([task_vec, sensory]))
|
| 415 |
+
if learn and self._prev_key is not None:
|
| 416 |
+
self.memory.write(self._prev_key, sensory)
|
| 417 |
+
elif not learn:
|
| 418 |
+
self._frozen_steps += 1
|
| 419 |
+
reads = self.memory.read(key)
|
| 420 |
+
self._features = np.clip(np.einsum('lfv,lv->lf', self._P, reads).ravel(), -10.0, 10.0)
|
| 421 |
+
self._prev_key = key
|
| 422 |
+
self._steps += 1
|
| 423 |
+
|
| 424 |
+
def features(self) -> np.ndarray:
|
| 425 |
+
return self._features.copy()
|
| 426 |
+
|
| 427 |
+
# ------------------------------------------------------------------ accounting / persistence
|
| 428 |
+
def parameter_count(self) -> int:
|
| 429 |
+
return self.memory.parameter_count
|
| 430 |
+
|
| 431 |
+
def state_numbers(self) -> int:
|
| 432 |
+
return int(self.memory.state_numbers + self._R.size + self._b.size + self._P.size
|
| 433 |
+
+ self.levels * self.key_dim + self.feature_dim + 2)
|
| 434 |
+
|
| 435 |
+
def telemetry(self) -> dict[str, Any]:
|
| 436 |
+
mem = self.memory
|
| 437 |
+
return {'id': self.id, 'levels': self.levels, 'periods': list(mem.periods), 'writes': int(mem.writes),
|
| 438 |
+
'update_counts': mem.update_counts.tolist(), 'steps': self._steps, 'frozen_steps': self._frozen_steps,
|
| 439 |
+
'last_surprise': float(mem.last_surprise), 'last_error': float(mem.last_error),
|
| 440 |
+
'last_alpha': mem.last_alpha.tolist(),
|
| 441 |
+
'level_norms': [float(np.linalg.norm(mem.M[level])) for level in range(self.levels)]}
|
| 442 |
+
|
| 443 |
+
def _config(self) -> dict[str, Any]:
|
| 444 |
+
mem = self.memory
|
| 445 |
+
return {'levels': self.levels, 'key_dim': self.key_dim, 'base_period': mem.base_period, 'lr': mem.lr,
|
| 446 |
+
'momentum': mem.momentum, 'forget': mem.forget, 'features_per_level': self.features_per_level,
|
| 447 |
+
'surprise_forget': mem.surprise_forget, 'max_forget': mem.max_forget,
|
| 448 |
+
'chunk_reduce': mem.chunk_reduce, 'seed': self.seed}
|
| 449 |
+
|
| 450 |
+
def export_state(self) -> dict[str, Any]:
|
| 451 |
+
return {'id': self.id, 'config': self._config(), 'memory': self.memory.export_state(),
|
| 452 |
+
'prev_key': None if self._prev_key is None else self._prev_key.tolist(),
|
| 453 |
+
'features': self._features.tolist(), 'steps': self._steps, 'frozen_steps': self._frozen_steps}
|
| 454 |
+
|
| 455 |
+
def import_state(self, state: Mapping[str, Any]) -> None:
|
| 456 |
+
super().import_state(state)
|
| 457 |
+
if state.get('config') != self._config():
|
| 458 |
+
raise ValueError('continuum memory extension state was made with a different configuration')
|
| 459 |
+
memory = copy.deepcopy(self.memory)
|
| 460 |
+
memory.import_state(state.get('memory')) # validates fully before anything is replaced
|
| 461 |
+
prev = state.get('prev_key')
|
| 462 |
+
if prev is not None:
|
| 463 |
+
prev = _array('prev_key', prev, (self.levels, self.key_dim))
|
| 464 |
+
if not np.allclose(np.abs(prev), self._key_scale, rtol=0.0, atol=1e-12):
|
| 465 |
+
raise ValueError('prev_key is not a binary random-feature key')
|
| 466 |
+
feats = _array('features', state.get('features'), (self.feature_dim,))
|
| 467 |
+
if np.max(np.abs(feats), initial=0.0) > 10.0:
|
| 468 |
+
raise ValueError('features out of range')
|
| 469 |
+
steps = _check_int('steps', state.get('steps'), 0, 2**62)
|
| 470 |
+
frozen = _check_int('frozen_steps', state.get('frozen_steps'), 0, steps)
|
| 471 |
+
self.memory = memory
|
| 472 |
+
self._prev_key = None if prev is None else np.where(prev > 0.0, self._key_scale, -self._key_scale)
|
| 473 |
+
self._features = feats.copy()
|
| 474 |
+
self._steps, self._frozen_steps = steps, frozen
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
# ====================================================================== recall benchmark
|
| 478 |
+
def make_recall_stream(seed: int, steps: int, *, key_dim: int = 128, value_dim: int = 8, n_short: int = 4,
|
| 479 |
+
n_long: int = 8, short_gap: Sequence[int] = (3, 10), long_gap: Sequence[int] = (40, 80),
|
| 480 |
+
remap_prob: float = 0.0) -> dict[str, np.ndarray]:
|
| 481 |
+
"""Deterministic key -> value stream with recurring associations and one-off interference.
|
| 482 |
+
|
| 483 |
+
``n_short`` items recur after gaps drawn from ``short_gap`` and ``n_long`` items after gaps from
|
| 484 |
+
``long_gap`` (inclusive, in steps). When several items are due, the earliest-due one is presented (ties: lowest
|
| 485 |
+
index) and the others wait, so realised gaps can be longer than drawn. Steps without a due item present a fresh
|
| 486 |
+
one-off association. With ``remap_prob`` a short-gap item gets a new value at a recurrence (kind ``remap``:
|
| 487 |
+
a write of a changed association, not a recall query). Keys are random unit vectors, values standard normal.
|
| 488 |
+
Returns ``keys (T, key_dim)``, ``values (T, value_dim)``, ``kind (T,)`` (codes in ``KIND_CODES``),
|
| 489 |
+
``item (T,)`` (-1 for fresh) and ``gap (T,)`` (0 unless the step is a recurrence)."""
|
| 490 |
+
_check_int('seed', seed, 0, 2**31 - 1)
|
| 491 |
+
_check_int('steps', steps, 1, 1_000_000)
|
| 492 |
+
_check_int('key_dim', key_dim, 1, 65_536)
|
| 493 |
+
_check_int('value_dim', value_dim, 1, 4096)
|
| 494 |
+
_check_int('n_short', n_short, 0, 1024)
|
| 495 |
+
_check_int('n_long', n_long, 0, 1024)
|
| 496 |
+
sg = _check_pair('short_gap', short_gap, 1, 1_000_000)
|
| 497 |
+
lg = _check_pair('long_gap', long_gap, 1, 1_000_000)
|
| 498 |
+
p_remap = _check_float('remap_prob', remap_prob, 0.0, 1.0)
|
| 499 |
+
rng = np.random.default_rng(seed + _STREAM_OFFSET)
|
| 500 |
+
n_items = n_short + n_long
|
| 501 |
+
item_keys = rng.standard_normal((n_items, key_dim))
|
| 502 |
+
item_keys /= np.linalg.norm(item_keys, axis=1, keepdims=True)
|
| 503 |
+
item_values = rng.standard_normal((n_items, value_dim))
|
| 504 |
+
gaps = [sg] * n_short + [lg] * n_long
|
| 505 |
+
due = np.array([int(rng.integers(0, g[1])) for g in gaps], dtype=np.int64)
|
| 506 |
+
last = np.full(n_items, -1, dtype=np.int64)
|
| 507 |
+
keys = np.zeros((steps, key_dim))
|
| 508 |
+
values = np.zeros((steps, value_dim))
|
| 509 |
+
kind = np.zeros(steps, dtype=np.int8)
|
| 510 |
+
item = np.full(steps, -1, dtype=np.int64)
|
| 511 |
+
gap = np.zeros(steps, dtype=np.int64)
|
| 512 |
+
for t in range(steps):
|
| 513 |
+
cand = np.flatnonzero(due <= t) if n_items else np.zeros(0, dtype=np.int64)
|
| 514 |
+
if cand.size:
|
| 515 |
+
i = int(cand[np.argmin(due[cand])])
|
| 516 |
+
if last[i] < 0:
|
| 517 |
+
code = KIND_CODES['first']
|
| 518 |
+
elif i < n_short:
|
| 519 |
+
code = KIND_CODES['short']
|
| 520 |
+
if p_remap > 0.0 and rng.random() < p_remap:
|
| 521 |
+
item_values[i] = rng.standard_normal(value_dim)
|
| 522 |
+
code = KIND_CODES['remap']
|
| 523 |
+
else:
|
| 524 |
+
code = KIND_CODES['long']
|
| 525 |
+
keys[t], values[t], kind[t], item[t] = item_keys[i], item_values[i], code, i
|
| 526 |
+
gap[t] = t - last[i] if last[i] >= 0 else 0
|
| 527 |
+
last[i] = t
|
| 528 |
+
due[i] = t + int(rng.integers(gaps[i][0], gaps[i][1] + 1))
|
| 529 |
+
else:
|
| 530 |
+
k = rng.standard_normal(key_dim)
|
| 531 |
+
keys[t] = k / np.linalg.norm(k)
|
| 532 |
+
values[t] = rng.standard_normal(value_dim)
|
| 533 |
+
return {'keys': keys, 'values': values, 'kind': kind, 'item': item, 'gap': gap}
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
def _score(preds_err: list[float], kinds: list[int]) -> dict[str, Any]:
|
| 537 |
+
err = np.asarray(preds_err)
|
| 538 |
+
kd = np.asarray(kinds)
|
| 539 |
+
out: dict[str, Any] = {}
|
| 540 |
+
for name in ('short', 'long'):
|
| 541 |
+
sel = err[kd == KIND_CODES[name]]
|
| 542 |
+
out[f'{name}_mse'] = float(sel.mean()) if sel.size else None
|
| 543 |
+
out[f'{name}_queries'] = int(sel.size)
|
| 544 |
+
return out
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
def _run_memory(memory: ContinuumMemory, stream: Mapping[str, np.ndarray], split: bool) -> dict[str, Any]:
|
| 548 |
+
"""Prequential: predict the value from the key, score recurring items, then write."""
|
| 549 |
+
errs, kinds = [], []
|
| 550 |
+
shape = (memory.levels, memory.key_dim)
|
| 551 |
+
for key, value, code in zip(stream['keys'], stream['values'], stream['kind']):
|
| 552 |
+
k = key.reshape(shape) if split else key
|
| 553 |
+
pred = memory.predict(k)
|
| 554 |
+
if code in (KIND_CODES['short'], KIND_CODES['long']):
|
| 555 |
+
errs.append(float(np.mean((pred - value) ** 2)))
|
| 556 |
+
kinds.append(int(code))
|
| 557 |
+
memory.write(k, value)
|
| 558 |
+
return _score(errs, kinds)
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
def _run_mean_predictor(stream: Mapping[str, np.ndarray]) -> dict[str, Any]:
|
| 562 |
+
"""No memory: predict the running mean of the values seen so far."""
|
| 563 |
+
mean = np.zeros(stream['values'].shape[1])
|
| 564 |
+
errs, kinds = [], []
|
| 565 |
+
for n, (value, code) in enumerate(zip(stream['values'], stream['kind']), start=1):
|
| 566 |
+
if code in (KIND_CODES['short'], KIND_CODES['long']):
|
| 567 |
+
errs.append(float(np.mean((mean - value) ** 2)))
|
| 568 |
+
kinds.append(int(code))
|
| 569 |
+
mean = mean + (value - mean) / n
|
| 570 |
+
return _score(errs, kinds)
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
def _overall(score: Mapping[str, Any]) -> float:
|
| 574 |
+
vals = [score[k] for k in ('short_mse', 'long_mse') if score[k] is not None]
|
| 575 |
+
return float(np.mean(vals)) if vals else float('inf')
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
# The grids bracket both arms' tuned optimum (measured 2026-11-19): learning rate and momentum trade off along a
|
| 579 |
+
# ridge of nearly equal effective step lr / (1 - momentum), and a grid that stops short of one arm's optimum on that
|
| 580 |
+
# ridge can hand the other arm a spurious win. Receipts flag a chosen value that sits on a grid edge.
|
| 581 |
+
RECALL_DEFAULTS: dict[str, Any] = {
|
| 582 |
+
'steps': 800, 'levels': 4, 'key_dim': 32, 'value_dim': 8, 'base_period': 1,
|
| 583 |
+
'n_short': 4, 'n_long': 8, 'short_gap': (3, 10), 'long_gap': (40, 80), 'remap_prob': 0.0,
|
| 584 |
+
'chunk_reduce': 'sum', 'surprise_forget': 0.0, 'max_forget': 0.5,
|
| 585 |
+
'lr_grid': (0.015625, 0.03125, 0.0625, 0.125, 0.25, 0.5), 'momentum_grid': (0.0, 0.5, 0.75, 0.875, 0.9375),
|
| 586 |
+
'forget_grid': (0.0, 0.01), 'tune_seeds': (1000, 1001)}
|
| 587 |
+
RECALL_QUICK: dict[str, Any] = {'steps': 240, 'lr_grid': (0.125, 0.25, 0.5), 'momentum_grid': (0.0, 0.25, 0.5),
|
| 588 |
+
'forget_grid': (0.0, 0.02), 'tune_seeds': (1000,)}
|
| 589 |
+
_NATURAL_BOUNDS = {'lr': (0.0,), 'momentum': (0.0,), 'forget': (0.0,)}
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
def run_recall_benchmark(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]:
|
| 593 |
+
"""CMS vs a single-level Titans-style memory with the same number of entries vs no memory.
|
| 594 |
+
|
| 595 |
+
Both memories use the same keys (random unit vectors in ``levels * key_dim`` dimensions): CMS level ``l`` reads
|
| 596 |
+
block ``l`` of the key, the single-level memory reads all of it, so both read functions are linear maps of the
|
| 597 |
+
same key with ``value_dim * levels * key_dim`` entries and differ only in the update schedule. For each memory
|
| 598 |
+
arm, ``(lr, momentum, forget)`` is chosen from the same grid by the mean of short- and long-gap recall MSE on
|
| 599 |
+
``tune_seeds`` (disjoint from ``seeds``); the chosen values are then evaluated on every seed. Verdict: paired
|
| 600 |
+
95 % t interval on long-gap recall MSE (lower is better), CMS vs single-level memory."""
|
| 601 |
+
from . import harness
|
| 602 |
+
if type(quick) is not bool:
|
| 603 |
+
raise ValueError('quick must be a boolean')
|
| 604 |
+
seeds = _check_seeds('seeds', seeds)
|
| 605 |
+
cfg = dict(RECALL_DEFAULTS)
|
| 606 |
+
if quick:
|
| 607 |
+
cfg.update(RECALL_QUICK)
|
| 608 |
+
unknown = sorted(set(overrides) - set(cfg))
|
| 609 |
+
if unknown:
|
| 610 |
+
raise ValueError(f'unknown run_recall_benchmark overrides: {unknown}')
|
| 611 |
+
cfg.update(overrides)
|
| 612 |
+
_check_int('steps', cfg['steps'], 16, 200_000)
|
| 613 |
+
tune_seeds = _check_seeds('tune_seeds', cfg['tune_seeds'])
|
| 614 |
+
if set(tune_seeds) & set(seeds):
|
| 615 |
+
raise ValueError('tune_seeds must be disjoint from seeds')
|
| 616 |
+
for name, lo, hi, open_hi in (('lr_grid', 0.0, 10.0, False), ('momentum_grid', 0.0, 1.0, True),
|
| 617 |
+
('forget_grid', 0.0, 1.0, True)):
|
| 618 |
+
cfg[name] = _check_grid(name, cfg[name], lo, hi, high_open=open_hi)
|
| 619 |
+
cfg['short_gap'] = _check_pair('short_gap', cfg['short_gap'], 1, 1_000_000)
|
| 620 |
+
cfg['long_gap'] = _check_pair('long_gap', cfg['long_gap'], 1, 1_000_000)
|
| 621 |
+
cfg['max_forget'] = _check_float('max_forget', cfg['max_forget'], 0.0, 1.0, high_open=True) # used in max()
|
| 622 |
+
cfg['tune_seeds'] = tune_seeds
|
| 623 |
+
levels, key_dim, value_dim = cfg['levels'], cfg['key_dim'], cfg['value_dim']
|
| 624 |
+
|
| 625 |
+
def make(arm: str, lr: float, momentum: float, forget: float) -> ContinuumMemory:
|
| 626 |
+
common = dict(surprise_forget=cfg['surprise_forget'], max_forget=max(cfg['max_forget'], forget),
|
| 627 |
+
chunk_reduce=cfg['chunk_reduce'])
|
| 628 |
+
if arm == 'cms':
|
| 629 |
+
return ContinuumMemory(key_dim, value_dim, levels, cfg['base_period'], lr, momentum, forget, **common)
|
| 630 |
+
return ContinuumMemory(levels * key_dim, value_dim, 1, 1, lr, momentum, forget, **common)
|
| 631 |
+
|
| 632 |
+
probe_cms, probe_single = make('cms', 0.5, 0.0, 0.0), make('single', 0.5, 0.0, 0.0) # validates sizes
|
| 633 |
+
if probe_cms.parameter_count != probe_single.parameter_count:
|
| 634 |
+
raise AssertionError('capacity matching failed')
|
| 635 |
+
stream_kw = dict(key_dim=levels * key_dim, value_dim=value_dim, n_short=cfg['n_short'], n_long=cfg['n_long'],
|
| 636 |
+
short_gap=cfg['short_gap'], long_gap=cfg['long_gap'], remap_prob=cfg['remap_prob'])
|
| 637 |
+
t0 = time.perf_counter()
|
| 638 |
+
tune_streams = [make_recall_stream(s, cfg['steps'], **stream_kw) for s in tune_seeds]
|
| 639 |
+
grid = list(itertools.product(cfg['lr_grid'], cfg['momentum_grid'], cfg['forget_grid']))
|
| 640 |
+
tuning: dict[str, Any] = {}
|
| 641 |
+
chosen: dict[str, tuple[float, float, float]] = {}
|
| 642 |
+
for arm in ('cms', 'single'):
|
| 643 |
+
table = []
|
| 644 |
+
for lr, momentum, forget in grid:
|
| 645 |
+
score = float(np.mean([_overall(_run_memory(make(arm, lr, momentum, forget), st, arm == 'cms'))
|
| 646 |
+
for st in tune_streams]))
|
| 647 |
+
table.append({'lr': lr, 'momentum': momentum, 'forget': forget, 'tune_score': score})
|
| 648 |
+
best = min(range(len(table)), key=lambda i: (table[i]['tune_score'], i))
|
| 649 |
+
chosen[arm] = (table[best]['lr'], table[best]['momentum'], table[best]['forget'])
|
| 650 |
+
picked = dict(zip(('lr', 'momentum', 'forget'), chosen[arm]))
|
| 651 |
+
edges = _grid_edges(picked, {'lr': cfg['lr_grid'], 'momentum': cfg['momentum_grid'],
|
| 652 |
+
'forget': cfg['forget_grid']}, _NATURAL_BOUNDS)
|
| 653 |
+
tuning[arm] = {'chosen': picked, 'chosen_on_grid_edge': edges, 'table': table}
|
| 654 |
+
tune_wall = time.perf_counter() - t0
|
| 655 |
+
|
| 656 |
+
t1 = time.perf_counter()
|
| 657 |
+
per_seed = []
|
| 658 |
+
for s in seeds:
|
| 659 |
+
stream = make_recall_stream(s, cfg['steps'], **stream_kw)
|
| 660 |
+
row = {'seed': int(s),
|
| 661 |
+
'cms': _run_memory(make('cms', *chosen['cms']), stream, True),
|
| 662 |
+
'single': _run_memory(make('single', *chosen['single']), stream, False),
|
| 663 |
+
'none': _run_mean_predictor(stream),
|
| 664 |
+
'kinds': {name: int(np.sum(stream['kind'] == code)) for name, code in KIND_CODES.items()}}
|
| 665 |
+
per_seed.append(row)
|
| 666 |
+
eval_wall = time.perf_counter() - t1
|
| 667 |
+
|
| 668 |
+
def vals(arm: str, metric: str) -> list[float]:
|
| 669 |
+
return [float('nan') if r[arm][metric] is None else r[arm][metric] for r in per_seed]
|
| 670 |
+
|
| 671 |
+
comparisons = {
|
| 672 |
+
'cms_vs_single_long_gap': harness.compare(vals('cms', 'long_mse'), vals('single', 'long_mse'),
|
| 673 |
+
higher_is_better=False),
|
| 674 |
+
'cms_vs_single_short_gap': harness.compare(vals('cms', 'short_mse'), vals('single', 'short_mse'),
|
| 675 |
+
higher_is_better=False),
|
| 676 |
+
'cms_vs_none_long_gap': harness.compare(vals('cms', 'long_mse'), vals('none', 'long_mse'),
|
| 677 |
+
higher_is_better=False),
|
| 678 |
+
'single_vs_none_long_gap': harness.compare(vals('single', 'long_mse'), vals('none', 'long_mse'),
|
| 679 |
+
higher_is_better=False),
|
| 680 |
+
}
|
| 681 |
+
summary = {arm: {m: float(np.nanmean(vals(arm, m))) for m in ('short_mse', 'long_mse')}
|
| 682 |
+
for arm in ('cms', 'single', 'none')}
|
| 683 |
+
entries = probe_cms.parameter_count
|
| 684 |
+
runs = len(grid) * len(tune_seeds) * 2 + 2 * len(seeds)
|
| 685 |
+
receipt = harness.base_receipt(RECALL_ID, 'memory_benchmark', {
|
| 686 |
+
**{k: (list(v) if isinstance(v, tuple) else v) for k, v in cfg.items()},
|
| 687 |
+
'seeds': list(seeds), 'quick': quick, 'scored_kinds': ['short', 'long'],
|
| 688 |
+
'tuning_objective': 'mean of short- and long-gap recall MSE on tune_seeds'})
|
| 689 |
+
receipt.update({
|
| 690 |
+
'module': MODULE_ID, 'source': SOURCE,
|
| 691 |
+
'arms': {'cms': f'{levels}-level continuum memory, periods {list(probe_cms.periods)}, per-level key blocks',
|
| 692 |
+
'single': 'one Titans-style memory (momentum + forgetting) reading the full key, period 1',
|
| 693 |
+
'none': 'running mean of the values seen so far'},
|
| 694 |
+
'tuning': tuning, 'per_seed': per_seed, 'summary': summary, 'comparisons': comparisons,
|
| 695 |
+
'verdict': comparisons['cms_vs_single_long_gap']['verdict'],
|
| 696 |
+
'verdict_basis': ('cms_vs_single_level_memory: paired 95% t interval over seeds on long-gap recall MSE '
|
| 697 |
+
'(lower is better); hyperparameters tuned per arm on disjoint tune_seeds'),
|
| 698 |
+
'budget': {'cms_memory_entries': entries, 'single_memory_entries': probe_single.parameter_count,
|
| 699 |
+
'cms_state_numbers': probe_cms.state_numbers, 'single_state_numbers': probe_single.state_numbers},
|
| 700 |
+
'estimated_cost': {'memory_runs': runs, 'steps_per_run': cfg['steps'],
|
| 701 |
+
'estimated_multiply_adds': int(runs * cfg['steps'] * 4 * entries)},
|
| 702 |
+
'measured_wallclock_s': {'tuning': tune_wall, 'evaluation': eval_wall},
|
| 703 |
+
'notes': ('Synthetic stream of random unit keys and Gaussian values; recall is scored prequentially (read '
|
| 704 |
+
'before write) at short-gap and long-gap recurrences only. The two memory arms hold the same '
|
| 705 |
+
'number of entries and read the same keys, so they differ only in the multi-period update '
|
| 706 |
+
'schedule (and per-level forgetting); the gates are fixed numbers, not the learned '
|
| 707 |
+
'data-dependent gates of Titans or Hope. Each memory arm gets its best point of the same grid on '
|
| 708 |
+
'separate tuning seeds; tuning.<arm>.chosen_on_grid_edge names any hyperparameter whose chosen '
|
| 709 |
+
'value is a grid edge (the optimum may then lie outside the grid). A linear toy: it says nothing '
|
| 710 |
+
'about language modelling or the published results.'),
|
| 711 |
+
})
|
| 712 |
+
return harness.seal(receipt)
|
| 713 |
+
|
| 714 |
+
|
| 715 |
+
# ====================================================================== NEUROWEAVE extension experiment
|
| 716 |
+
_EXT_DEFAULTS: dict[str, Any] = {'levels': 4, 'key_dim': 8, 'base_period': 1, 'lr': 0.25, 'momentum': 0.0,
|
| 717 |
+
'forget': 0.01, 'features_per_level': 2, 'surprise_forget': 0.0, 'max_forget': 0.5,
|
| 718 |
+
'chunk_reduce': 'sum'}
|
| 719 |
+
_RUN_DEFAULTS: dict[str, Any] = {'task': 'delayed_recall', 'heldout_seeds': (100, 101), 'steps': 300,
|
| 720 |
+
'heldout_steps': None, 'neurons': 48, 'topology': 'clustered', 'mechanisms': ()}
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
def run_experiment(*, quick: bool = False, seeds: Sequence[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]:
|
| 724 |
+
"""Baseline vs ``ContinuumMemoryExtension`` readout features vs the random-trace capacity control on a
|
| 725 |
+
NEUROWEAVE temporal task (default ``delayed_recall``), through ``harness.run_extension_experiment``.
|
| 726 |
+
|
| 727 |
+
Extension overrides: the keys of ``_EXT_DEFAULTS``. Harness overrides: ``task``, ``heldout_seeds``, ``steps``,
|
| 728 |
+
``heldout_steps``, ``neurons``, ``topology``, ``mechanisms``. Quick mode uses the harness ``QUICK_ARGS`` sizes
|
| 729 |
+
(the seeds stay the caller's)."""
|
| 730 |
+
from . import harness
|
| 731 |
+
if type(quick) is not bool:
|
| 732 |
+
raise ValueError('quick must be a boolean')
|
| 733 |
+
seeds = _check_seeds('seeds', seeds)
|
| 734 |
+
ext_cfg, run_cfg = dict(_EXT_DEFAULTS), dict(_RUN_DEFAULTS)
|
| 735 |
+
if quick:
|
| 736 |
+
run_cfg.update({k: v for k, v in harness.QUICK_ARGS.items() if k != 'seeds'})
|
| 737 |
+
unknown = sorted(set(overrides) - set(ext_cfg) - set(run_cfg))
|
| 738 |
+
if unknown:
|
| 739 |
+
raise ValueError(f'unknown run_experiment overrides: {unknown}')
|
| 740 |
+
for key, value in overrides.items():
|
| 741 |
+
(ext_cfg if key in ext_cfg else run_cfg)[key] = value
|
| 742 |
+
ContinuumMemoryExtension(seed=0, **ext_cfg) # validate before running anything
|
| 743 |
+
|
| 744 |
+
def factory(seed: int) -> ContinuumMemoryExtension:
|
| 745 |
+
return ContinuumMemoryExtension(seed=seed, **ext_cfg)
|
| 746 |
+
|
| 747 |
+
t0 = time.perf_counter()
|
| 748 |
+
receipt = harness.run_extension_experiment(
|
| 749 |
+
MODULE_ID, factory, seeds=seeds, control='random_trace', metric='accuracy', notes=(
|
| 750 |
+
f'Readout-only extension: a {ext_cfg["levels"]}-level continuum memory stores previous task+sensory '
|
| 751 |
+
'context -> current '
|
| 752 |
+
'sensory frame (writes only while learning) and its per-level reads of the current context (a '
|
| 753 |
+
'multi-timescale forecast of the next frame) are projected to readout features. It never changes the '
|
| 754 |
+
'brain drive and does not read the brain output. The control gets the same number of random '
|
| 755 |
+
'leaky-trace features of the brain output. Small synthetic task; the verdict is a paired 95 % t '
|
| 756 |
+
'interval over seeds.'),
|
| 757 |
+
**run_cfg)
|
| 758 |
+
receipt = dict(receipt)
|
| 759 |
+
receipt.pop('digest', None)
|
| 760 |
+
receipt['config'] = {**receipt['config'], 'quick': quick, 'extension': ext_cfg}
|
| 761 |
+
receipt['module'] = MODULE_ID
|
| 762 |
+
receipt['source'] = SOURCE
|
| 763 |
+
receipt['measured_wallclock_s'] = {'total': time.perf_counter() - t0}
|
| 764 |
+
return harness.seal(receipt)
|
| 765 |
+
|
| 766 |
+
|
| 767 |
+
EXPERIMENTS: dict[str, Callable[..., dict[str, Any]]] = {MODULE_ID: run_experiment, RECALL_ID: run_recall_benchmark}
|
synapse/frontier/dendritic.py
ADDED
|
@@ -0,0 +1,592 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Structured dendritic layer (dANN) compared with a dense MLP at matched trainable parameters.
|
| 2 |
+
|
| 3 |
+
Inspired by (not a reproduction of): S. Chavlis and P. Poirazi, "Dendrites endow artificial
|
| 4 |
+
neural networks with accurate, robust and parameter-efficient learning", Nature
|
| 5 |
+
Communications 16, 943 (22 January 2025), https://doi.org/10.1038/s41467-025-56297-9
|
| 6 |
+
(preprint arXiv:2404.03708).
|
| 7 |
+
|
| 8 |
+
What is implemented
|
| 9 |
+
-------------------
|
| 10 |
+
``DendriticLayer`` is a two-stage sparse layer: ``somas * dendrites_per_soma`` dendrites each
|
| 11 |
+
receive exactly ``synapses_per_dendrite`` inputs through a *fixed* binary synaptic mask
|
| 12 |
+
(``W <- W * M``, applied in the forward pass so masked weights get no gradient, and re-applied
|
| 13 |
+
after every optimiser step as in the paper's Eq. 1/3); each dendrite applies a leaky ReLU
|
| 14 |
+
(slope 0.1, as in the paper); each soma sums its own dendrites through trainable cable weights
|
| 15 |
+
(every dendrite belongs to exactly one soma) and applies a second leaky ReLU::
|
| 16 |
+
|
| 17 |
+
d_k = lrelu(sum_i M_ki W_ki x_i + b_k) (dendrite k)
|
| 18 |
+
s_j = lrelu(sum_{k in dendrites(j)} c_jk d_k + a_j) (soma j)
|
| 19 |
+
|
| 20 |
+
Input sampling (fixed at construction from a seeded NumPy generator):
|
| 21 |
+
|
| 22 |
+
* ``random``: each dendrite samples ``synapses_per_dendrite`` distinct inputs uniformly;
|
| 23 |
+
* ``local``: each dendrite gets a uniformly drawn centre pixel and samples the nearest pixels
|
| 24 |
+
(its 3x3 block, subsampled, or expanded ring by ring with random fill), following the
|
| 25 |
+
authors' released ``receptive_fields.py``;
|
| 26 |
+
* ``global``: each soma gets a centre pixel; its dendrites' centres are drawn from the
|
| 27 |
+
neighbourhood of that centre by the same ring rule, and each dendrite then samples
|
| 28 |
+
locally around its own centre.
|
| 29 |
+
|
| 30 |
+
``parameter_count()`` counts only unmasked synapses plus biases and cable weights.
|
| 31 |
+
|
| 32 |
+
Benchmark (``run_experiment``)
|
| 33 |
+
------------------------------
|
| 34 |
+
Procedurally generated 12x12 glyphs (10 stroke-drawn classes, no downloads) with random
|
| 35 |
+
translation, scale, small rotation, stroke-thickness jitter and Gaussian pixel noise. Arms:
|
| 36 |
+
one dANN per sampling mode and a dense two-hidden-layer MLP whose width is chosen so its
|
| 37 |
+
trainable parameters match the dANN's (within ``param_tolerance``). All arms share data,
|
| 38 |
+
minibatch order, optimiser (Adam) and number of updates. Metrics: held-out accuracy and
|
| 39 |
+
held-out accuracy under extra pixel noise. The best dANN is chosen by mean *validation*
|
| 40 |
+
accuracy; the verdict is ``harness.compare`` (paired 95 % t interval over seeds) of that dANN
|
| 41 |
+
against the dense MLP on held-out accuracy; robustness gets its own comparison.
|
| 42 |
+
|
| 43 |
+
Synthetic abstraction only: the paper's datasets (MNIST variants, CIFAR-10), sizes and
|
| 44 |
+
efficiency scores are not reproduced.
|
| 45 |
+
"""
|
| 46 |
+
from __future__ import annotations
|
| 47 |
+
|
| 48 |
+
import contextlib
|
| 49 |
+
import functools
|
| 50 |
+
import math
|
| 51 |
+
import time
|
| 52 |
+
from typing import Any, Callable, Iterable, Iterator, Mapping
|
| 53 |
+
|
| 54 |
+
import numpy as np
|
| 55 |
+
import torch
|
| 56 |
+
import torch.nn.functional as F
|
| 57 |
+
from torch import nn
|
| 58 |
+
|
| 59 |
+
from . import harness
|
| 60 |
+
|
| 61 |
+
__all__ = ['MODULE_ID', 'EXPERIMENTS', 'SAMPLING_MODES', 'GLYPHS', 'GLYPH_NAMES', 'GLYPH_SIDE', 'DEFAULTS', 'QUICK',
|
| 62 |
+
'sample_receptive_fields', 'DendriticLayer', 'DendriticNet', 'DenseMLP', 'dense_parameter_count',
|
| 63 |
+
'dann_parameter_count', 'matched_dense_hidden', 'render_glyph', 'make_glyph_dataset', 'train_classifier',
|
| 64 |
+
'accuracy', 'run_experiment']
|
| 65 |
+
|
| 66 |
+
MODULE_ID = 'dendritic_layer'
|
| 67 |
+
SAMPLING_MODES = ('random', 'local', 'global')
|
| 68 |
+
NEGATIVE_SLOPE = 0.1 # leaky ReLU slope used for dendrites and somata in the paper
|
| 69 |
+
GLYPH_SIDE = 12
|
| 70 |
+
|
| 71 |
+
_MASK_OFFSET = 41_011
|
| 72 |
+
_INIT_OFFSET = 41_113
|
| 73 |
+
_DATA_OFFSET = 41_201
|
| 74 |
+
_NOISE_OFFSET = 41_303
|
| 75 |
+
_STREAM_OFFSET = 41_407
|
| 76 |
+
|
| 77 |
+
# Ten stroke glyphs as polylines in the unit square (x to the right, y downwards).
|
| 78 |
+
GLYPHS: dict[str, tuple[tuple[tuple[float, float], ...], ...]] = {
|
| 79 |
+
'box': (((0, 0), (1, 0), (1, 1), (0, 1), (0, 0)),),
|
| 80 |
+
'bar': (((0.5, 0), (0.5, 1)),),
|
| 81 |
+
'plus': (((0.5, 0), (0.5, 1)), ((0, 0.5), (1, 0.5))),
|
| 82 |
+
'cross': (((0, 0), (1, 1)), ((1, 0), (0, 1))),
|
| 83 |
+
'ell': (((0, 0), (0, 1), (1, 1)),),
|
| 84 |
+
'tee': (((0, 0), (1, 0)), ((0.5, 0), (0.5, 1))),
|
| 85 |
+
'zed': (((0, 0), (1, 0), (0, 1), (1, 1)),),
|
| 86 |
+
'caret': (((0, 1), (0.5, 0), (1, 1)),),
|
| 87 |
+
'aitch': (((0, 0), (0, 1)), ((1, 0), (1, 1)), ((0, 0.5), (1, 0.5))),
|
| 88 |
+
'cup': (((0, 0), (0, 1), (1, 1), (1, 0)),),
|
| 89 |
+
}
|
| 90 |
+
GLYPH_NAMES: tuple[str, ...] = tuple(GLYPHS)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _segments(name: str) -> np.ndarray:
|
| 94 |
+
segs = [(a, b) for line in GLYPHS[name] for a, b in zip(line[:-1], line[1:])]
|
| 95 |
+
return np.asarray(segs, dtype=np.float64) # (K, 2 endpoints, 2 coords)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
_SEGMENTS = {name: _segments(name) for name in GLYPH_NAMES}
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _check_int(name: str, value: Any, low: int, high: int) -> int:
|
| 102 |
+
if type(value) is not int or not low <= value <= high:
|
| 103 |
+
raise ValueError(f'{name} must be an int in [{low}, {high}]')
|
| 104 |
+
return value
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
# ====================================================================== receptive fields
|
| 108 |
+
def _ring(center: tuple[int, int], radius: int, shape: tuple[int, int]) -> list[int]:
|
| 109 |
+
"""Flat indices at Chebyshev distance exactly ``radius`` (0 = the centre) inside the image."""
|
| 110 |
+
r0, c0 = center
|
| 111 |
+
h, w = shape
|
| 112 |
+
out = []
|
| 113 |
+
for r in range(max(0, r0 - radius), min(h, r0 + radius + 1)):
|
| 114 |
+
for c in range(max(0, c0 - radius), min(w, c0 + radius + 1)):
|
| 115 |
+
if max(abs(r - r0), abs(c - c0)) == radius:
|
| 116 |
+
out.append(r * w + c)
|
| 117 |
+
return out
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _neighbourhood(center: tuple[int, int], count: int, shape: tuple[int, int], rng: np.random.Generator) -> list[int]:
|
| 121 |
+
"""``count`` distinct pixels nearest ``center``: its 3x3 block (subsampled when larger than needed),
|
| 122 |
+
then rings at Chebyshev radius 2, 3, ... with a random subset of the last ring needed."""
|
| 123 |
+
h, w = shape
|
| 124 |
+
if count > h * w:
|
| 125 |
+
raise ValueError('neighbourhood larger than the image')
|
| 126 |
+
block = _ring(center, 0, shape) + _ring(center, 1, shape)
|
| 127 |
+
if len(block) >= count:
|
| 128 |
+
return sorted(int(i) for i in rng.choice(block, size=count, replace=False))
|
| 129 |
+
chosen = list(block)
|
| 130 |
+
radius = 2
|
| 131 |
+
while len(chosen) < count:
|
| 132 |
+
ring = _ring(center, radius, shape)
|
| 133 |
+
need = count - len(chosen)
|
| 134 |
+
chosen.extend(ring if len(ring) <= need else (int(i) for i in rng.choice(ring, size=need, replace=False)))
|
| 135 |
+
radius += 1
|
| 136 |
+
return sorted(chosen)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def sample_receptive_fields(in_features: int, somas: int, dendrites_per_soma: int, synapses_per_dendrite: int,
|
| 140 |
+
sampling: str, *, image_shape: tuple[int, int] | None = None,
|
| 141 |
+
rng: np.random.Generator) -> np.ndarray:
|
| 142 |
+
"""Input indices per dendrite, shape ``(somas * dendrites_per_soma, synapses_per_dendrite)``, sorted per row.
|
| 143 |
+
|
| 144 |
+
Dendrites ``j * dendrites_per_soma ... (j + 1) * dendrites_per_soma - 1`` belong to soma ``j``."""
|
| 145 |
+
_check_int('in_features', in_features, 1, 1 << 20)
|
| 146 |
+
_check_int('somas', somas, 1, 1 << 16)
|
| 147 |
+
_check_int('dendrites_per_soma', dendrites_per_soma, 1, 1 << 12)
|
| 148 |
+
_check_int('synapses_per_dendrite', synapses_per_dendrite, 1, in_features)
|
| 149 |
+
if sampling not in SAMPLING_MODES:
|
| 150 |
+
raise ValueError(f'sampling must be one of {SAMPLING_MODES}')
|
| 151 |
+
shape = _image_shape(in_features, image_shape)
|
| 152 |
+
if sampling == 'global' and dendrites_per_soma > in_features:
|
| 153 |
+
raise ValueError('global sampling needs dendrites_per_soma <= in_features (distinct dendrite centres)')
|
| 154 |
+
n_dend = somas * dendrites_per_soma
|
| 155 |
+
fields = np.zeros((n_dend, synapses_per_dendrite), dtype=np.int64)
|
| 156 |
+
h, w = shape
|
| 157 |
+
if sampling == 'random':
|
| 158 |
+
for k in range(n_dend):
|
| 159 |
+
fields[k] = np.sort(rng.choice(in_features, size=synapses_per_dendrite, replace=False))
|
| 160 |
+
elif sampling == 'local':
|
| 161 |
+
for k in range(n_dend):
|
| 162 |
+
c = int(rng.integers(in_features))
|
| 163 |
+
fields[k] = _neighbourhood((c // w, c % w), synapses_per_dendrite, shape, rng)
|
| 164 |
+
else:
|
| 165 |
+
for j in range(somas):
|
| 166 |
+
c = int(rng.integers(in_features))
|
| 167 |
+
centres = _neighbourhood((c // w, c % w), dendrites_per_soma, shape, rng)
|
| 168 |
+
order = rng.permutation(len(centres))
|
| 169 |
+
for i, ci in enumerate(order):
|
| 170 |
+
cc = centres[int(ci)]
|
| 171 |
+
fields[j * dendrites_per_soma + i] = _neighbourhood((cc // w, cc % w), synapses_per_dendrite, shape, rng)
|
| 172 |
+
return fields
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def _image_shape(in_features: int, image_shape: tuple[int, int] | None) -> tuple[int, int]:
|
| 176 |
+
if image_shape is None:
|
| 177 |
+
side = math.isqrt(in_features)
|
| 178 |
+
return (side, side) if side * side == in_features else (1, in_features)
|
| 179 |
+
if (not isinstance(image_shape, (tuple, list)) or len(image_shape) != 2
|
| 180 |
+
or any(type(v) is not int or v < 1 for v in image_shape) or image_shape[0] * image_shape[1] != in_features):
|
| 181 |
+
raise ValueError('image_shape must be two positive ints whose product is in_features')
|
| 182 |
+
return int(image_shape[0]), int(image_shape[1])
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
# ====================================================================== models
|
| 186 |
+
class _Linear(nn.Module):
|
| 187 |
+
"""Affine map initialised like ``nn.Linear`` but from an explicit generator (never the global RNG)."""
|
| 188 |
+
|
| 189 |
+
def __init__(self, in_features: int, out_features: int, generator: torch.Generator) -> None:
|
| 190 |
+
super().__init__()
|
| 191 |
+
bound = 1.0 / math.sqrt(in_features)
|
| 192 |
+
self.weight = nn.Parameter(torch.empty(out_features, in_features).uniform_(-bound, bound, generator=generator))
|
| 193 |
+
self.bias = nn.Parameter(torch.empty(out_features).uniform_(-bound, bound, generator=generator))
|
| 194 |
+
|
| 195 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 196 |
+
return F.linear(x, self.weight, self.bias)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
class DendriticLayer(nn.Module):
|
| 200 |
+
"""Dendrites with fixed sparse receptive fields feeding somata that sum their own dendrites.
|
| 201 |
+
|
| 202 |
+
``synaptic_mask`` (buffer, 0/1, shape ``(somas * dendrites_per_soma, in_features)``) has exactly
|
| 203 |
+
``synapses_per_dendrite`` ones per row and never changes; ``cable_weight`` has shape
|
| 204 |
+
``(somas, dendrites_per_soma)`` (each dendrite connects to one soma)."""
|
| 205 |
+
|
| 206 |
+
def __init__(self, in_features: int, somas: int, dendrites_per_soma: int, synapses_per_dendrite: int,
|
| 207 |
+
sampling: str = 'random', *, image_shape: tuple[int, int] | None = None, seed: int = 0,
|
| 208 |
+
negative_slope: float = NEGATIVE_SLOPE) -> None:
|
| 209 |
+
super().__init__()
|
| 210 |
+
_check_int('seed', seed, 0, 2**31 - 1)
|
| 211 |
+
if isinstance(negative_slope, bool) or not isinstance(negative_slope, (int, float)) or not 0.0 <= negative_slope < 1.0:
|
| 212 |
+
raise ValueError('negative_slope must be in [0, 1)')
|
| 213 |
+
fields = sample_receptive_fields(in_features, somas, dendrites_per_soma, synapses_per_dendrite, sampling,
|
| 214 |
+
image_shape=image_shape, rng=np.random.default_rng(seed + _MASK_OFFSET))
|
| 215 |
+
self.in_features, self.somas = in_features, somas
|
| 216 |
+
self.dendrites_per_soma, self.synapses_per_dendrite = dendrites_per_soma, synapses_per_dendrite
|
| 217 |
+
self.sampling, self.seed, self.negative_slope = sampling, seed, float(negative_slope)
|
| 218 |
+
self.image_shape = _image_shape(in_features, image_shape)
|
| 219 |
+
n_dend = somas * dendrites_per_soma
|
| 220 |
+
mask = torch.zeros(n_dend, in_features)
|
| 221 |
+
mask[torch.arange(n_dend).unsqueeze(1), torch.from_numpy(fields)] = 1.0
|
| 222 |
+
self.register_buffer('synaptic_mask', mask)
|
| 223 |
+
self.register_buffer('fields', torch.from_numpy(fields))
|
| 224 |
+
g = torch.Generator().manual_seed(seed + _INIT_OFFSET)
|
| 225 |
+
bs, bc = 1.0 / math.sqrt(synapses_per_dendrite), 1.0 / math.sqrt(dendrites_per_soma)
|
| 226 |
+
self.synaptic_weight = nn.Parameter(torch.empty(n_dend, in_features).uniform_(-bs, bs, generator=g) * mask)
|
| 227 |
+
self.dendritic_bias = nn.Parameter(torch.empty(n_dend).uniform_(-bs, bs, generator=g))
|
| 228 |
+
self.cable_weight = nn.Parameter(torch.empty(somas, dendrites_per_soma).uniform_(-bc, bc, generator=g))
|
| 229 |
+
self.soma_bias = nn.Parameter(torch.empty(somas).uniform_(-bc, bc, generator=g))
|
| 230 |
+
|
| 231 |
+
def dendritic_activity(self, x: torch.Tensor) -> torch.Tensor:
|
| 232 |
+
if not isinstance(x, torch.Tensor) or x.ndim != 2 or x.shape[1] != self.in_features:
|
| 233 |
+
raise ValueError(f'x must be a tensor of shape (batch, {self.in_features})')
|
| 234 |
+
return F.leaky_relu(F.linear(x, self.synaptic_weight * self.synaptic_mask, self.dendritic_bias),
|
| 235 |
+
self.negative_slope)
|
| 236 |
+
|
| 237 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 238 |
+
d = self.dendritic_activity(x).view(-1, self.somas, self.dendrites_per_soma)
|
| 239 |
+
return F.leaky_relu((d * self.cable_weight).sum(-1) + self.soma_bias, self.negative_slope)
|
| 240 |
+
|
| 241 |
+
@torch.no_grad()
|
| 242 |
+
def enforce_mask(self) -> None:
|
| 243 |
+
"""Re-apply ``W <- W * M`` (a no-op unless something wrote into masked weights)."""
|
| 244 |
+
self.synaptic_weight.mul_(self.synaptic_mask)
|
| 245 |
+
|
| 246 |
+
def cable_mask(self) -> torch.Tensor:
|
| 247 |
+
"""Dense 0/1 soma-by-dendrite connectivity implied by the tree (each dendrite -> one soma)."""
|
| 248 |
+
return torch.repeat_interleave(torch.eye(self.somas), self.dendrites_per_soma, dim=1)
|
| 249 |
+
|
| 250 |
+
def parameter_count(self) -> int:
|
| 251 |
+
"""Trainable parameters that exist in the model: unmasked synapses, biases, cable weights."""
|
| 252 |
+
return int(self.synaptic_mask.sum().item()) + self.dendritic_bias.numel() + self.cable_weight.numel() \
|
| 253 |
+
+ self.soma_bias.numel()
|
| 254 |
+
|
| 255 |
+
def mask_density(self) -> float:
|
| 256 |
+
return float(self.synaptic_mask.mean().item())
|
| 257 |
+
|
| 258 |
+
def macs(self) -> int:
|
| 259 |
+
"""Multiply-accumulates per example that a sparse implementation would need (masked entries excluded)."""
|
| 260 |
+
return int(self.synaptic_mask.sum().item()) + self.cable_weight.numel()
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
class DendriticNet(nn.Module):
|
| 264 |
+
"""``DendriticLayer`` followed by a dense linear read-out over the somata."""
|
| 265 |
+
|
| 266 |
+
def __init__(self, in_features: int, classes: int, somas: int, dendrites_per_soma: int, synapses_per_dendrite: int,
|
| 267 |
+
sampling: str = 'random', *, image_shape: tuple[int, int] | None = None, seed: int = 0) -> None:
|
| 268 |
+
super().__init__()
|
| 269 |
+
_check_int('classes', classes, 2, 1 << 16)
|
| 270 |
+
self.dendritic = DendriticLayer(in_features, somas, dendrites_per_soma, synapses_per_dendrite, sampling,
|
| 271 |
+
image_shape=image_shape, seed=seed)
|
| 272 |
+
g = torch.Generator().manual_seed(seed + _INIT_OFFSET + 1)
|
| 273 |
+
self.readout = _Linear(somas, classes, g)
|
| 274 |
+
|
| 275 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 276 |
+
return self.readout(self.dendritic(x))
|
| 277 |
+
|
| 278 |
+
def enforce_mask(self) -> None:
|
| 279 |
+
self.dendritic.enforce_mask()
|
| 280 |
+
|
| 281 |
+
def parameter_count(self) -> int:
|
| 282 |
+
return self.dendritic.parameter_count() + self.readout.weight.numel() + self.readout.bias.numel()
|
| 283 |
+
|
| 284 |
+
def macs(self) -> int:
|
| 285 |
+
return self.dendritic.macs() + self.readout.weight.numel()
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def dense_parameter_count(in_features: int, classes: int, hidden: int) -> int:
|
| 289 |
+
"""Trainable parameters of ``DenseMLP(in_features, classes, hidden)``."""
|
| 290 |
+
return in_features * hidden + hidden + hidden * hidden + hidden + hidden * classes + classes
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def dann_parameter_count(somas: int, dendrites_per_soma: int, synapses_per_dendrite: int, classes: int) -> int:
|
| 294 |
+
"""Trainable parameters of ``DendriticNet`` (existing synapses, dendritic biases, cable weights, somatic
|
| 295 |
+
biases, read-out); independent of the input size and of the sampling mode."""
|
| 296 |
+
dendrites = somas * dendrites_per_soma
|
| 297 |
+
return dendrites * synapses_per_dendrite + 2 * dendrites + somas + somas * classes + classes
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
class DenseMLP(nn.Module):
|
| 301 |
+
"""Dense control: two hidden layers of width ``hidden`` with the same leaky ReLU, then a linear read-out."""
|
| 302 |
+
|
| 303 |
+
def __init__(self, in_features: int, classes: int, hidden: int, *, seed: int = 0) -> None:
|
| 304 |
+
super().__init__()
|
| 305 |
+
self.in_features = _check_int('in_features', in_features, 1, 1 << 20)
|
| 306 |
+
_check_int('classes', classes, 2, 1 << 16)
|
| 307 |
+
self.hidden = _check_int('hidden', hidden, 1, 1 << 14)
|
| 308 |
+
_check_int('seed', seed, 0, 2**31 - 1)
|
| 309 |
+
g = torch.Generator().manual_seed(seed + _INIT_OFFSET + 2)
|
| 310 |
+
self.fc1, self.fc2, self.readout = _Linear(in_features, hidden, g), _Linear(hidden, hidden, g), _Linear(hidden, classes, g)
|
| 311 |
+
|
| 312 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 313 |
+
if not isinstance(x, torch.Tensor) or x.ndim != 2 or x.shape[1] != self.in_features:
|
| 314 |
+
raise ValueError(f'x must be a tensor of shape (batch, {self.in_features})')
|
| 315 |
+
h = F.leaky_relu(self.fc1(x), NEGATIVE_SLOPE)
|
| 316 |
+
return self.readout(F.leaky_relu(self.fc2(h), NEGATIVE_SLOPE))
|
| 317 |
+
|
| 318 |
+
def parameter_count(self) -> int:
|
| 319 |
+
return int(sum(p.numel() for p in self.parameters() if p.requires_grad))
|
| 320 |
+
|
| 321 |
+
def macs(self) -> int:
|
| 322 |
+
return int(self.fc1.weight.numel() + self.fc2.weight.numel() + self.readout.weight.numel())
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def matched_dense_hidden(target_params: int, in_features: int, classes: int) -> int:
|
| 326 |
+
"""Width whose ``DenseMLP`` parameter count is closest to ``target_params``."""
|
| 327 |
+
_check_int('target_params', target_params, 1, 1 << 40)
|
| 328 |
+
best, gap = 1, None
|
| 329 |
+
for h in range(1, 1 << 14):
|
| 330 |
+
n = dense_parameter_count(in_features, classes, h)
|
| 331 |
+
if gap is None or abs(n - target_params) < gap:
|
| 332 |
+
best, gap = h, abs(n - target_params)
|
| 333 |
+
if n > target_params:
|
| 334 |
+
break
|
| 335 |
+
return best
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
# ====================================================================== glyph data
|
| 339 |
+
def _segment_distance(points: np.ndarray, segs: np.ndarray) -> np.ndarray:
|
| 340 |
+
"""Distance from each point (P, 2) to the nearest segment (K, 2, 2)."""
|
| 341 |
+
a, b = segs[:, 0][None], segs[:, 1][None] # (1, K, 2)
|
| 342 |
+
p = points[:, None, :] # (P, 1, 2)
|
| 343 |
+
ab = b - a
|
| 344 |
+
t = np.clip(((p - a) * ab).sum(-1) / np.maximum((ab * ab).sum(-1), 1e-12), 0.0, 1.0)
|
| 345 |
+
proj = a + t[..., None] * ab
|
| 346 |
+
return np.sqrt(((p - proj) ** 2).sum(-1)).min(axis=1)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
_PIXELS = np.stack(np.meshgrid(np.arange(GLYPH_SIDE) + 0.5, np.arange(GLYPH_SIDE) + 0.5, indexing='xy'), -1).reshape(-1, 2)
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def render_glyph(label: int, rng: np.random.Generator, *, noise: float = 0.0, shift: float = 2.0,
|
| 353 |
+
size: tuple[float, float] = (6.0, 8.5), thickness: tuple[float, float] = (0.35, 0.9),
|
| 354 |
+
rotation: float = 0.25) -> np.ndarray:
|
| 355 |
+
"""One anti-aliased 12x12 glyph (flattened, float64) with random placement, scale, rotation (radians),
|
| 356 |
+
half stroke width and additive Gaussian pixel noise."""
|
| 357 |
+
_check_int('label', label, 0, len(GLYPH_NAMES) - 1)
|
| 358 |
+
segs = _SEGMENTS[GLYPH_NAMES[label]]
|
| 359 |
+
s = rng.uniform(*size)
|
| 360 |
+
theta = rng.uniform(-rotation, rotation)
|
| 361 |
+
cx, cy = GLYPH_SIDE / 2 + rng.uniform(-shift, shift, size=2)
|
| 362 |
+
half = rng.uniform(*thickness)
|
| 363 |
+
rot = np.array([[math.cos(theta), -math.sin(theta)], [math.sin(theta), math.cos(theta)]])
|
| 364 |
+
placed = ((segs - 0.5) * s) @ rot.T + np.array([cx, cy])
|
| 365 |
+
img = np.clip(half + 0.5 - _segment_distance(_PIXELS, placed), 0.0, 1.0)
|
| 366 |
+
if noise > 0:
|
| 367 |
+
img = img + rng.normal(0.0, noise, size=img.shape)
|
| 368 |
+
return img
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def make_glyph_dataset(n_per_class: int, *, seed: int, noise: float = 0.2, **render_kw: Any
|
| 372 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 373 |
+
"""Balanced, shuffled glyph set: ``x`` float32 ``(10 * n_per_class, 144)``, ``y`` int64 labels."""
|
| 374 |
+
_check_int('n_per_class', n_per_class, 1, 1 << 20)
|
| 375 |
+
_check_int('seed', seed, 0, 2**40)
|
| 376 |
+
if isinstance(noise, bool) or not isinstance(noise, (int, float)) or not 0.0 <= noise <= 10.0:
|
| 377 |
+
raise ValueError('noise must be in [0, 10]')
|
| 378 |
+
rng = np.random.default_rng(seed)
|
| 379 |
+
labels = np.repeat(np.arange(len(GLYPH_NAMES)), n_per_class)
|
| 380 |
+
labels = labels[rng.permutation(labels.size)]
|
| 381 |
+
x = np.stack([render_glyph(int(c), rng, noise=float(noise), **render_kw) for c in labels])
|
| 382 |
+
return torch.from_numpy(x.astype(np.float32)), torch.from_numpy(labels.astype(np.int64))
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
# ====================================================================== training / evaluation
|
| 386 |
+
@torch.no_grad()
|
| 387 |
+
def accuracy(model: nn.Module, x: torch.Tensor, y: torch.Tensor) -> float:
|
| 388 |
+
model.eval()
|
| 389 |
+
return float((model(x).argmax(-1) == y).float().mean())
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
@functools.lru_cache(maxsize=1)
|
| 393 |
+
def _fused_adam_available() -> bool:
|
| 394 |
+
"""Whether this torch build runs the fused CPU Adam kernel (several times faster for tiny models)."""
|
| 395 |
+
try:
|
| 396 |
+
p = nn.Parameter(torch.zeros(2))
|
| 397 |
+
p.grad = torch.ones(2)
|
| 398 |
+
torch.optim.Adam([p], lr=1e-3, fused=True).step()
|
| 399 |
+
return bool(torch.isfinite(p).all())
|
| 400 |
+
except (RuntimeError, TypeError, ValueError):
|
| 401 |
+
return False
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def train_classifier(model: nn.Module, x: torch.Tensor, y: torch.Tensor, *, updates: int, batch_size: int, lr: float,
|
| 405 |
+
generator: torch.Generator) -> dict[str, Any]:
|
| 406 |
+
"""Adam on cross-entropy over a deterministic shuffled minibatch stream; masks re-applied after each step."""
|
| 407 |
+
_check_int('updates', updates, 1, 1 << 20)
|
| 408 |
+
_check_int('batch_size', batch_size, 1, 1 << 16)
|
| 409 |
+
if not isinstance(lr, (int, float)) or isinstance(lr, bool) or not 0.0 < float(lr) <= 1.0:
|
| 410 |
+
raise ValueError('lr must be a number in (0, 1]')
|
| 411 |
+
if x.ndim != 2 or y.ndim != 1 or x.shape[0] != y.shape[0] or x.shape[0] < 1:
|
| 412 |
+
raise ValueError('x must be (n, features) and y (n,) with n >= 1')
|
| 413 |
+
opt = torch.optim.Adam(model.parameters(), lr=float(lr), **({'fused': True} if _fused_adam_available() else {}))
|
| 414 |
+
enforce = getattr(model, 'enforce_mask', None)
|
| 415 |
+
order = torch.empty(0, dtype=torch.long)
|
| 416 |
+
losses = []
|
| 417 |
+
model.train()
|
| 418 |
+
for _ in range(updates):
|
| 419 |
+
if order.numel() < batch_size:
|
| 420 |
+
order = torch.cat([order, torch.randperm(x.shape[0], generator=generator)])
|
| 421 |
+
idx, order = order[:batch_size], order[batch_size:]
|
| 422 |
+
loss = F.cross_entropy(model(x[idx]), y[idx])
|
| 423 |
+
opt.zero_grad(set_to_none=True)
|
| 424 |
+
loss.backward()
|
| 425 |
+
opt.step()
|
| 426 |
+
if enforce is not None:
|
| 427 |
+
enforce()
|
| 428 |
+
losses.append(float(loss.detach()))
|
| 429 |
+
return {'updates': updates, 'final_loss': float(np.mean(losses[-max(1, len(losses) // 10):]))}
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
# ====================================================================== experiment
|
| 433 |
+
DEFAULTS: dict[str, Any] = {
|
| 434 |
+
'train_per_class': 60, 'val_per_class': 50, 'test_per_class': 200, 'noise': 0.2, 'extra_noise': 0.5,
|
| 435 |
+
'somas': 16, 'dendrites_per_soma': 8, 'synapses_per_dendrite': 9,
|
| 436 |
+
'updates': 1000, 'batch_size': 64, 'lr': 3e-3, 'param_tolerance': 0.10,
|
| 437 |
+
}
|
| 438 |
+
QUICK: dict[str, Any] = {**DEFAULTS, 'train_per_class': 40, 'val_per_class': 20, 'test_per_class': 50, 'updates': 250}
|
| 439 |
+
_INT_KEYS = {'train_per_class': (2, 100_000), 'val_per_class': (2, 100_000), 'test_per_class': (2, 100_000),
|
| 440 |
+
'somas': (1, 4096), 'dendrites_per_soma': (1, GLYPH_SIDE ** 2),
|
| 441 |
+
'synapses_per_dendrite': (1, GLYPH_SIDE ** 2), 'updates': (1, 1_000_000), 'batch_size': (1, 65_536)}
|
| 442 |
+
_FLOAT_KEYS = {'noise': (0.0, 5.0), 'extra_noise': (0.0, 5.0), 'lr': (1e-6, 1.0), 'param_tolerance': (0.0, 1.0)}
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def _config(quick: bool, overrides: Mapping[str, Any]) -> dict[str, Any]:
|
| 446 |
+
cfg = dict(QUICK if quick else DEFAULTS)
|
| 447 |
+
unknown = set(overrides) - set(cfg)
|
| 448 |
+
if unknown:
|
| 449 |
+
raise ValueError(f'unknown dendritic_layer options: {sorted(unknown)}')
|
| 450 |
+
cfg.update(overrides)
|
| 451 |
+
for k, (lo, hi) in _INT_KEYS.items():
|
| 452 |
+
_check_int(k, cfg[k], lo, hi)
|
| 453 |
+
for k, (lo, hi) in _FLOAT_KEYS.items():
|
| 454 |
+
v = cfg[k]
|
| 455 |
+
if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(float(v)) or not lo <= v <= hi:
|
| 456 |
+
raise ValueError(f'{k} must be a number in [{lo}, {hi}]')
|
| 457 |
+
cfg[k] = float(v)
|
| 458 |
+
return cfg
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
@contextlib.contextmanager
|
| 462 |
+
def _single_thread() -> Iterator[None]:
|
| 463 |
+
previous = torch.get_num_threads()
|
| 464 |
+
try:
|
| 465 |
+
if previous != 1:
|
| 466 |
+
torch.set_num_threads(1)
|
| 467 |
+
yield
|
| 468 |
+
finally:
|
| 469 |
+
if torch.get_num_threads() != previous:
|
| 470 |
+
torch.set_num_threads(previous)
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def _seed_data(seed: int, cfg: Mapping[str, Any]) -> dict[str, tuple[torch.Tensor, torch.Tensor]]:
|
| 474 |
+
base = seed * 10 + _DATA_OFFSET
|
| 475 |
+
data = {'train': make_glyph_dataset(cfg['train_per_class'], seed=base, noise=cfg['noise']),
|
| 476 |
+
'val': make_glyph_dataset(cfg['val_per_class'], seed=base + 1, noise=cfg['noise']),
|
| 477 |
+
'test': make_glyph_dataset(cfg['test_per_class'], seed=base + 2, noise=cfg['noise'])}
|
| 478 |
+
xt, yt = data['test']
|
| 479 |
+
g = torch.Generator().manual_seed(seed + _NOISE_OFFSET)
|
| 480 |
+
data['test_noisy'] = (xt + cfg['extra_noise'] * torch.randn(xt.shape, generator=g), yt)
|
| 481 |
+
return data
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
def _budget(cfg: Mapping[str, Any]) -> dict[str, Any]:
|
| 485 |
+
"""Parameter budget of every arm, computed before any training; ``ValueError`` when the dense control
|
| 486 |
+
cannot be matched within ``param_tolerance`` (e.g. a dANN smaller than the narrowest dense MLP)."""
|
| 487 |
+
in_features, classes = GLYPH_SIDE ** 2, len(GLYPH_NAMES)
|
| 488 |
+
target = dann_parameter_count(cfg['somas'], cfg['dendrites_per_soma'], cfg['synapses_per_dendrite'], classes)
|
| 489 |
+
hidden = matched_dense_hidden(target, in_features, classes)
|
| 490 |
+
dense = dense_parameter_count(in_features, classes, hidden)
|
| 491 |
+
gap = abs(dense - target) / target
|
| 492 |
+
if gap > cfg['param_tolerance']:
|
| 493 |
+
raise ValueError(f'the dense MLP cannot match the dANN budget: {dense} vs {target} parameters '
|
| 494 |
+
f'(gap {gap:.3f} > param_tolerance {cfg["param_tolerance"]})')
|
| 495 |
+
params = {f'dann_{m}': target for m in SAMPLING_MODES}
|
| 496 |
+
params['dense_mlp'] = dense
|
| 497 |
+
return {'trainable_parameters': params, 'dense_hidden': hidden, 'max_relative_gap': gap}
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
def _run_seed(seed: int, cfg: dict[str, Any], hidden: int) -> dict[str, Any]:
|
| 501 |
+
data = _seed_data(seed, cfg)
|
| 502 |
+
x_train, y_train = data['train']
|
| 503 |
+
in_features, classes = x_train.shape[1], len(GLYPH_NAMES)
|
| 504 |
+
shape = dict(somas=cfg['somas'], dendrites_per_soma=cfg['dendrites_per_soma'],
|
| 505 |
+
synapses_per_dendrite=cfg['synapses_per_dendrite'])
|
| 506 |
+
models: dict[str, nn.Module] = {f'dann_{m}': DendriticNet(in_features, classes, sampling=m, seed=seed, **shape)
|
| 507 |
+
for m in SAMPLING_MODES}
|
| 508 |
+
models['dense_mlp'] = DenseMLP(in_features, classes, hidden, seed=seed)
|
| 509 |
+
arms = {}
|
| 510 |
+
for name, model in models.items():
|
| 511 |
+
gen = torch.Generator().manual_seed(seed + _STREAM_OFFSET) # same minibatch order for every arm
|
| 512 |
+
t0 = time.perf_counter()
|
| 513 |
+
log = train_classifier(model, x_train, y_train, updates=cfg['updates'], batch_size=cfg['batch_size'],
|
| 514 |
+
lr=cfg['lr'], generator=gen)
|
| 515 |
+
t1 = time.perf_counter()
|
| 516 |
+
metrics = {split: accuracy(model, *data[split]) for split in ('train', 'val', 'test', 'test_noisy')}
|
| 517 |
+
arm = {'seed': int(seed), 'parameters': model.parameter_count(), 'estimated_macs_per_example': model.macs(),
|
| 518 |
+
'training': log, 'train_accuracy': metrics['train'], 'val_accuracy': metrics['val'],
|
| 519 |
+
'heldout_accuracy': metrics['test'], 'heldout_noisy_accuracy': metrics['test_noisy'],
|
| 520 |
+
'measured_wallclock_s': {'train': t1 - t0, 'eval': time.perf_counter() - t1}}
|
| 521 |
+
if isinstance(model, DendriticNet):
|
| 522 |
+
layer = model.dendritic
|
| 523 |
+
arm['mask_density'] = layer.mask_density()
|
| 524 |
+
arm['masked_weights_nonzero'] = int((layer.synaptic_weight.detach() * (1 - layer.synaptic_mask)).ne(0).sum())
|
| 525 |
+
arms[name] = arm
|
| 526 |
+
return {'arms': arms}
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
def _summary(per_seed: list[dict[str, Any]]) -> dict[str, float]:
|
| 530 |
+
keys = ('train_accuracy', 'val_accuracy', 'heldout_accuracy', 'heldout_noisy_accuracy')
|
| 531 |
+
return {k: float(np.mean([a[k] for a in per_seed])) for k in keys}
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def run_experiment(*, quick: bool = False, seeds: Iterable[int] = (0, 1, 2), **overrides: Any) -> dict[str, Any]:
|
| 535 |
+
"""dANN (random / local / global sampling) vs a parameter-matched dense MLP on procedural glyphs.
|
| 536 |
+
|
| 537 |
+
Returns a sealed frontier receipt. ``overrides`` may change any key of ``DEFAULTS``."""
|
| 538 |
+
if type(quick) is not bool:
|
| 539 |
+
raise ValueError('quick must be a boolean')
|
| 540 |
+
seeds = tuple(seeds)
|
| 541 |
+
if not seeds or any(type(s) is not int or not 0 <= s <= 2**31 - 1 for s in seeds) or len(set(seeds)) != len(seeds):
|
| 542 |
+
raise ValueError('seeds must be unique non-negative ints')
|
| 543 |
+
cfg = _config(quick, overrides)
|
| 544 |
+
budget = _budget(cfg) # ValueError before any training
|
| 545 |
+
params, gap = budget['trainable_parameters'], budget['max_relative_gap']
|
| 546 |
+
t_start = time.perf_counter()
|
| 547 |
+
with _single_thread():
|
| 548 |
+
runs = [_run_seed(s, cfg, budget['dense_hidden']) for s in seeds]
|
| 549 |
+
names = [f'dann_{m}' for m in SAMPLING_MODES] + ['dense_mlp']
|
| 550 |
+
per_arm = {n: [r['arms'][n] for r in runs] for n in names}
|
| 551 |
+
if any(a['parameters'] != params[n] for n in names for a in per_arm[n]):
|
| 552 |
+
raise RuntimeError('built models do not match the computed parameter budget')
|
| 553 |
+
summaries = {n: _summary(per_arm[n]) for n in names}
|
| 554 |
+
dann_names = names[:-1]
|
| 555 |
+
best = max(dann_names, key=lambda n: (summaries[n]['val_accuracy'], -dann_names.index(n)))
|
| 556 |
+
acc = {n: [a['heldout_accuracy'] for a in per_arm[n]] for n in names}
|
| 557 |
+
noisy = {n: [a['heldout_noisy_accuracy'] for a in per_arm[n]] for n in names}
|
| 558 |
+
comparisons = {'best_dann_vs_dense': harness.compare(acc[best], acc['dense_mlp']),
|
| 559 |
+
'best_dann_vs_dense_noisy': harness.compare(noisy[best], noisy['dense_mlp'])}
|
| 560 |
+
for n in dann_names:
|
| 561 |
+
comparisons[f'{n}_vs_dense'] = harness.compare(acc[n], acc['dense_mlp'])
|
| 562 |
+
comparisons[f'{n}_vs_dense_noisy'] = harness.compare(noisy[n], noisy['dense_mlp'])
|
| 563 |
+
receipt = harness.base_receipt(MODULE_ID, 'model_comparison', {
|
| 564 |
+
**cfg, 'quick': quick, 'seeds': list(seeds), 'task': 'procedural_glyphs_12x12_10_classes',
|
| 565 |
+
'glyphs': list(GLYPH_NAMES), 'metric': 'heldout_accuracy', 'robustness_metric': 'heldout_noisy_accuracy',
|
| 566 |
+
'render': {'shift_px': 2.0, 'size_px': [6.0, 8.5], 'half_thickness_px': [0.35, 0.9], 'rotation_rad': 0.25},
|
| 567 |
+
'optimizer': 'Adam', 'nonlinearity': f'leaky_relu({NEGATIVE_SLOPE})', 'torch_threads': 1})
|
| 568 |
+
receipt['parameter_budget'] = {'trainable_parameters': params, 'dense_hidden': budget['dense_hidden'],
|
| 569 |
+
'max_relative_gap': gap, 'tolerance': cfg['param_tolerance'],
|
| 570 |
+
'within_tolerance': bool(gap <= cfg['param_tolerance']),
|
| 571 |
+
'dann_mask_density': per_arm['dann_random'][0]['mask_density'],
|
| 572 |
+
'counting': 'dANN counts only unmasked synapses + biases + cable + read-out'}
|
| 573 |
+
receipt['arms'] = {n: {'per_seed': per_arm[n], 'summary': summaries[n]} for n in names}
|
| 574 |
+
receipt['best_dann'] = {'arm': best, 'selected_by': 'highest mean validation accuracy (held-out set unused)'}
|
| 575 |
+
receipt['comparisons'] = comparisons
|
| 576 |
+
receipt['verdict'] = comparisons['best_dann_vs_dense']['verdict']
|
| 577 |
+
receipt['verdict_basis'] = f'best_dann({best})_vs_dense_mlp: paired 95% t interval on held-out accuracy over seeds'
|
| 578 |
+
receipt['robustness_verdict'] = comparisons['best_dann_vs_dense_noisy']['verdict']
|
| 579 |
+
receipt['estimated_cost'] = {'macs_per_example': {n: per_arm[n][0]['estimated_macs_per_example'] for n in names},
|
| 580 |
+
'optimizer_updates_per_arm': cfg['updates'],
|
| 581 |
+
'implementation': 'dense masked matmul; sparsity is not exploited for speed'}
|
| 582 |
+
receipt['measured_wallclock_s'] = {'total': time.perf_counter() - t_start}
|
| 583 |
+
receipt['notes'] = (
|
| 584 |
+
'Synthetic glyph benchmark inspired by dendritic ANNs (Chavlis & Poirazi, Nat. Commun. 2025); not a '
|
| 585 |
+
'reproduction (no MNIST/CIFAR, no efficiency scores, no sparse-ANN control). All arms: same data, same '
|
| 586 |
+
'minibatch order, same Adam updates; the dense MLP width is chosen to match trainable parameters. The best '
|
| 587 |
+
'dANN is picked on a separate validation set before the held-out comparison. With few seeds the paired t '
|
| 588 |
+
'interval is wide.')
|
| 589 |
+
return harness.seal(receipt)
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
EXPERIMENTS: dict[str, Callable[..., dict[str, Any]]] = {MODULE_ID: run_experiment}
|